auto_scaling.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 notifiers
  15. import (
  16. "context"
  17. "yunion.io/x/jsonutils"
  18. "yunion.io/x/pkg/errors"
  19. "yunion.io/x/onecloud/pkg/apis/monitor"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. "yunion.io/x/onecloud/pkg/mcclient/auth"
  22. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  23. "yunion.io/x/onecloud/pkg/monitor/alerting"
  24. "yunion.io/x/onecloud/pkg/monitor/models"
  25. "yunion.io/x/onecloud/pkg/monitor/options"
  26. )
  27. func init() {
  28. alerting.RegisterNotifier(&alerting.NotifierPlugin{
  29. Type: monitor.AlertNotificationTypeAutoScaling,
  30. Factory: newAutoScalingNotifier,
  31. ValidateCreateData: func(cred mcclient.IIdentityProvider, input monitor.NotificationCreateInput) (monitor.NotificationCreateInput, error) {
  32. return input, nil
  33. },
  34. })
  35. }
  36. type AutoScalingNotifier struct {
  37. NotifierBase
  38. session *mcclient.ClientSession
  39. }
  40. func newAutoScalingNotifier(config alerting.NotificationConfig) (alerting.Notifier, error) {
  41. return &AutoScalingNotifier{
  42. NotifierBase: NewNotifierBase(config),
  43. session: auth.GetAdminSession(context.Background(), options.Options.Region),
  44. }, nil
  45. }
  46. func (as *AutoScalingNotifier) Notify(ctx *alerting.EvalContext, data jsonutils.JSONObject) error {
  47. scalingPolicyId, _ := data.GetString("scaling_policy_id")
  48. alarmID := ctx.Rule.Id
  49. params := jsonutils.NewDict()
  50. params.Set("alarm_id", jsonutils.NewString(alarmID))
  51. _, err := modules.ScalingPolicy.PerformAction(as.session, scalingPolicyId, "trigger", params)
  52. if err != nil {
  53. return errors.Wrap(err, "Request to trigger ScalingPolicy '%s' failed")
  54. }
  55. return nil
  56. }
  57. func (as *AutoScalingNotifier) ShouldNotify(ctx context.Context, evalContext *alerting.EvalContext,
  58. notificationState *models.SAlertnotification) bool {
  59. if evalContext.NoDataFound {
  60. return false
  61. }
  62. return as.NotifierBase.ShouldNotify(ctx, evalContext, notificationState)
  63. }