alertresourcedrivers.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 models
  15. import (
  16. "yunion.io/x/pkg/errors"
  17. "yunion.io/x/onecloud/pkg/apis/monitor"
  18. )
  19. const (
  20. ErrAlertResourceDriverNotFound = errors.Error("Alert resource driver not found")
  21. ErrAlertResourceDriverDuplicateMatch = errors.Error("Alert resource driver duplicate match")
  22. )
  23. var (
  24. alertResourceDriverFs = make(map[monitor.AlertResourceType]IAlertResourceDriverFactory, 0)
  25. )
  26. type IAlertResourceDriverFactory interface {
  27. // GetType return the driver type
  28. GetType() monitor.AlertResourceType
  29. // IsEvalMatched match driver by monitor.EvalMatch
  30. IsEvalMatched(input monitor.EvalMatch) bool
  31. GetDriver(input monitor.EvalMatch) IAlertResourceDriver
  32. }
  33. type IAlertResourceDriver interface {
  34. // GetType return the driver type
  35. GetType() monitor.AlertResourceType
  36. // GetUniqCond get uniq match conditions from eval match to find AlertResource
  37. GetUniqCond() *AlertResourceUniqCond
  38. }
  39. func RegisterAlertResourceDriverFactory(drvs ...IAlertResourceDriverFactory) {
  40. for _, drv := range drvs {
  41. alertResourceDriverFs[drv.GetType()] = drv
  42. }
  43. }
  44. func GetAlertResourceDriver(match monitor.EvalMatch) (IAlertResourceDriver, error) {
  45. var matchedType monitor.AlertResourceType
  46. matchedDrvs := make(map[monitor.AlertResourceType]IAlertResourceDriverFactory)
  47. for _, drv := range alertResourceDriverFs {
  48. if ok := drv.IsEvalMatched(match); ok {
  49. matchedDrvs[drv.GetType()] = drv
  50. matchedType = drv.GetType()
  51. }
  52. }
  53. if len(matchedDrvs) == 0 {
  54. return nil, errors.Wrapf(ErrAlertResourceDriverNotFound, "match by %v", match)
  55. }
  56. if len(matchedDrvs) > 1 {
  57. return nil, errors.Wrapf(ErrAlertResourceDriverDuplicateMatch, "match by %v", match)
  58. }
  59. return matchedDrvs[matchedType].GetDriver(match), nil
  60. }