plugin.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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. // NotifyLogEvent sends the log event notifications using any defined notifier plugins
  270. func (m *Manager) NotifyLogEvent(event notifier.LogEventType, protocol, username, ip, role string, err error) {
  271. if !m.hasNotifiers {
  272. return
  273. }
  274. m.notifLock.RLock()
  275. defer m.notifLock.RUnlock()
  276. e := &notifier.LogEvent{
  277. Timestamp: time.Now().UnixNano(),
  278. Event: event,
  279. Protocol: protocol,
  280. Username: username,
  281. IP: ip,
  282. Message: err.Error(),
  283. Role: role,
  284. }
  285. for _, n := range m.notifiers {
  286. n.notifyLogEvent(e)
  287. }
  288. }
  289. // HasSearcher returns true if an event searcher plugin is defined
  290. func (m *Manager) HasSearcher() bool {
  291. return m.hasSearcher
  292. }
  293. // SearchFsEvents returns the filesystem events matching the specified filters
  294. func (m *Manager) SearchFsEvents(searchFilters *eventsearcher.FsEventSearch) ([]byte, error) {
  295. if !m.hasSearcher {
  296. return nil, ErrNoSearcher
  297. }
  298. m.searcherLock.RLock()
  299. plugin := m.searcher
  300. m.searcherLock.RUnlock()
  301. return plugin.searchear.SearchFsEvents(searchFilters)
  302. }
  303. // SearchProviderEvents returns the provider events matching the specified filters
  304. func (m *Manager) SearchProviderEvents(searchFilters *eventsearcher.ProviderEventSearch) ([]byte, error) {
  305. if !m.hasSearcher {
  306. return nil, ErrNoSearcher
  307. }
  308. m.searcherLock.RLock()
  309. plugin := m.searcher
  310. m.searcherLock.RUnlock()
  311. return plugin.searchear.SearchProviderEvents(searchFilters)
  312. }
  313. // SearchLogEvents returns the log events matching the specified filters
  314. func (m *Manager) SearchLogEvents(searchFilters *eventsearcher.LogEventSearch) ([]byte, error) {
  315. if !m.hasSearcher {
  316. return nil, ErrNoSearcher
  317. }
  318. m.searcherLock.RLock()
  319. plugin := m.searcher
  320. m.searcherLock.RUnlock()
  321. return plugin.searchear.SearchLogEvents(searchFilters)
  322. }
  323. // HasMetadater returns true if a metadata plugin is defined
  324. func (m *Manager) HasMetadater() bool {
  325. return m.hasMetadater
  326. }
  327. // SetModificationTime sets the modification time for the specified object
  328. func (m *Manager) SetModificationTime(storageID, objectPath string, mTime int64) 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.SetModificationTime(storageID, objectPath, mTime)
  336. }
  337. // GetModificationTime returns the modification time for the specified path
  338. func (m *Manager) GetModificationTime(storageID, objectPath string, _ bool) (int64, error) {
  339. if !m.hasMetadater {
  340. return 0, ErrNoMetadater
  341. }
  342. m.metadaterLock.RLock()
  343. plugin := m.metadater
  344. m.metadaterLock.RUnlock()
  345. return plugin.metadater.GetModificationTime(storageID, objectPath)
  346. }
  347. // GetModificationTimes returns the modification times for all the files within the specified folder
  348. func (m *Manager) GetModificationTimes(storageID, objectPath string) (map[string]int64, error) {
  349. if !m.hasMetadater {
  350. return nil, ErrNoMetadater
  351. }
  352. m.metadaterLock.RLock()
  353. plugin := m.metadater
  354. m.metadaterLock.RUnlock()
  355. return plugin.metadater.GetModificationTimes(storageID, objectPath)
  356. }
  357. // RemoveMetadata deletes the metadata stored for the specified object
  358. func (m *Manager) RemoveMetadata(storageID, objectPath string) error {
  359. if !m.hasMetadater {
  360. return ErrNoMetadater
  361. }
  362. m.metadaterLock.RLock()
  363. plugin := m.metadater
  364. m.metadaterLock.RUnlock()
  365. return plugin.metadater.RemoveMetadata(storageID, objectPath)
  366. }
  367. // GetMetadataFolders returns the folders that metadata is associated with
  368. func (m *Manager) GetMetadataFolders(storageID, from string, limit int) ([]string, error) {
  369. if !m.hasMetadater {
  370. return nil, ErrNoMetadater
  371. }
  372. m.metadaterLock.RLock()
  373. plugin := m.metadater
  374. m.metadaterLock.RUnlock()
  375. return plugin.metadater.GetFolders(storageID, limit, from)
  376. }
  377. // IsIPBanned returns true if the IP filter plugin does not allow the specified ip.
  378. // If no IP filter plugin is defined this method returns false
  379. func (m *Manager) IsIPBanned(ip, protocol string) bool {
  380. if !m.hasIPFilter {
  381. return false
  382. }
  383. m.ipFilterLock.RLock()
  384. plugin := m.filter
  385. m.ipFilterLock.RUnlock()
  386. if plugin.exited() {
  387. logger.Warn(logSender, "", "ip filter plugin is not active, cannot check ip %q", ip)
  388. return false
  389. }
  390. return plugin.filter.CheckIP(ip, protocol) != nil
  391. }
  392. // ReloadFilter sends a reload request to the IP filter plugin
  393. func (m *Manager) ReloadFilter() {
  394. if !m.hasIPFilter {
  395. return
  396. }
  397. m.ipFilterLock.RLock()
  398. plugin := m.filter
  399. m.ipFilterLock.RUnlock()
  400. if err := plugin.filter.Reload(); err != nil {
  401. logger.Error(logSender, "", "unable to reload IP filter plugin: %v", err)
  402. }
  403. }
  404. func (m *Manager) kmsEncrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, string, int32, error) {
  405. m.kmsLock.RLock()
  406. plugin := m.kms[kmsID]
  407. m.kmsLock.RUnlock()
  408. return plugin.Encrypt(secret, url, masterKey)
  409. }
  410. func (m *Manager) kmsDecrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, error) {
  411. m.kmsLock.RLock()
  412. plugin := m.kms[kmsID]
  413. m.kmsLock.RUnlock()
  414. return plugin.Decrypt(secret, url, masterKey)
  415. }
  416. // HasAuthScope returns true if there is an auth plugin that support the specified scope
  417. func (m *Manager) HasAuthScope(scope int) bool {
  418. if m.authScopes == -1 {
  419. return false
  420. }
  421. return m.authScopes&scope != 0
  422. }
  423. // Authenticate tries to authenticate the specified user using an external plugin
  424. func (m *Manager) Authenticate(username, password, ip, protocol string, pkey string,
  425. tlsCert *x509.Certificate, authScope int, userAsJSON []byte,
  426. ) ([]byte, error) {
  427. switch authScope {
  428. case AuthScopePassword:
  429. return m.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  430. case AuthScopePublicKey:
  431. return m.checkUserAndPublicKey(username, pkey, ip, protocol, userAsJSON)
  432. case AuthScopeKeyboardInteractive:
  433. return m.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  434. case AuthScopeTLSCertificate:
  435. cert, err := util.EncodeTLSCertToPem(tlsCert)
  436. if err != nil {
  437. logger.Error(logSender, "", "unable to encode tls certificate to pem: %v", err)
  438. return nil, fmt.Errorf("unable to encode tls cert to pem: %w", err)
  439. }
  440. return m.checkUserAndTLSCert(username, cert, ip, protocol, userAsJSON)
  441. default:
  442. return nil, fmt.Errorf("unsupported auth scope: %v", authScope)
  443. }
  444. }
  445. // ExecuteKeyboardInteractiveStep executes a keyboard interactive step
  446. func (m *Manager) ExecuteKeyboardInteractiveStep(req *KeyboardAuthRequest) (*KeyboardAuthResponse, error) {
  447. var plugin *authPlugin
  448. m.authLock.Lock()
  449. for _, p := range m.auths {
  450. if p.config.AuthOptions.Scope&AuthScopePassword != 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 keyaboard interactive authentication step")
  458. }
  459. return plugin.sendKeyboardIteractiveRequest(req)
  460. }
  461. func (m *Manager) checkUserAndPass(username, password, 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&AuthScopePassword != 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 password checking")
  473. }
  474. return plugin.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  475. }
  476. func (m *Manager) checkUserAndPublicKey(username, pubKey, 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&AuthScopePublicKey != 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 public key checking")
  488. }
  489. return plugin.checkUserAndPublicKey(username, pubKey, ip, protocol, userAsJSON)
  490. }
  491. func (m *Manager) checkUserAndTLSCert(username, tlsCert, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  492. var plugin *authPlugin
  493. m.authLock.Lock()
  494. for _, p := range m.auths {
  495. if p.config.AuthOptions.Scope&AuthScopeTLSCertificate != 0 {
  496. plugin = p
  497. break
  498. }
  499. }
  500. m.authLock.Unlock()
  501. if plugin == nil {
  502. return nil, errors.New("no auth plugin configured for TLS certificate checking")
  503. }
  504. return plugin.checkUserAndTLSCertificate(username, tlsCert, ip, protocol, userAsJSON)
  505. }
  506. func (m *Manager) checkUserAndKeyboardInteractive(username, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  507. var plugin *authPlugin
  508. m.authLock.Lock()
  509. for _, p := range m.auths {
  510. if p.config.AuthOptions.Scope&AuthScopeKeyboardInteractive != 0 {
  511. plugin = p
  512. break
  513. }
  514. }
  515. m.authLock.Unlock()
  516. if plugin == nil {
  517. return nil, errors.New("no auth plugin configured for keyboard interactive checking")
  518. }
  519. return plugin.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  520. }
  521. func (m *Manager) checkCrashedPlugins() {
  522. m.notifLock.RLock()
  523. for idx, n := range m.notifiers {
  524. if n.exited() {
  525. defer func(cfg Config, index int) {
  526. Handler.restartNotifierPlugin(cfg, index)
  527. }(n.config, idx)
  528. } else {
  529. n.sendQueuedEvents()
  530. }
  531. }
  532. m.notifLock.RUnlock()
  533. m.kmsLock.RLock()
  534. for idx, k := range m.kms {
  535. if k.exited() {
  536. defer func(cfg Config, index int) {
  537. Handler.restartKMSPlugin(cfg, index)
  538. }(k.config, idx)
  539. }
  540. }
  541. m.kmsLock.RUnlock()
  542. m.authLock.RLock()
  543. for idx, a := range m.auths {
  544. if a.exited() {
  545. defer func(cfg Config, index int) {
  546. Handler.restartAuthPlugin(cfg, index)
  547. }(a.config, idx)
  548. }
  549. }
  550. m.authLock.RUnlock()
  551. if m.hasSearcher {
  552. m.searcherLock.RLock()
  553. if m.searcher.exited() {
  554. defer func(cfg Config) {
  555. Handler.restartSearcherPlugin(cfg)
  556. }(m.searcher.config)
  557. }
  558. m.searcherLock.RUnlock()
  559. }
  560. if m.hasMetadater {
  561. m.metadaterLock.RLock()
  562. if m.metadater.exited() {
  563. defer func(cfg Config) {
  564. Handler.restartMetadaterPlugin(cfg)
  565. }(m.metadater.config)
  566. }
  567. m.metadaterLock.RUnlock()
  568. }
  569. if m.hasIPFilter {
  570. m.ipFilterLock.RLock()
  571. if m.filter.exited() {
  572. defer func(cfg Config) {
  573. Handler.restartIPFilterPlugin(cfg)
  574. }(m.filter.config)
  575. }
  576. m.ipFilterLock.RUnlock()
  577. }
  578. }
  579. func (m *Manager) restartNotifierPlugin(config Config, idx int) {
  580. if m.closed.Load() {
  581. return
  582. }
  583. logger.Info(logSender, "", "try to restart crashed notifier plugin %q, idx: %v", config.Cmd, idx)
  584. plugin, err := newNotifierPlugin(config)
  585. if err != nil {
  586. logger.Error(logSender, "", "unable to restart notifier plugin %q, err: %v", config.Cmd, err)
  587. return
  588. }
  589. m.notifLock.Lock()
  590. plugin.queue = m.notifiers[idx].queue
  591. m.notifiers[idx] = plugin
  592. m.notifLock.Unlock()
  593. plugin.sendQueuedEvents()
  594. }
  595. func (m *Manager) restartKMSPlugin(config Config, idx int) {
  596. if m.closed.Load() {
  597. return
  598. }
  599. logger.Info(logSender, "", "try to restart crashed kms plugin %q, idx: %v", config.Cmd, idx)
  600. plugin, err := newKMSPlugin(config)
  601. if err != nil {
  602. logger.Error(logSender, "", "unable to restart kms plugin %q, err: %v", config.Cmd, err)
  603. return
  604. }
  605. m.kmsLock.Lock()
  606. m.kms[idx] = plugin
  607. m.kmsLock.Unlock()
  608. }
  609. func (m *Manager) restartAuthPlugin(config Config, idx int) {
  610. if m.closed.Load() {
  611. return
  612. }
  613. logger.Info(logSender, "", "try to restart crashed auth plugin %q, idx: %v", config.Cmd, idx)
  614. plugin, err := newAuthPlugin(config)
  615. if err != nil {
  616. logger.Error(logSender, "", "unable to restart auth plugin %q, err: %v", config.Cmd, err)
  617. return
  618. }
  619. m.authLock.Lock()
  620. m.auths[idx] = plugin
  621. m.authLock.Unlock()
  622. }
  623. func (m *Manager) restartSearcherPlugin(config Config) {
  624. if m.closed.Load() {
  625. return
  626. }
  627. logger.Info(logSender, "", "try to restart crashed searcher plugin %q", config.Cmd)
  628. plugin, err := newSearcherPlugin(config)
  629. if err != nil {
  630. logger.Error(logSender, "", "unable to restart searcher plugin %q, err: %v", config.Cmd, err)
  631. return
  632. }
  633. m.searcherLock.Lock()
  634. m.searcher = plugin
  635. m.searcherLock.Unlock()
  636. }
  637. func (m *Manager) restartMetadaterPlugin(config Config) {
  638. if m.closed.Load() {
  639. return
  640. }
  641. logger.Info(logSender, "", "try to restart crashed metadater plugin %q", config.Cmd)
  642. plugin, err := newMetadaterPlugin(config)
  643. if err != nil {
  644. logger.Error(logSender, "", "unable to restart metadater plugin %q, err: %v", config.Cmd, err)
  645. return
  646. }
  647. m.metadaterLock.Lock()
  648. m.metadater = plugin
  649. m.metadaterLock.Unlock()
  650. }
  651. func (m *Manager) restartIPFilterPlugin(config Config) {
  652. if m.closed.Load() {
  653. return
  654. }
  655. logger.Info(logSender, "", "try to restart crashed IP filter plugin %q", config.Cmd)
  656. plugin, err := newIPFilterPlugin(config)
  657. if err != nil {
  658. logger.Error(logSender, "", "unable to restart IP filter plugin %q, err: %v", config.Cmd, err)
  659. return
  660. }
  661. m.ipFilterLock.Lock()
  662. m.filter = plugin
  663. m.ipFilterLock.Unlock()
  664. }
  665. func (m *Manager) addTask() {
  666. m.concurrencyGuard <- struct{}{}
  667. }
  668. func (m *Manager) removeTask() {
  669. <-m.concurrencyGuard
  670. }
  671. // Cleanup releases all the active plugins
  672. func (m *Manager) Cleanup() {
  673. if m.closed.Swap(true) {
  674. return
  675. }
  676. logger.Debug(logSender, "", "cleanup")
  677. close(m.done)
  678. m.notifLock.Lock()
  679. for _, n := range m.notifiers {
  680. logger.Debug(logSender, "", "cleanup notifier plugin %v", n.config.Cmd)
  681. n.cleanup()
  682. }
  683. m.notifLock.Unlock()
  684. m.kmsLock.Lock()
  685. for _, k := range m.kms {
  686. logger.Debug(logSender, "", "cleanup kms plugin %v", k.config.Cmd)
  687. k.cleanup()
  688. }
  689. m.kmsLock.Unlock()
  690. m.authLock.Lock()
  691. for _, a := range m.auths {
  692. logger.Debug(logSender, "", "cleanup auth plugin %v", a.config.Cmd)
  693. a.cleanup()
  694. }
  695. m.authLock.Unlock()
  696. if m.hasSearcher {
  697. m.searcherLock.Lock()
  698. logger.Debug(logSender, "", "cleanup searcher plugin %v", m.searcher.config.Cmd)
  699. m.searcher.cleanup()
  700. m.searcherLock.Unlock()
  701. }
  702. if m.hasMetadater {
  703. m.metadaterLock.Lock()
  704. logger.Debug(logSender, "", "cleanup metadater plugin %v", m.metadater.config.Cmd)
  705. m.metadater.cleanup()
  706. m.metadaterLock.Unlock()
  707. }
  708. if m.hasIPFilter {
  709. m.ipFilterLock.Lock()
  710. logger.Debug(logSender, "", "cleanup IP filter plugin %v", m.filter.config.Cmd)
  711. m.filter.cleanup()
  712. m.ipFilterLock.Unlock()
  713. }
  714. }
  715. func setLogLevel(logLevel string) {
  716. switch logLevel {
  717. case "info":
  718. pluginsLogLevel = hclog.Info
  719. case "warn":
  720. pluginsLogLevel = hclog.Warn
  721. case "error":
  722. pluginsLogLevel = hclog.Error
  723. default:
  724. pluginsLogLevel = hclog.Debug
  725. }
  726. }
  727. func startCheckTicker() {
  728. logger.Debug(logSender, "", "start plugins checker")
  729. go func() {
  730. ticker := time.NewTicker(30 * time.Second)
  731. defer ticker.Stop()
  732. for {
  733. select {
  734. case <-Handler.done:
  735. logger.Debug(logSender, "", "handler done, stop plugins checker")
  736. return
  737. case <-ticker.C:
  738. Handler.checkCrashedPlugins()
  739. }
  740. }
  741. }()
  742. }