drivers.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package notifydrivers
  15. import (
  16. "context"
  17. "time"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/onecloud/pkg/apis/monitor"
  21. "yunion.io/x/onecloud/pkg/mcclient"
  22. )
  23. const (
  24. ErrUnsupportedNotificationType = errors.Error("Unsupported notification type")
  25. )
  26. // Notifier is responsible for sending alert notifications.
  27. type Notifier interface {
  28. GetType() string
  29. GetNotifierId() string
  30. // GetIsDefault() bool
  31. GetSendReminder() bool
  32. GetDisableResolveMessage() bool
  33. GetFrequency() time.Duration
  34. }
  35. type NotificationConfig struct {
  36. Ctx context.Context
  37. Id string
  38. Name string
  39. Type string
  40. SendReminder bool
  41. DisableResolveMessage bool
  42. Frequency time.Duration
  43. Settings jsonutils.JSONObject
  44. }
  45. type NotifierFactory func(notification NotificationConfig) (Notifier, error)
  46. var notifierFactories = make(map[string]*NotifierPlugin)
  47. type NotifierPlugin struct {
  48. Type string
  49. Factory NotifierFactory
  50. ValidateCreateData func(cred mcclient.IIdentityProvider, input monitor.NotificationCreateInput) (monitor.NotificationCreateInput, error)
  51. }
  52. func RegisterNotifier(plugin *NotifierPlugin) {
  53. notifierFactories[plugin.Type] = plugin
  54. }
  55. func GetNotifiers() []*NotifierPlugin {
  56. list := make([]*NotifierPlugin, 0)
  57. for _, value := range notifierFactories {
  58. list = append(list, value)
  59. }
  60. return list
  61. }
  62. func GetPlugin(typ string) (*NotifierPlugin, error) {
  63. plugin, found := notifierFactories[typ]
  64. if !found {
  65. return nil, errors.Wrapf(ErrUnsupportedNotificationType, "type %s", typ)
  66. }
  67. return plugin, nil
  68. }
  69. // InitNotifier instantiate a new notifier based on the model
  70. func InitNotifier(config NotificationConfig) (Notifier, error) {
  71. plugin, err := GetPlugin(config.Type)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return plugin.Factory(config)
  76. }