plugin.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 provides support for the SFTPGo plugin system
  15. package plugin
  16. import (
  17. "crypto/sha256"
  18. "crypto/x509"
  19. "encoding/hex"
  20. "errors"
  21. "fmt"
  22. "sync"
  23. "sync/atomic"
  24. "time"
  25. "github.com/hashicorp/go-hclog"
  26. "github.com/hashicorp/go-plugin"
  27. "github.com/sftpgo/sdk/plugin/auth"
  28. "github.com/sftpgo/sdk/plugin/eventsearcher"
  29. "github.com/sftpgo/sdk/plugin/ipfilter"
  30. kmsplugin "github.com/sftpgo/sdk/plugin/kms"
  31. "github.com/sftpgo/sdk/plugin/metadata"
  32. "github.com/sftpgo/sdk/plugin/notifier"
  33. "github.com/drakkan/sftpgo/v2/internal/kms"
  34. "github.com/drakkan/sftpgo/v2/internal/logger"
  35. "github.com/drakkan/sftpgo/v2/internal/util"
  36. )
  37. const (
  38. logSender = "plugins"
  39. )
  40. var (
  41. // Handler defines the plugins manager
  42. Handler Manager
  43. pluginsLogLevel = hclog.Debug
  44. // ErrNoSearcher defines the error to return for events searches if no plugin is configured
  45. ErrNoSearcher = errors.New("no events searcher plugin defined")
  46. // ErrNoMetadater returns the error to return for metadata methods if no plugin is configured
  47. ErrNoMetadater = errors.New("no metadata plugin defined")
  48. )
  49. // Renderer defines the interface for generic objects rendering
  50. type Renderer interface {
  51. RenderAsJSON(reload bool) ([]byte, error)
  52. }
  53. // Config defines a plugin configuration
  54. type Config struct {
  55. // Plugin type
  56. Type string `json:"type" mapstructure:"type"`
  57. // NotifierOptions defines options for notifiers plugins
  58. NotifierOptions NotifierConfig `json:"notifier_options" mapstructure:"notifier_options"`
  59. // KMSOptions defines options for a KMS plugin
  60. KMSOptions KMSConfig `json:"kms_options" mapstructure:"kms_options"`
  61. // AuthOptions defines options for authentication plugins
  62. AuthOptions AuthConfig `json:"auth_options" mapstructure:"auth_options"`
  63. // Path to the plugin executable
  64. Cmd string `json:"cmd" mapstructure:"cmd"`
  65. // Args to pass to the plugin executable
  66. Args []string `json:"args" mapstructure:"args"`
  67. // SHA256 checksum for the plugin executable.
  68. // If not empty it will be used to verify the integrity of the executable
  69. SHA256Sum string `json:"sha256sum" mapstructure:"sha256sum"`
  70. // If enabled the client and the server automatically negotiate mTLS for
  71. // transport authentication. This ensures that only the original client will
  72. // be allowed to connect to the server, and all other connections will be
  73. // rejected. The client will also refuse to connect to any server that isn't
  74. // the original instance started by the client.
  75. AutoMTLS bool `json:"auto_mtls" mapstructure:"auto_mtls"`
  76. // unique identifier for kms plugins
  77. kmsID int
  78. }
  79. func (c *Config) getSecureConfig() (*plugin.SecureConfig, error) {
  80. if c.SHA256Sum != "" {
  81. checksum, err := hex.DecodeString(c.SHA256Sum)
  82. if err != nil {
  83. return nil, fmt.Errorf("invalid sha256 hash %q: %w", c.SHA256Sum, err)
  84. }
  85. return &plugin.SecureConfig{
  86. Checksum: checksum,
  87. Hash: sha256.New(),
  88. }, nil
  89. }
  90. return nil, nil
  91. }
  92. func (c *Config) newKMSPluginSecretProvider(base kms.BaseSecret, url, masterKey string) kms.SecretProvider {
  93. return &kmsPluginSecretProvider{
  94. BaseSecret: base,
  95. URL: url,
  96. MasterKey: masterKey,
  97. config: c,
  98. }
  99. }
  100. // Manager handles enabled plugins
  101. type Manager struct {
  102. closed atomic.Bool
  103. done chan bool
  104. // List of configured plugins
  105. Configs []Config `json:"plugins" mapstructure:"plugins"`
  106. notifLock sync.RWMutex
  107. notifiers []*notifierPlugin
  108. kmsLock sync.RWMutex
  109. kms []*kmsPlugin
  110. authLock sync.RWMutex
  111. auths []*authPlugin
  112. searcherLock sync.RWMutex
  113. searcher *searcherPlugin
  114. metadaterLock sync.RWMutex
  115. metadater *metadataPlugin
  116. ipFilterLock sync.RWMutex
  117. filter *ipFilterPlugin
  118. authScopes int
  119. hasSearcher bool
  120. hasMetadater bool
  121. hasNotifiers bool
  122. hasAuths bool
  123. hasIPFilter bool
  124. concurrencyGuard chan struct{}
  125. }
  126. // Initialize initializes the configured plugins
  127. func Initialize(configs []Config, logLevel string) error {
  128. logger.Debug(logSender, "", "initialize")
  129. Handler = Manager{
  130. Configs: configs,
  131. done: make(chan bool),
  132. authScopes: -1,
  133. concurrencyGuard: make(chan struct{}, 250),
  134. }
  135. Handler.closed.Store(false)
  136. setLogLevel(logLevel)
  137. if len(configs) == 0 {
  138. return nil
  139. }
  140. if err := Handler.validateConfigs(); err != nil {
  141. return err
  142. }
  143. if err := initializePlugins(); err != nil {
  144. return err
  145. }
  146. startCheckTicker()
  147. return nil
  148. }
  149. func initializePlugins() error {
  150. kmsID := 0
  151. for idx, config := range Handler.Configs {
  152. switch config.Type {
  153. case notifier.PluginName:
  154. plugin, err := newNotifierPlugin(config)
  155. if err != nil {
  156. return err
  157. }
  158. Handler.notifiers = append(Handler.notifiers, plugin)
  159. case kmsplugin.PluginName:
  160. plugin, err := newKMSPlugin(config)
  161. if err != nil {
  162. return err
  163. }
  164. Handler.kms = append(Handler.kms, plugin)
  165. Handler.Configs[idx].kmsID = kmsID
  166. kmsID++
  167. kms.RegisterSecretProvider(config.KMSOptions.Scheme, config.KMSOptions.EncryptedStatus,
  168. Handler.Configs[idx].newKMSPluginSecretProvider)
  169. logger.Info(logSender, "", "registered secret provider for scheme: %v, encrypted status: %v",
  170. config.KMSOptions.Scheme, config.KMSOptions.EncryptedStatus)
  171. case auth.PluginName:
  172. plugin, err := newAuthPlugin(config)
  173. if err != nil {
  174. return err
  175. }
  176. Handler.auths = append(Handler.auths, plugin)
  177. if Handler.authScopes == -1 {
  178. Handler.authScopes = config.AuthOptions.Scope
  179. } else {
  180. Handler.authScopes |= config.AuthOptions.Scope
  181. }
  182. case eventsearcher.PluginName:
  183. plugin, err := newSearcherPlugin(config)
  184. if err != nil {
  185. return err
  186. }
  187. Handler.searcher = plugin
  188. case metadata.PluginName:
  189. plugin, err := newMetadaterPlugin(config)
  190. if err != nil {
  191. return err
  192. }
  193. Handler.metadater = plugin
  194. case ipfilter.PluginName:
  195. plugin, err := newIPFilterPlugin(config)
  196. if err != nil {
  197. return err
  198. }
  199. Handler.filter = plugin
  200. default:
  201. return fmt.Errorf("unsupported plugin type: %v", config.Type)
  202. }
  203. }
  204. return nil
  205. }
  206. func (m *Manager) validateConfigs() error {
  207. kmsSchemes := make(map[string]bool)
  208. kmsEncryptions := make(map[string]bool)
  209. m.hasSearcher = false
  210. m.hasMetadater = false
  211. m.hasNotifiers = false
  212. m.hasAuths = false
  213. m.hasIPFilter = false
  214. for _, config := range m.Configs {
  215. switch config.Type {
  216. case kmsplugin.PluginName:
  217. if _, ok := kmsSchemes[config.KMSOptions.Scheme]; ok {
  218. return fmt.Errorf("invalid KMS configuration, duplicated scheme %q", config.KMSOptions.Scheme)
  219. }
  220. if _, ok := kmsEncryptions[config.KMSOptions.EncryptedStatus]; ok {
  221. return fmt.Errorf("invalid KMS configuration, duplicated encrypted status %q", config.KMSOptions.EncryptedStatus)
  222. }
  223. kmsSchemes[config.KMSOptions.Scheme] = true
  224. kmsEncryptions[config.KMSOptions.EncryptedStatus] = true
  225. case eventsearcher.PluginName:
  226. if m.hasSearcher {
  227. return errors.New("only one eventsearcher plugin can be defined")
  228. }
  229. m.hasSearcher = true
  230. case metadata.PluginName:
  231. if m.hasMetadater {
  232. return errors.New("only one metadata plugin can be defined")
  233. }
  234. m.hasMetadater = true
  235. case notifier.PluginName:
  236. m.hasNotifiers = true
  237. case auth.PluginName:
  238. m.hasAuths = true
  239. case ipfilter.PluginName:
  240. m.hasIPFilter = true
  241. }
  242. }
  243. return nil
  244. }
  245. // HasAuthenticators returns true if there is at least an auth plugin
  246. func (m *Manager) HasAuthenticators() bool {
  247. return m.hasAuths
  248. }
  249. // HasNotifiers returns true if there is at least a notifier plugin
  250. func (m *Manager) HasNotifiers() bool {
  251. return m.hasNotifiers
  252. }
  253. // NotifyFsEvent sends the fs event notifications using any defined notifier plugins
  254. func (m *Manager) NotifyFsEvent(event *notifier.FsEvent) {
  255. m.notifLock.RLock()
  256. defer m.notifLock.RUnlock()
  257. for _, n := range m.notifiers {
  258. n.notifyFsAction(event)
  259. }
  260. }
  261. // NotifyProviderEvent sends the provider event notifications using any defined notifier plugins
  262. func (m *Manager) NotifyProviderEvent(event *notifier.ProviderEvent, object Renderer) {
  263. m.notifLock.RLock()
  264. defer m.notifLock.RUnlock()
  265. for _, n := range m.notifiers {
  266. n.notifyProviderAction(event, object)
  267. }
  268. }
  269. // HasSearcher returns true if an event searcher plugin is defined
  270. func (m *Manager) HasSearcher() bool {
  271. return m.hasSearcher
  272. }
  273. // SearchFsEvents returns the filesystem events matching the specified filters
  274. func (m *Manager) SearchFsEvents(searchFilters *eventsearcher.FsEventSearch) ([]byte, []string, []string, error) {
  275. if !m.hasSearcher {
  276. return nil, nil, nil, ErrNoSearcher
  277. }
  278. m.searcherLock.RLock()
  279. plugin := m.searcher
  280. m.searcherLock.RUnlock()
  281. return plugin.searchear.SearchFsEvents(searchFilters)
  282. }
  283. // SearchProviderEvents returns the provider events matching the specified filters
  284. func (m *Manager) SearchProviderEvents(searchFilters *eventsearcher.ProviderEventSearch) ([]byte, []string, []string, error) {
  285. if !m.hasSearcher {
  286. return nil, nil, nil, ErrNoSearcher
  287. }
  288. m.searcherLock.RLock()
  289. plugin := m.searcher
  290. m.searcherLock.RUnlock()
  291. return plugin.searchear.SearchProviderEvents(searchFilters)
  292. }
  293. // HasMetadater returns true if a metadata plugin is defined
  294. func (m *Manager) HasMetadater() bool {
  295. return m.hasMetadater
  296. }
  297. // SetModificationTime sets the modification time for the specified object
  298. func (m *Manager) SetModificationTime(storageID, objectPath string, mTime int64) error {
  299. if !m.hasMetadater {
  300. return ErrNoMetadater
  301. }
  302. m.metadaterLock.RLock()
  303. plugin := m.metadater
  304. m.metadaterLock.RUnlock()
  305. return plugin.metadater.SetModificationTime(storageID, objectPath, mTime)
  306. }
  307. // GetModificationTime returns the modification time for the specified path
  308. func (m *Manager) GetModificationTime(storageID, objectPath string, isDir bool) (int64, error) {
  309. if !m.hasMetadater {
  310. return 0, ErrNoMetadater
  311. }
  312. m.metadaterLock.RLock()
  313. plugin := m.metadater
  314. m.metadaterLock.RUnlock()
  315. return plugin.metadater.GetModificationTime(storageID, objectPath)
  316. }
  317. // GetModificationTimes returns the modification times for all the files within the specified folder
  318. func (m *Manager) GetModificationTimes(storageID, objectPath string) (map[string]int64, error) {
  319. if !m.hasMetadater {
  320. return nil, ErrNoMetadater
  321. }
  322. m.metadaterLock.RLock()
  323. plugin := m.metadater
  324. m.metadaterLock.RUnlock()
  325. return plugin.metadater.GetModificationTimes(storageID, objectPath)
  326. }
  327. // RemoveMetadata deletes the metadata stored for the specified object
  328. func (m *Manager) RemoveMetadata(storageID, objectPath string) error {
  329. if !m.hasMetadater {
  330. return ErrNoMetadater
  331. }
  332. m.metadaterLock.RLock()
  333. plugin := m.metadater
  334. m.metadaterLock.RUnlock()
  335. return plugin.metadater.RemoveMetadata(storageID, objectPath)
  336. }
  337. // GetMetadataFolders returns the folders that metadata is associated with
  338. func (m *Manager) GetMetadataFolders(storageID, from string, limit int) ([]string, error) {
  339. if !m.hasMetadater {
  340. return nil, ErrNoMetadater
  341. }
  342. m.metadaterLock.RLock()
  343. plugin := m.metadater
  344. m.metadaterLock.RUnlock()
  345. return plugin.metadater.GetFolders(storageID, limit, from)
  346. }
  347. // IsIPBanned returns true if the IP filter plugin does not allow the specified ip.
  348. // If no IP filter plugin is defined this method returns false
  349. func (m *Manager) IsIPBanned(ip, protocol string) bool {
  350. if !m.hasIPFilter {
  351. return false
  352. }
  353. m.ipFilterLock.RLock()
  354. plugin := m.filter
  355. m.ipFilterLock.RUnlock()
  356. if plugin.exited() {
  357. logger.Warn(logSender, "", "ip filter plugin is not active, cannot check ip %q", ip)
  358. return false
  359. }
  360. return plugin.filter.CheckIP(ip, protocol) != nil
  361. }
  362. // ReloadFilter sends a reload request to the IP filter plugin
  363. func (m *Manager) ReloadFilter() {
  364. if !m.hasIPFilter {
  365. return
  366. }
  367. m.ipFilterLock.RLock()
  368. plugin := m.filter
  369. m.ipFilterLock.RUnlock()
  370. if err := plugin.filter.Reload(); err != nil {
  371. logger.Error(logSender, "", "unable to reload IP filter plugin: %v", err)
  372. }
  373. }
  374. func (m *Manager) kmsEncrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, string, int32, error) {
  375. m.kmsLock.RLock()
  376. plugin := m.kms[kmsID]
  377. m.kmsLock.RUnlock()
  378. return plugin.Encrypt(secret, url, masterKey)
  379. }
  380. func (m *Manager) kmsDecrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, error) {
  381. m.kmsLock.RLock()
  382. plugin := m.kms[kmsID]
  383. m.kmsLock.RUnlock()
  384. return plugin.Decrypt(secret, url, masterKey)
  385. }
  386. // HasAuthScope returns true if there is an auth plugin that support the specified scope
  387. func (m *Manager) HasAuthScope(scope int) bool {
  388. if m.authScopes == -1 {
  389. return false
  390. }
  391. return m.authScopes&scope != 0
  392. }
  393. // Authenticate tries to authenticate the specified user using an external plugin
  394. func (m *Manager) Authenticate(username, password, ip, protocol string, pkey string,
  395. tlsCert *x509.Certificate, authScope int, userAsJSON []byte,
  396. ) ([]byte, error) {
  397. switch authScope {
  398. case AuthScopePassword:
  399. return m.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  400. case AuthScopePublicKey:
  401. return m.checkUserAndPublicKey(username, pkey, ip, protocol, userAsJSON)
  402. case AuthScopeKeyboardInteractive:
  403. return m.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  404. case AuthScopeTLSCertificate:
  405. cert, err := util.EncodeTLSCertToPem(tlsCert)
  406. if err != nil {
  407. logger.Error(logSender, "", "unable to encode tls certificate to pem: %v", err)
  408. return nil, fmt.Errorf("unable to encode tls cert to pem: %w", err)
  409. }
  410. return m.checkUserAndTLSCert(username, cert, ip, protocol, userAsJSON)
  411. default:
  412. return nil, fmt.Errorf("unsupported auth scope: %v", authScope)
  413. }
  414. }
  415. // ExecuteKeyboardInteractiveStep executes a keyboard interactive step
  416. func (m *Manager) ExecuteKeyboardInteractiveStep(req *KeyboardAuthRequest) (*KeyboardAuthResponse, error) {
  417. var plugin *authPlugin
  418. m.authLock.Lock()
  419. for _, p := range m.auths {
  420. if p.config.AuthOptions.Scope&AuthScopePassword != 0 {
  421. plugin = p
  422. break
  423. }
  424. }
  425. m.authLock.Unlock()
  426. if plugin == nil {
  427. return nil, errors.New("no auth plugin configured for keyaboard interactive authentication step")
  428. }
  429. return plugin.sendKeyboardIteractiveRequest(req)
  430. }
  431. func (m *Manager) checkUserAndPass(username, password, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  432. var plugin *authPlugin
  433. m.authLock.Lock()
  434. for _, p := range m.auths {
  435. if p.config.AuthOptions.Scope&AuthScopePassword != 0 {
  436. plugin = p
  437. break
  438. }
  439. }
  440. m.authLock.Unlock()
  441. if plugin == nil {
  442. return nil, errors.New("no auth plugin configured for password checking")
  443. }
  444. return plugin.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  445. }
  446. func (m *Manager) checkUserAndPublicKey(username, pubKey, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  447. var plugin *authPlugin
  448. m.authLock.Lock()
  449. for _, p := range m.auths {
  450. if p.config.AuthOptions.Scope&AuthScopePublicKey != 0 {
  451. plugin = p
  452. break
  453. }
  454. }
  455. m.authLock.Unlock()
  456. if plugin == nil {
  457. return nil, errors.New("no auth plugin configured for public key checking")
  458. }
  459. return plugin.checkUserAndPublicKey(username, pubKey, ip, protocol, userAsJSON)
  460. }
  461. func (m *Manager) checkUserAndTLSCert(username, tlsCert, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  462. var plugin *authPlugin
  463. m.authLock.Lock()
  464. for _, p := range m.auths {
  465. if p.config.AuthOptions.Scope&AuthScopeTLSCertificate != 0 {
  466. plugin = p
  467. break
  468. }
  469. }
  470. m.authLock.Unlock()
  471. if plugin == nil {
  472. return nil, errors.New("no auth plugin configured for TLS certificate checking")
  473. }
  474. return plugin.checkUserAndTLSCertificate(username, tlsCert, ip, protocol, userAsJSON)
  475. }
  476. func (m *Manager) checkUserAndKeyboardInteractive(username, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  477. var plugin *authPlugin
  478. m.authLock.Lock()
  479. for _, p := range m.auths {
  480. if p.config.AuthOptions.Scope&AuthScopeKeyboardInteractive != 0 {
  481. plugin = p
  482. break
  483. }
  484. }
  485. m.authLock.Unlock()
  486. if plugin == nil {
  487. return nil, errors.New("no auth plugin configured for keyboard interactive checking")
  488. }
  489. return plugin.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  490. }
  491. func (m *Manager) checkCrashedPlugins() {
  492. m.notifLock.RLock()
  493. for idx, n := range m.notifiers {
  494. if n.exited() {
  495. defer func(cfg Config, index int) {
  496. Handler.restartNotifierPlugin(cfg, index)
  497. }(n.config, idx)
  498. } else {
  499. n.sendQueuedEvents()
  500. }
  501. }
  502. m.notifLock.RUnlock()
  503. m.kmsLock.RLock()
  504. for idx, k := range m.kms {
  505. if k.exited() {
  506. defer func(cfg Config, index int) {
  507. Handler.restartKMSPlugin(cfg, index)
  508. }(k.config, idx)
  509. }
  510. }
  511. m.kmsLock.RUnlock()
  512. m.authLock.RLock()
  513. for idx, a := range m.auths {
  514. if a.exited() {
  515. defer func(cfg Config, index int) {
  516. Handler.restartAuthPlugin(cfg, index)
  517. }(a.config, idx)
  518. }
  519. }
  520. m.authLock.RUnlock()
  521. if m.hasSearcher {
  522. m.searcherLock.RLock()
  523. if m.searcher.exited() {
  524. defer func(cfg Config) {
  525. Handler.restartSearcherPlugin(cfg)
  526. }(m.searcher.config)
  527. }
  528. m.searcherLock.RUnlock()
  529. }
  530. if m.hasMetadater {
  531. m.metadaterLock.RLock()
  532. if m.metadater.exited() {
  533. defer func(cfg Config) {
  534. Handler.restartMetadaterPlugin(cfg)
  535. }(m.metadater.config)
  536. }
  537. m.metadaterLock.RUnlock()
  538. }
  539. if m.hasIPFilter {
  540. m.ipFilterLock.RLock()
  541. if m.filter.exited() {
  542. defer func(cfg Config) {
  543. Handler.restartIPFilterPlugin(cfg)
  544. }(m.filter.config)
  545. }
  546. m.ipFilterLock.RUnlock()
  547. }
  548. }
  549. func (m *Manager) restartNotifierPlugin(config Config, idx int) {
  550. if m.closed.Load() {
  551. return
  552. }
  553. logger.Info(logSender, "", "try to restart crashed notifier plugin %q, idx: %v", config.Cmd, idx)
  554. plugin, err := newNotifierPlugin(config)
  555. if err != nil {
  556. logger.Error(logSender, "", "unable to restart notifier plugin %q, err: %v", config.Cmd, err)
  557. return
  558. }
  559. m.notifLock.Lock()
  560. plugin.queue = m.notifiers[idx].queue
  561. m.notifiers[idx] = plugin
  562. m.notifLock.Unlock()
  563. plugin.sendQueuedEvents()
  564. }
  565. func (m *Manager) restartKMSPlugin(config Config, idx int) {
  566. if m.closed.Load() {
  567. return
  568. }
  569. logger.Info(logSender, "", "try to restart crashed kms plugin %q, idx: %v", config.Cmd, idx)
  570. plugin, err := newKMSPlugin(config)
  571. if err != nil {
  572. logger.Error(logSender, "", "unable to restart kms plugin %q, err: %v", config.Cmd, err)
  573. return
  574. }
  575. m.kmsLock.Lock()
  576. m.kms[idx] = plugin
  577. m.kmsLock.Unlock()
  578. }
  579. func (m *Manager) restartAuthPlugin(config Config, idx int) {
  580. if m.closed.Load() {
  581. return
  582. }
  583. logger.Info(logSender, "", "try to restart crashed auth plugin %q, idx: %v", config.Cmd, idx)
  584. plugin, err := newAuthPlugin(config)
  585. if err != nil {
  586. logger.Error(logSender, "", "unable to restart auth plugin %q, err: %v", config.Cmd, err)
  587. return
  588. }
  589. m.authLock.Lock()
  590. m.auths[idx] = plugin
  591. m.authLock.Unlock()
  592. }
  593. func (m *Manager) restartSearcherPlugin(config Config) {
  594. if m.closed.Load() {
  595. return
  596. }
  597. logger.Info(logSender, "", "try to restart crashed searcher plugin %q", config.Cmd)
  598. plugin, err := newSearcherPlugin(config)
  599. if err != nil {
  600. logger.Error(logSender, "", "unable to restart searcher plugin %q, err: %v", config.Cmd, err)
  601. return
  602. }
  603. m.searcherLock.Lock()
  604. m.searcher = plugin
  605. m.searcherLock.Unlock()
  606. }
  607. func (m *Manager) restartMetadaterPlugin(config Config) {
  608. if m.closed.Load() {
  609. return
  610. }
  611. logger.Info(logSender, "", "try to restart crashed metadater plugin %q", config.Cmd)
  612. plugin, err := newMetadaterPlugin(config)
  613. if err != nil {
  614. logger.Error(logSender, "", "unable to restart metadater plugin %q, err: %v", config.Cmd, err)
  615. return
  616. }
  617. m.metadaterLock.Lock()
  618. m.metadater = plugin
  619. m.metadaterLock.Unlock()
  620. }
  621. func (m *Manager) restartIPFilterPlugin(config Config) {
  622. if m.closed.Load() {
  623. return
  624. }
  625. logger.Info(logSender, "", "try to restart crashed IP filter plugin %q", config.Cmd)
  626. plugin, err := newIPFilterPlugin(config)
  627. if err != nil {
  628. logger.Error(logSender, "", "unable to restart IP filter plugin %q, err: %v", config.Cmd, err)
  629. return
  630. }
  631. m.ipFilterLock.Lock()
  632. m.filter = plugin
  633. m.ipFilterLock.Unlock()
  634. }
  635. func (m *Manager) addTask() {
  636. m.concurrencyGuard <- struct{}{}
  637. }
  638. func (m *Manager) removeTask() {
  639. <-m.concurrencyGuard
  640. }
  641. // Cleanup releases all the active plugins
  642. func (m *Manager) Cleanup() {
  643. if m.closed.Swap(true) {
  644. return
  645. }
  646. logger.Debug(logSender, "", "cleanup")
  647. close(m.done)
  648. m.notifLock.Lock()
  649. for _, n := range m.notifiers {
  650. logger.Debug(logSender, "", "cleanup notifier plugin %v", n.config.Cmd)
  651. n.cleanup()
  652. }
  653. m.notifLock.Unlock()
  654. m.kmsLock.Lock()
  655. for _, k := range m.kms {
  656. logger.Debug(logSender, "", "cleanup kms plugin %v", k.config.Cmd)
  657. k.cleanup()
  658. }
  659. m.kmsLock.Unlock()
  660. m.authLock.Lock()
  661. for _, a := range m.auths {
  662. logger.Debug(logSender, "", "cleanup auth plugin %v", a.config.Cmd)
  663. a.cleanup()
  664. }
  665. m.authLock.Unlock()
  666. if m.hasSearcher {
  667. m.searcherLock.Lock()
  668. logger.Debug(logSender, "", "cleanup searcher plugin %v", m.searcher.config.Cmd)
  669. m.searcher.cleanup()
  670. m.searcherLock.Unlock()
  671. }
  672. if m.hasMetadater {
  673. m.metadaterLock.Lock()
  674. logger.Debug(logSender, "", "cleanup metadater plugin %v", m.metadater.config.Cmd)
  675. m.metadater.cleanup()
  676. m.metadaterLock.Unlock()
  677. }
  678. if m.hasIPFilter {
  679. m.ipFilterLock.Lock()
  680. logger.Debug(logSender, "", "cleanup IP filter plugin %v", m.filter.config.Cmd)
  681. m.filter.cleanup()
  682. m.ipFilterLock.Unlock()
  683. }
  684. }
  685. func setLogLevel(logLevel string) {
  686. switch logLevel {
  687. case "info":
  688. pluginsLogLevel = hclog.Info
  689. case "warn":
  690. pluginsLogLevel = hclog.Warn
  691. case "error":
  692. pluginsLogLevel = hclog.Error
  693. default:
  694. pluginsLogLevel = hclog.Debug
  695. }
  696. }
  697. func startCheckTicker() {
  698. logger.Debug(logSender, "", "start plugins checker")
  699. go func() {
  700. ticker := time.NewTicker(30 * time.Second)
  701. defer ticker.Stop()
  702. for {
  703. select {
  704. case <-Handler.done:
  705. logger.Debug(logSender, "", "handler done, stop plugins checker")
  706. return
  707. case <-ticker.C:
  708. Handler.checkCrashedPlugins()
  709. }
  710. }
  711. }()
  712. }