plugin.go 21 KB

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