plugin.go 20 KB

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