From ac3b54d7b35ed589f6f22d86dffd36d5a288e185 Mon Sep 17 00:00:00 2001 From: Zexi Li Date: Fri, 16 Sep 2022 10:34:52 +0800 Subject: [PATCH] Automated cherry pick of #14979: fix(monitor,region,climc): use commonalert api for scaling policy (#14986) * fix(monitor,region,climc): use commonalert api for scaling policy * fix(monitor): use commonalert as nodealert's backend --- cmd/climc/shell/monitor/alert.go | 2 +- cmd/climc/shell/monitor/commonalert.go | 3 +- pkg/apis/monitor/alertnotification.go | 7 + pkg/apis/monitor/commalert.go | 27 ++- pkg/apis/monitor/nodealert.go | 90 +++++++-- pkg/compute/models/scaling_trigger.go | 6 +- pkg/mcclient/modules/monitor/helper.go | 68 ++++++- .../modules/monitor/mod_commonalert.go | 15 +- .../modules/monitor/mod_monitor_resource.go | 2 +- pkg/mcclient/options/monitor/alert.go | 2 +- pkg/mcclient/options/monitor/commonalert.go | 42 ++++ pkg/monitor/models/alert.go | 4 + pkg/monitor/models/alertnotification.go | 8 +- pkg/monitor/models/commonalert.go | 66 ++++-- pkg/monitor/models/meteralert.go | 2 +- pkg/monitor/models/nodealert.go | 188 ++++++++++++------ pkg/monitor/tasks/delete_alertrecord_task.go | 7 +- .../tasks/detach_alertresource_task.go | 6 +- .../tasks/detach_monitor_resource_task.go | 6 +- .../tasks/update_monitor_resource_task.go | 7 +- pkg/monitor/validators/validators.go | 6 +- 21 files changed, 414 insertions(+), 150 deletions(-) diff --git a/cmd/climc/shell/monitor/alert.go b/cmd/climc/shell/monitor/alert.go index 98676158c3..0c3f88b0df 100644 --- a/cmd/climc/shell/monitor/alert.go +++ b/cmd/climc/shell/monitor/alert.go @@ -29,7 +29,7 @@ import ( func init() { cmd := NewResourceCmd(monitor.Alerts) cmd.List(new(options.AlertListOptions)) - cmd.Create(new(options.AlertCreateOptions)) + // cmd.Create(new(options.AlertCreateOptions)) cmd.Show(new(options.AlertShowOptions)) cmd.Update(new(options.AlertUpdateOptions)) cmd.BatchDelete(new(options.AlertDeleteOptions)) diff --git a/cmd/climc/shell/monitor/commonalert.go b/cmd/climc/shell/monitor/commonalert.go index 32b3b1f56a..2303469772 100644 --- a/cmd/climc/shell/monitor/commonalert.go +++ b/cmd/climc/shell/monitor/commonalert.go @@ -20,7 +20,8 @@ import ( ) func init() { - cmd := NewResourceCmd(modules.CommonAlertManager) + cmd := NewResourceCmd(modules.CommonAlerts) + cmd.Create(new(options.CommonAlertCreateOptions)) cmd.List(new(options.CommonAlertListOptions)) cmd.Show(new(options.CommonAlertShowOptions)) cmd.Perform("enable", &options.CommonAlertShowOptions{}) diff --git a/pkg/apis/monitor/alertnotification.go b/pkg/apis/monitor/alertnotification.go index d483fe6555..b4b05dd510 100644 --- a/pkg/apis/monitor/alertnotification.go +++ b/pkg/apis/monitor/alertnotification.go @@ -20,6 +20,13 @@ import ( "yunion.io/x/onecloud/pkg/apis" ) +const ( + AlertNotificationUsedByMeterAlert = "meter_alert" + AlertNotificationUsedByNodeAlert = "node_alert" + AlertNotificationUsedByCommonAlert = "common_alert" + AlertNotificationUsedByMigrationAlert = "migration_alert" +) + type AlertJointResourceBaseDetails struct { apis.JointResourceBaseDetails SAlertJointsBase diff --git a/pkg/apis/monitor/commalert.go b/pkg/apis/monitor/commalert.go index 7a1001b7f1..b7993ce2e0 100644 --- a/pkg/apis/monitor/commalert.go +++ b/pkg/apis/monitor/commalert.go @@ -21,8 +21,9 @@ const ( ALERT_STATUS_DELETING = "deleting" ALERT_STATUS_DELETED = "deleted" - CommonAlertSystemAlertType = "system" - CommonAlertNomalAlertType = "normal" + CommonAlertSystemAlertType = "system" + CommonAlertNomalAlertType = "normal" + CommonAlertServiceAlertType = "service" MonitorComponentType = "default-monitor" MonitorComponentPort = 30093 @@ -40,16 +41,15 @@ const ( METRIC_QUERY_TYPE_NO_DATA = "nodata_query" METRIC_QUERY_NO_DATA_THESHOLD = "nodata" + + CommonAlertLevelNormal = "normal" + CommonAlertLevelImportant = "important" + CommonAlertLevelFatal = "fatal" ) -var CommonAlertLevels = []string{"normal", "important", "fatal"} +var CommonAlertLevels = []string{CommonAlertLevelNormal, CommonAlertLevelImportant, CommonAlertLevelFatal} -type CommonAlertCreateInput struct { - CommonMetricInputQuery - AlertCreateInput - - // 查询指标周期 - Period string `json:"period"` +type CommonAlertCreateBaseInput struct { // 报警连续持续周期数 AlertDuration int64 `json:"alert_duration"` // 通知方式, 比如: email, mobile @@ -76,6 +76,15 @@ type CommonAlertCreateInput struct { Description string `json:"description"` } +type CommonAlertCreateInput struct { + CommonMetricInputQuery + AlertCreateInput + CommonAlertCreateBaseInput + + // 查询指标周期 + Period string `json:"period"` +} + type CommonMetricInputQuery struct { From string `json:"from"` To string `json:"to"` diff --git a/pkg/apis/monitor/nodealert.go b/pkg/apis/monitor/nodealert.go index a4901d14eb..e51413a9e9 100644 --- a/pkg/apis/monitor/nodealert.go +++ b/pkg/apis/monitor/nodealert.go @@ -15,7 +15,7 @@ package monitor import ( - "time" + "strings" ) const ( @@ -51,39 +51,79 @@ type NodeAlertCreateInput struct { NodeName string `json:"node_name"` // 监控资源 Id NodeId string `json:"node_id"` + + // CommonAlertCreateInput injected by server and do not pass it through API + CommonAlertCreateInput *CommonAlertCreateInput `json:"common_alert_create_input,omitempty"` } -func (input NodeAlertCreateInput) ToAlertCreateInput( +func (input NodeAlertCreateInput) ToCommonAlertCreateInput( name string, field string, measurement string, - db string) AlertCreateInput { - freq, _ := time.ParseDuration(input.Window) - ret := AlertCreateInput{ - Name: name, - Frequency: int64(freq / time.Second), - Level: input.Level, - Settings: AlertSetting{ - Conditions: []AlertCondition{ + db string) CommonAlertCreateInput { + ret := CommonAlertCreateInput{ + AlertCreateInput: AlertCreateInput{ + Name: name, + Level: input.Level, + }, + CommonAlertCreateBaseInput: CommonAlertCreateBaseInput{ + Channel: strings.Split(input.Channel, ","), + Recipients: strings.Split(input.Recipients, ","), + AlertType: CommonAlertNomalAlertType, + }, + CommonMetricInputQuery: CommonMetricInputQuery{ + MetricQuery: []*CommonAlertQuery{ { - Type: "query", - Operator: "and", - Query: AlertQuery{ + AlertQuery: &AlertQuery{ Model: input.GetQuery(field, measurement, db), From: input.Period, To: "now", }, - Evaluator: input.GetEvaluator(), - Reducer: Condition{ - Type: "avg", - }, + Comparator: input.Comparator, + Threshold: input.Threshold, + ConditionType: "query", + Reduce: "avg", }, }, }, + Period: input.Window, } + ret.UsedBy = AlertNotificationUsedByNodeAlert + return ret } +// func (input NodeAlertCreateInput) ToAlertCreateInput( +// name string, +// field string, +// measurement string, +// db string) AlertCreateInput { +// freq, _ := time.ParseDuration(input.Window) +// ret := AlertCreateInput{ +// Name: name, +// Frequency: int64(freq / time.Second), +// Level: input.Level, +// Settings: AlertSetting{ +// Conditions: []AlertCondition{ +// { +// Type: "query", +// Operator: "and", +// Query: AlertQuery{ +// Model: input.GetQuery(field, measurement, db), +// From: input.Period, +// To: "now", +// }, +// Evaluator: input.GetEvaluator(), +// Reducer: Condition{ +// Type: "avg", +// }, +// }, +// }, +// }, +// } +// return ret +// } + func (input NodeAlertCreateInput) GetQuery(field, measurement, db string) MetricQuery { return GetNodeAlertQuery(input.Type, field, measurement, db, input.NodeId) } @@ -102,8 +142,9 @@ func GetNodeAlertQuery(typ, field, measurement, db, nodeId string) MetricQuery { Selects: sels, Tags: []MetricQueryTag{ { - Key: idField, - Value: nodeId, + Key: idField, + Operator: "=", + Value: nodeId, }, }, GroupBy: []MetricQueryPart{ @@ -145,7 +186,7 @@ type V1AlertListInput struct { } type NodeAlertListInput struct { - V1AlertListInput + AlertListInput // 监控指标名称 Metric string `json:"metric"` @@ -157,6 +198,13 @@ type NodeAlertListInput struct { NodeId string `json:"node_id"` } +func (o NodeAlertListInput) ToCommonAlertListInput() CommonAlertListInput { + return CommonAlertListInput{ + AlertListInput: o.AlertListInput, + Metric: o.Metric, + } +} + type AlertV1Details struct { AlertDetails @@ -185,7 +233,7 @@ type NodeAlertDetails struct { } type NodeAlertUpdateInput struct { - V1AlertUpdateInput + AlertUpdateInput // 监控指标名称 Metric *string `json:"metric"` diff --git a/pkg/compute/models/scaling_trigger.go b/pkg/compute/models/scaling_trigger.go index 1c5b3c5298..6445552f98 100644 --- a/pkg/compute/models/scaling_trigger.go +++ b/pkg/compute/models/scaling_trigger.go @@ -285,7 +285,9 @@ func (sa *SScalingAlarm) Register(ctx context.Context, userCred mcclient.TokenCr if err != nil { return errors.Wrap(err, "ScalingAlarm.generateAlertConfig") } - alert, err := monitor.Alerts.DoCreate(session, config) + alert, err := monitor.CommonAlerts.DoCreate(session, config, &monapi.CommonAlertCreateBaseInput{ + AlertType: monapi.CommonAlertServiceAlertType, + }) if err != nil { return errors.Wrap(err, "create Alert failed") } @@ -359,7 +361,7 @@ func (sa *SScalingAlarm) generateAlertConfig(sp *SScalingPolicy) (*monitor.Alert func (sa *SScalingAlarm) UnRegister(ctx context.Context, userCred mcclient.TokenCredential) error { session := auth.GetSession(ctx, userCred, "") _, err := monitor.Alerts.Delete(session, sa.AlarmId, jsonutils.NewDict()) - if err != nil { + if err != nil && errors.Cause(err) != httperrors.ErrResourceNotFound { return errors.Wrap(err, "Alerts.Delete") } err = sa.Delete(ctx, userCred) diff --git a/pkg/mcclient/modules/monitor/helper.go b/pkg/mcclient/modules/monitor/helper.go index 8d6a7fa577..d30f54e854 100644 --- a/pkg/mcclient/modules/monitor/helper.go +++ b/pkg/mcclient/modules/monitor/helper.go @@ -19,6 +19,8 @@ import ( "strings" "time" + "yunion.io/x/pkg/utils" + "yunion.io/x/onecloud/pkg/apis/monitor" "yunion.io/x/onecloud/pkg/monitor/tsdb" ) @@ -26,6 +28,7 @@ import ( // AlertConfig is a helper to generate monitor service alert related api input type AlertConfig struct { name string + frequencyStr string frequency int64 forTime int64 level string @@ -42,11 +45,12 @@ func NewAlertConfig(name string, frequency string, enabled bool) (*AlertConfig, return nil, err } input := &AlertConfig{ - name: name, - frequency: int64(freq / time.Second), - level: "", - enabled: enabled, - conditions: make([]*AlertCondition, 0), + name: name, + frequencyStr: frequency, + frequency: int64(freq / time.Second), + level: "", + enabled: enabled, + conditions: make([]*AlertCondition, 0), } return input, nil } @@ -81,9 +85,37 @@ func (c *AlertConfig) ToAlertCreateInput() monitor.AlertCreateInput { For: c.forTime, ExecutionErrorState: c.execErrorState, NoDataState: c.noDataState, + UsedBy: c.UsedBy, } } +func (c *AlertConfig) ToCommonMetricInputQuery() monitor.CommonMetricInputQuery { + conds := make([]*monitor.CommonAlertQuery, len(c.conditions)) + for i, cc := range c.conditions { + tmp := cc.ToCommonAlertQuery() + conds[i] = &tmp + } + return monitor.CommonMetricInputQuery{ + MetricQuery: conds, + } +} + +func (c *AlertConfig) ToCommonAlertCreateInput(bi *monitor.CommonAlertCreateBaseInput) monitor.CommonAlertCreateInput { + mq := c.ToCommonMetricInputQuery() + ai := c.ToAlertCreateInput() + if bi == nil { + bi = new(monitor.CommonAlertCreateBaseInput) + } + input := monitor.CommonAlertCreateInput{ + CommonMetricInputQuery: mq, + AlertCreateInput: ai, + CommonAlertCreateBaseInput: *bi, + Period: c.frequencyStr, + } + input.UsedBy = c.UsedBy + return input +} + func (c *AlertConfig) ToAlertSetting() monitor.AlertSetting { conds := make([]monitor.AlertCondition, len(c.conditions)) for i, cc := range c.conditions { @@ -149,6 +181,32 @@ func (c *AlertCondition) ToCondition() monitor.AlertCondition { } } +func (c *AlertCondition) ToCommonAlertQuery() monitor.CommonAlertQuery { + aq := c.query.ToAlertQuery() + eval := c.evaluator.Type + if !utils.IsInStringArray(eval, []string{"lt", "gt", "eq"}) { + panic(fmt.Sprintf("Invalid evaluator %q", eval)) + } + var comp string + switch eval { + case "lt": + comp = "<=" + case "gt": + comp = ">=" + case "eq": + comp = "==" + } + return monitor.CommonAlertQuery{ + AlertQuery: &aq, + Reduce: c.reducer.Type, + Comparator: comp, + Threshold: c.evaluator.Params[0], + // TODO: figure out what's the meaning of FieldOpt + FieldOpt: "", + ConditionType: "query", + } +} + func (c *AlertCondition) setOperator(op string) *AlertCondition { c.operator = op return c diff --git a/pkg/mcclient/modules/monitor/mod_commonalert.go b/pkg/mcclient/modules/monitor/mod_commonalert.go index 31d8cb65f2..d2c213fd7a 100644 --- a/pkg/mcclient/modules/monitor/mod_commonalert.go +++ b/pkg/mcclient/modules/monitor/mod_commonalert.go @@ -15,12 +15,16 @@ package monitor import ( + "yunion.io/x/jsonutils" + + "yunion.io/x/onecloud/pkg/apis/monitor" + "yunion.io/x/onecloud/pkg/mcclient" "yunion.io/x/onecloud/pkg/mcclient/modulebase" "yunion.io/x/onecloud/pkg/mcclient/modules" ) var ( - CommonAlertManager *SCommonAlertManager + CommonAlerts *SCommonAlertManager ) type SCommonAlertManager struct { @@ -28,9 +32,9 @@ type SCommonAlertManager struct { } func init() { - CommonAlertManager = NewCommonAlertManager() + CommonAlerts = NewCommonAlertManager() for _, m := range []modulebase.IBaseManager{ - CommonAlertManager, + CommonAlerts, } { modules.Register(m) } @@ -44,3 +48,8 @@ func NewCommonAlertManager() *SCommonAlertManager { ResourceManager: &man, } } + +func (m *SCommonAlertManager) DoCreate(s *mcclient.ClientSession, config *AlertConfig, bi *monitor.CommonAlertCreateBaseInput) (jsonutils.JSONObject, error) { + input := config.ToCommonAlertCreateInput(bi) + return m.Create(s, input.JSON(input)) +} diff --git a/pkg/mcclient/modules/monitor/mod_monitor_resource.go b/pkg/mcclient/modules/monitor/mod_monitor_resource.go index d7dc4d5bbc..9695e06481 100644 --- a/pkg/mcclient/modules/monitor/mod_monitor_resource.go +++ b/pkg/mcclient/modules/monitor/mod_monitor_resource.go @@ -54,6 +54,6 @@ func newAlertResourceAlertManager() *SMonitorResourceAlertManager { []string{"monitor_resource_id", "alert_id", "res_name", "res_type", "alert_name", "alert_state", "send_state", "level", "trigger_time", "data"}, []string{}, - MonitorResourceManager, CommonAlertManager) + MonitorResourceManager, CommonAlerts) return &SMonitorResourceAlertManager{&man} } diff --git a/pkg/mcclient/options/monitor/alert.go b/pkg/mcclient/options/monitor/alert.go index 08dc5fb619..5798f59d0e 100644 --- a/pkg/mcclient/options/monitor/alert.go +++ b/pkg/mcclient/options/monitor/alert.go @@ -94,7 +94,6 @@ type AlertConditionOptions struct { THRESHOLD float64 `help:"Alert threshold"` Period string `help:"Query metric period e.g. '5m', '1h'" default:"5m"` Tag []string `help:"Query tag, e.g. 'zone=zon0,name=vmname'"` - For string `help:"For time duration"` } func (opt AlertConditionOptions) Params(conf *monitor2.AlertConfig) (*monitor2.AlertCondition, error) { @@ -152,6 +151,7 @@ type AlertCreateOptions struct { Frequency string `help:"Alert execute frequency, e.g. '5m', '1h'"` Enabled bool `help:"Enable alert"` Level string `help:"Alert level"` + For string `help:"For time duration"` } func (opt AlertCreateOptions) Params() (jsonutils.JSONObject, error) { diff --git a/pkg/mcclient/options/monitor/commonalert.go b/pkg/mcclient/options/monitor/commonalert.go index efade57823..01f15ed2e7 100644 --- a/pkg/mcclient/options/monitor/commonalert.go +++ b/pkg/mcclient/options/monitor/commonalert.go @@ -16,7 +16,11 @@ package monitor import ( "yunion.io/x/jsonutils" + "yunion.io/x/pkg/errors" + "yunion.io/x/onecloud/pkg/apis" + "yunion.io/x/onecloud/pkg/apis/monitor" + monitor2 "yunion.io/x/onecloud/pkg/mcclient/modules/monitor" "yunion.io/x/onecloud/pkg/mcclient/options" ) @@ -70,3 +74,41 @@ func (o *CommonAlertDeleteOptions) GetIds() []string { func (o *CommonAlertDeleteOptions) Params() (jsonutils.JSONObject, error) { return options.StructToParams(o) } + +type CommonAlertConditionOptions struct { + AlertConditionOptions +} + +func (o CommonAlertConditionOptions) Params(conf *monitor2.AlertConfig) (*monitor2.AlertCondition, error) { + cond, err := o.AlertConditionOptions.Params(conf) + if err != nil { + return nil, errors.Wrap(err, "AlertConditionOptions.Params") + } + return cond, nil +} + +type CommonAlertCreateOptions struct { + apis.Meta + monitor.CommonAlertCreateBaseInput + + CommonAlertConditionOptions + AlertStatesOptions + + NAME string `help:"Name of the alert"` + // 报警级别 + Level string `json:"level"` +} + +func (o *CommonAlertCreateOptions) Params() (jsonutils.JSONObject, error) { + input, err := monitor2.NewAlertConfig(o.NAME, o.Period, true) + if err != nil { + return nil, err + } + if _, err := o.CommonAlertConditionOptions.Params(input); err != nil { + return nil, err + } + input.NoDataState(o.NoDataState) + input.ExecutionErrorState(o.ExecutionErrorState) + ret := input.ToCommonAlertCreateInput(&o.CommonAlertCreateBaseInput) + return ret.JSON(ret), nil +} diff --git a/pkg/monitor/models/alert.go b/pkg/monitor/models/alert.go index 1dd65e3fba..34bfb04f97 100644 --- a/pkg/monitor/models/alert.go +++ b/pkg/monitor/models/alert.go @@ -401,6 +401,10 @@ func (alert *SAlert) CustomizeCreate(ctx context.Context, userCred mcclient.Toke return alert.SScopedResourceBase.CustomizeCreate(ctx, userCred, ownerId, query, data) } +func (alert *SAlert) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) { + alert.SetStatus(userCred, monitor.ALERT_STATUS_READY, "") +} + func (alert *SAlert) PerformEnable(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input apis.PerformEnableInput) (jsonutils.JSONObject, error) { err := db.EnabledPerformEnable(alert, ctx, userCred, true) if err != nil { diff --git a/pkg/monitor/models/alertnotification.go b/pkg/monitor/models/alertnotification.go index deea431bd4..9b1730b55d 100644 --- a/pkg/monitor/models/alertnotification.go +++ b/pkg/monitor/models/alertnotification.go @@ -29,10 +29,10 @@ import ( ) const ( - AlertNotificationUsedByMeterAlert = "meter_alert" - AlertNotificationUsedByNodeAlert = "node_alert" - AlertNotificationUsedByCommonAlert = "common_alert" - AlertNotificationUsedByMigrationAlert = "migration_alert" + AlertNotificationUsedByMeterAlert = monitor.AlertNotificationUsedByMeterAlert + AlertNotificationUsedByNodeAlert = monitor.AlertNotificationUsedByNodeAlert + AlertNotificationUsedByCommonAlert = monitor.AlertNotificationUsedByCommonAlert + AlertNotificationUsedByMigrationAlert = monitor.AlertNotificationUsedByMigrationAlert ) type SAlertNotificationManager struct { diff --git a/pkg/monitor/models/commonalert.go b/pkg/monitor/models/commonalert.go index 91971ea187..411128c31b 100644 --- a/pkg/monitor/models/commonalert.go +++ b/pkg/monitor/models/commonalert.go @@ -92,6 +92,17 @@ type SCommonAlertManager struct { subscriptionManager ISubscriptionManager } +type ICommonAlert interface { + db.IModel + + RealDelete(ctx context.Context, userCred mcclient.TokenCredential) error + DeleteAttachAlertRecords(ctx context.Context, userCred mcclient.TokenCredential) []error + DetachAlertResourceOnDisable(ctx context.Context, userCred mcclient.TokenCredential) []error + DetachMonitorResourceJoint(ctx context.Context, userCred mcclient.TokenCredential) error + UpdateMonitorResourceJoint(ctx context.Context, userCred mcclient.TokenCredential) error + GetMoreDetails(ctx context.Context, out monitor.CommonAlertDetails) (monitor.CommonAlertDetails, error) +} + type SCommonAlert struct { SAlert } @@ -173,7 +184,7 @@ func (man *SCommonAlertManager) ValidateCreateData( return data, merrors.NewArgIsEmptyErr("name") } if data.Level == "" { - return data, merrors.NewArgIsEmptyErr("level") + data.Level = monitor.CommonAlertLevelNormal } if len(data.Channel) == 0 { data.Channel = []string{monitor.DEFAULT_SEND_NOTIFY_CHANNEL} @@ -194,7 +205,10 @@ func (man *SCommonAlertManager) ValidateCreateData( } } // 默认的系统配置Recipients=commonalert-default - if data.AlertType != monitor.CommonAlertSystemAlertType { + if !utils.IsInStringArray(data.AlertType, []string{ + monitor.CommonAlertSystemAlertType, + monitor.CommonAlertServiceAlertType, + }) { if len(data.Recipients) == 0 && len(data.RobotIds) == 0 && len(data.Roles) == 0 { return data, merrors.NewArgIsEmptyErr("recipients, robot_ids or roles") } @@ -225,7 +239,7 @@ func (man *SCommonAlertManager) ValidateCreateData( if data.AlertType != "" { if !utils.IsInStringArray(data.AlertType, validators.CommonAlertType) { - return data, httperrors.NewInputParameterError("the AlertType is illegal:%s", data.AlertType) + return data, httperrors.NewInputParameterError("Invalid AlertType: %s", data.AlertType) } } var err = man.ValidateMetricQuery(&data.CommonMetricInputQuery, data.Scope, ownerId) @@ -298,7 +312,8 @@ func (alert *SCommonAlert) setAlertType(ctx context.Context, userCred mcclient.T } func (alert *SCommonAlert) getAlertType() string { - return alert.GetMetadata(context.Background(), CommonAlertMetadataAlertType, nil) + ret := alert.GetMetadata(context.Background(), CommonAlertMetadataAlertType, nil) + return ret } func (alert *SCommonAlert) setFieldOpt(ctx context.Context, userCred mcclient.TokenCredential, fieldOpt string) error { @@ -353,7 +368,6 @@ func (alert *SCommonAlert) customizeCreateNotis(ctx context.Context, userCred mc return err } - // used_by 弃用 if input.AlertType == monitor.CommonAlertSystemAlertType { s := &monitor.NotificationSettingOneCloud{ Channel: "webconsole", @@ -409,7 +423,6 @@ func (alert *SCommonAlert) createAlertNoti(ctx context.Context, userCred mcclien if alert.Id == "" { alert.Id = db.DefaultUUIDGenerator() } - //alert.UsedBy = usedBy _, err = alert.AttachNotification( ctx, userCred, noti, monitor.AlertNotificationStateUnknown, @@ -430,7 +443,9 @@ func (alert *SCommonAlert) PostCreate(ctx context.Context, alert.SetStatus(userCred, monitor.ALERT_STATUS_READY, "") if input.AlertType != "" { - alert.setAlertType(ctx, userCred, input.AlertType) + if err := alert.setAlertType(ctx, userCred, input.AlertType); err != nil { + log.Errorf("etAlertType error for %q: %v", alert.GetId(), err) + } } fieldOpt := "" for i, metricQ := range input.CommonMetricInputQuery.MetricQuery { @@ -474,9 +489,12 @@ func (man *SCommonAlertManager) ListItemFilter( } func (man *SCommonAlertManager) FieldListFilter(q *sqlchemy.SQuery, input monitor.CommonAlertListInput) { - if len(input.UsedBy) == 0 { - q.Filter(sqlchemy.IsNull(q.Field("used_by"))) - } else { + // if len(input.UsedBy) == 0 { + // q.Filter(sqlchemy.IsNull(q.Field("used_by"))) + // } else { + // q.Equals("used_by", input.UsedBy) + // } + if len(input.UsedBy) != 0 { q.Equals("used_by", input.UsedBy) } @@ -637,7 +655,11 @@ func (man *SCommonAlertManager) FetchCustomizeColumns( alertRows := man.SAlertManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList) for i := range rows { rows[i].AlertDetails = alertRows[i] - rows[i], _ = objs[i].(*SCommonAlert).GetMoreDetails(ctx, rows[i]) + var err error + rows[i], err = objs[i].(ICommonAlert).GetMoreDetails(ctx, rows[i]) + if err != nil { + log.Warningf("GetMoreDetails for alert %s: %v", rows[i].Name, err) + } } return rows } @@ -674,17 +696,17 @@ func (alert *SCommonAlert) GetMoreDetails(ctx context.Context, out monitor.Commo var err error alertNotis, err := alert.GetNotifications() if err != nil { - return out, err + return out, errors.Wrap(err, "GetNotifications") } channel := sets.String{} for i, alertNoti := range alertNotis { noti, err := alertNoti.GetNotification() if err != nil { - return out, errors.Wrap(err, "get notify err:") + return out, errors.Wrap(err, "get notify") } settings := new(monitor.NotificationSettingOneCloud) if err := noti.Settings.Unmarshal(settings); err != nil { - return out, err + return out, errors.Wrap(err, "Unmarshal to NotificationSettingOneCloud") } if i == 0 { out.Recipients = settings.UserIds @@ -716,9 +738,8 @@ func (alert *SCommonAlert) GetMoreDetails(ctx context.Context, out monitor.Commo out.AlertDuration = 1 } - err = alert.getCommonAlertMetricDetails(&out) - if err != nil { - return out, err + if err := alert.getCommonAlertMetricDetails(&out); err != nil { + return out, errors.Wrap(err, "getCommonAlertMetricDetails") } return out, nil } @@ -1057,13 +1078,13 @@ func (alert *SCommonAlert) PostUpdate( data.Unmarshal(updateInput) if len(updateInput.Channel) != 0 { if err := alert.UpdateNotification(ctx, userCred, query, data); err != nil { - log.Errorln("update notification", err) + log.Errorf("update notification error: %v", err) } } if _, err := data.GetString("scope"); err == nil { _, err = alert.PerformSetScope(ctx, userCred, query, data) if err != nil { - log.Errorln(errors.Wrap(err, "Alert PerformSetScope")) + log.Errorf("Alert PerformSetScope: %v", err) } } if updateInput.GetPointStr { @@ -1088,7 +1109,7 @@ func (alert *SCommonAlert) UpdateNotification(ctx context.Context, userCred mccl } err = alert.customizeCreateNotis(ctx, userCred, query, data) if err != nil { - log.Errorln(err) + log.Errorf("customizeCreateNotis for %s(%s): %v", alert.GetName(), alert.GetId(), err) } return err } @@ -1097,8 +1118,8 @@ func (alert *SCommonAlert) getUpdateAlertInput(updateInput monitor.CommonAlertUp input := monitor.CommonAlertCreateInput{ CommonMetricInputQuery: updateInput.CommonMetricInputQuery, Period: updateInput.Period, - AlertDuration: updateInput.AlertDuration, } + input.AlertDuration = updateInput.AlertDuration alertCreateInput := CommonAlertManager.toAlertCreatInput(input) return alertCreateInput } @@ -1416,6 +1437,9 @@ func (alert *SCommonAlert) DetachMonitorResourceJoint(ctx context.Context, userC func (alert *SCommonAlert) UpdateResType() error { setting, _ := alert.GetSettings() + if len(setting.Conditions) == 0 { + return nil + } measurement, _ := MetricMeasurementManager.GetCache().Get(setting.Conditions[0].Query.Model.Measurement) if measurement == nil { return nil diff --git a/pkg/monitor/models/meteralert.go b/pkg/monitor/models/meteralert.go index 48c2ee2448..7514a8c8d4 100644 --- a/pkg/monitor/models/meteralert.go +++ b/pkg/monitor/models/meteralert.go @@ -63,7 +63,7 @@ type SMeterAlertManager struct { func NewMeterAlertManager() *SMeterAlertManager { man := &SMeterAlertManager{ SV1AlertManager: SV1AlertManager{ - *NewAlertManager(SMeterAlert{}, "meteralert", "meteralerts"), + SAlertManager: *NewAlertManager(SMeterAlert{}, "meteralert", "meteralerts"), }, } man.SetVirtualObject(man) diff --git a/pkg/monitor/models/nodealert.go b/pkg/monitor/models/nodealert.go index cd24b846ff..a7ed8b2921 100644 --- a/pkg/monitor/models/nodealert.go +++ b/pkg/monitor/models/nodealert.go @@ -56,13 +56,13 @@ type SV1AlertManager struct { } type SNodeAlertManager struct { - SV1AlertManager + SCommonAlertManager } func NewNodeAlertManager() *SNodeAlertManager { man := &SNodeAlertManager{ - SV1AlertManager: SV1AlertManager{ - *NewAlertManager(SNodeAlert{}, "nodealert", "nodealerts"), + SCommonAlertManager: SCommonAlertManager{ + SAlertManager: *NewAlertManager(SNodeAlert{}, "nodealert", "nodealerts"), }, } man.SetVirtualObject(man) @@ -74,7 +74,7 @@ type SV1Alert struct { } type SNodeAlert struct { - SV1Alert + SCommonAlert } func (v1man *SV1AlertManager) CreateNotification( @@ -127,12 +127,14 @@ func (man *SNodeAlertManager) ValidateCreateData( if err != nil { return nil, err } - alertInput := data.ToAlertCreateInput(name, field, measurement, monitor.METRIC_DATABASE_TELE) - alertInput, err = AlertManager.ValidateCreateData(ctx, userCred, ownerId, query, alertInput) + alertInput := data.ToCommonAlertCreateInput(name, field, measurement, monitor.METRIC_DATABASE_TELE) + alertInput, err = GetCommonAlertManager().ValidateCreateData(ctx, userCred, ownerId, query, alertInput) if err != nil { - return nil, err + return nil, errors.Wrap(err, "CommonAlertManager.ValidateCreateData") } - data.AlertCreateInput = alertInput + data.CommonAlertCreateInput = &alertInput + data.AlertCreateInput = alertInput.AlertCreateInput + data.UsedBy = AlertNotificationUsedByNodeAlert return &data, nil } @@ -254,7 +256,7 @@ func (man *SNodeAlertManager) ListItemFilter( userCred mcclient.TokenCredential, query monitor.NodeAlertListInput, ) (*sqlchemy.SQuery, error) { - q, err := man.SV1AlertManager.ListItemFilter(ctx, q, userCred, query.V1AlertListInput) + q, err := man.SCommonAlertManager.ListItemFilter(ctx, q, userCred, query.ToCommonAlertListInput()) if err != nil { return nil, err } @@ -282,7 +284,7 @@ func (man *SNodeAlertManager) OrderByExtraFields( ) (*sqlchemy.SQuery, error) { var err error - q, err = man.SV1AlertManager.OrderByExtraFields(ctx, q, userCred, query.V1AlertListInput) + q, err = man.SCommonAlertManager.OrderByExtraFields(ctx, q, userCred, query.AlertListInput) if err != nil { return nil, errors.Wrap(err, "SV1AlertManager.OrderByExtraFields") } @@ -293,7 +295,7 @@ func (man *SNodeAlertManager) OrderByExtraFields( func (man *SNodeAlertManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) { var err error - q, err = man.SV1AlertManager.QueryDistinctExtraField(q, field) + q, err = man.SCommonAlertManager.QueryDistinctExtraField(q, field) if err == nil { return q, nil } @@ -313,7 +315,7 @@ func (man *SNodeAlertManager) CustomizeFilterList( ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) ( *db.CustomizeListFilters, error) { - filters, err := man.SV1AlertManager.CustomizeFilterList(ctx, q, userCred, query) + filters, err := man.SCommonAlertManager.CustomizeFilterList(ctx, q, userCred, query) if err != nil { return nil, err } @@ -383,7 +385,7 @@ func (man *SNodeAlertManager) CustomizeFilterList( func (alert *SV1Alert) CustomizeCreate( ctx context.Context, userCred mcclient.TokenCredential, notiName, channel, recipients, usedBy string) error { - noti, err := NodeAlertManager.CreateNotification(ctx, userCred, notiName, channel, recipients) + noti, err := MeterAlertManager.CreateNotification(ctx, userCred, notiName, channel, recipients) if err != nil { return errors.Wrap(err, "create notification") } @@ -413,14 +415,19 @@ func (alert *SNodeAlert) CustomizeCreate( query jsonutils.JSONObject, data jsonutils.JSONObject, ) error { - if err := alert.SAlert.CustomizeCreate(ctx, userCred, ownerId, query, data); err != nil { - return err - } input := new(monitor.NodeAlertCreateInput) if err := data.Unmarshal(input); err != nil { return err } - return alert.SV1Alert.CustomizeCreate(ctx, userCred, input.Metric, input.Channel, input.Recipients, AlertNotificationUsedByNodeAlert) + if alert.Id == "" { + alert.Id = db.DefaultUUIDGenerator() + } + alert.UsedBy = input.UsedBy + caInput := input.CommonAlertCreateInput + if err := alert.SCommonAlert.CustomizeCreate(ctx, userCred, ownerId, query, caInput.JSON(caInput)); err != nil { + return errors.Wrap(err, "CommonAlert.CustomizeCreate") + } + return nil } func (alert *SNodeAlert) getNodeId() string { @@ -450,7 +457,6 @@ func (alert *SNodeAlert) setType(ctx context.Context, userCred mcclient.TokenCre func (alert *SNodeAlert) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) { - alert.SStatusStandaloneResourceBase.PostCreate(ctx, userCred, ownerId, query, data) input := new(monitor.NodeAlertCreateInput) if err := data.Unmarshal(input); err != nil { log.Errorf("post create unmarshal input: %v", err) @@ -468,6 +474,8 @@ func (alert *SNodeAlert) PostCreate(ctx context.Context, log.Errorf("set type: %v", err) return } + caInput := input.CommonAlertCreateInput + alert.SCommonAlert.PostCreate(ctx, userCred, ownerId, query, caInput.JSON(caInput)) } func (man *SV1AlertManager) FetchCustomizeColumns( @@ -512,7 +520,7 @@ func (alert *SV1Alert) getMoreDetails(out monitor.AlertV1Details, usedBy string) setting, err := alert.GetSettings() if err != nil { - return out, err + return out, errors.Wrapf(err, "GetSettings") } if len(setting.Conditions) == 0 { return out, nil @@ -532,13 +540,13 @@ func (alert *SV1Alert) getMoreDetails(out monitor.AlertV1Details, usedBy string) noti, err := alert.GetNotification(usedBy) if err != nil { - return out, err + return out, errors.Wrapf(err, "GetNotification for %q", usedBy) } if noti != nil { out.NotifierId = noti.GetId() settings := new(monitor.NotificationSettingOneCloud) if err := noti.Settings.Unmarshal(settings); err != nil { - return out, err + return out, errors.Wrapf(err, "Unmarshal to NotificationSettingOneCloud") } out.Recipients = strings.Join(settings.UserIds, ",") out.Channel = settings.Channel @@ -565,37 +573,76 @@ func (man *SNodeAlertManager) FetchCustomizeColumns( ) []monitor.NodeAlertDetails { rows := make([]monitor.NodeAlertDetails, len(objs)) - v1Rows := man.SV1AlertManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList) + v1Rows := man.SCommonAlertManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList) for i := range rows { rows[i] = monitor.NodeAlertDetails{ - AlertV1Details: v1Rows[i], + AlertV1Details: monitor.AlertV1Details{ + AlertDetails: v1Rows[i].AlertDetails, + }, + } + var err error + rows[i], err = objs[i].(*SNodeAlert).getMoreDetails(ctx, v1Rows[i], rows[i]) + if err != nil { + log.Warningf("getMoreDetails for nodealert %s: %v", rows[i].Name, err) } - rows[i], _ = objs[i].(*SNodeAlert).getMoreDetails(rows[i]) } return rows } -func (alert *SNodeAlert) getMoreDetails(out monitor.NodeAlertDetails) (monitor.NodeAlertDetails, error) { - var err error - out.AlertV1Details, err = alert.SV1Alert.getMoreDetails(out.AlertV1Details, AlertNotificationUsedByNodeAlert) - if err != nil { - return out, errors.Wrap(err, "SV1Alert.getMoreDetails") - } - +func (alert *SNodeAlert) getMoreDetails(ctx context.Context, input monitor.CommonAlertDetails, out monitor.NodeAlertDetails) (monitor.NodeAlertDetails, error) { out.Type = alert.getType() out.NodeId = alert.getNodeId() out.NodeName = alert.getNodeName() + out.AlertDetails = input.AlertDetails + out.Name = alert.GetName() + out.Period = input.Period + if alert.Frequency < 60 { + out.Window = fmt.Sprintf("%ds", alert.Frequency) + } else { + out.Window = fmt.Sprintf("%dm", alert.Frequency/60) + } + setting, err := alert.GetSettings() if err != nil { - return out, err + return out, errors.Wrap(err, "GetSettings") } if len(setting.Conditions) == 0 { return out, nil } + cond := setting.Conditions[0] + cmp := "" + switch cond.Evaluator.Type { + case "gt": + cmp = ">=" + case "lt": + cmp = "<=" + } + out.Level = alert.Level + out.Comparator = cmp + out.Threshold = cond.Evaluator.Params[0] + out.Period = cond.Query.From + q := cond.Query + measurement := q.Model.Measurement + field := q.Model.Selects[0][0].Params[0] + db := q.Model.Database + out.Measurement = measurement + out.Field = field out.Metric = fmt.Sprintf("%s.%s", out.Measurement, out.Field) + out.DB = db + out.Status = alert.GetStatus() + + input, err = alert.SCommonAlert.GetMoreDetails(ctx, input) + if err != nil { + return out, errors.Wrap(err, "SCommonAlert.GetMoreDetails") + } + + if len(input.Channel) > 0 { + out.Channel = input.Channel[0] + } + out.Recipients = strings.Join(input.Recipients, ",") return out, nil } @@ -695,14 +742,8 @@ func (alert *SV1Alert) CustomizeDelete( return nil } -func (alert *SNodeAlert) ValidateUpdateData( - ctx context.Context, - userCred mcclient.TokenCredential, - query jsonutils.JSONObject, - input monitor.NodeAlertUpdateInput, -) (monitor.NodeAlertUpdateInput, error) { - // ret := monitor.AlertUpdateInput{} - detailsList := NodeAlertManager.FetchCustomizeColumns(ctx, userCred, query, []interface{}{alert}, nil, false) +func (alert *SNodeAlert) GetCommonAlertUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *monitor.NodeAlertUpdateInput) (jsonutils.JSONObject, error) { + detailsList := NodeAlertManager.FetchCustomizeColumns(ctx, userCred, nil, []interface{}{alert}, nil, false) if len(detailsList) == 0 { panic("inconsistent return results of FetchCustomizeColumns") } @@ -713,37 +754,36 @@ func (alert *SNodeAlert) ValidateUpdateData( nameChange = true details.NodeId = *input.NodeId if err := alert.setNodeId(ctx, userCred, details.NodeId); err != nil { - return input, err + return nil, err } } if input.Type != nil && *input.Type != details.Type { nameChange = true details.Type = *input.Type if err := alert.setType(ctx, userCred, details.Type); err != nil { - return input, err + return nil, err } } nodeName, resType, err := NodeAlertManager.validateResourceId(ctx, details.Type, details.NodeId) if err != nil { - return input, err + return nil, err } if details.NodeName != nodeName { nameChange = true if err := alert.setNodeName(ctx, userCred, nodeName); err != nil { - return input, err + return nil, err } details.NodeName = nodeName } if input.Level != nil && *input.Level != details.Level { details.Level = *input.Level - // ret.Level = input.Level } if input.Window != nil && *input.Window != details.Window { details.Window = *input.Window freq, err := time.ParseDuration(details.Window) if err != nil { - return input, err + return nil, err } freqSec := int64(freq / time.Second) input.Frequency = &freqSec @@ -761,11 +801,19 @@ func (alert *SNodeAlert) ValidateUpdateData( details.Period = *input.Period } + if input.Channel != nil { + details.Channel = *input.Channel + } + + if input.Recipients != nil { + details.Recipients = *input.Recipients + } + if input.Metric != nil && *input.Metric != details.Metric { details.Metric = *input.Metric measurement, field, err := GetMeasurementField(*input.Metric) if err != nil { - return input, err + return nil, err } details.Measurement = measurement details.Field = field @@ -775,35 +823,40 @@ func (alert *SNodeAlert) ValidateUpdateData( if nameChange { name, err = NodeAlertManager.genName(ctx, userCred, resType, details.NodeName, details.Metric) if err != nil { - return input, err + return nil, err } input.Name = name } ds, err := DataSourceManager.GetDefaultSource() if err != nil { - return input, errors.Wrap(err, "get default data source") + return nil, errors.Wrap(err, "get default data source") } - // hack: update notification here - if err := alert.UpdateNotification(AlertNotificationUsedByNodeAlert, input.Channel, input.Recipients); err != nil { - return input, errors.Wrap(err, "update notification") - } - tmpS := alert.getUpdateSetting(name, details, ds.GetId()) - input.Settings = &tmpS + tmpS := alert.getUpdateInput(name, details, ds.GetId()) + input.Settings = &tmpS.Settings - input.V1AlertUpdateInput, err = alert.SV1Alert.ValidateUpdateData(ctx, userCred, query, input.V1AlertUpdateInput) + uData, err := alert.SCommonAlert.ValidateUpdateData(ctx, userCred, nil, tmpS.JSON(tmpS)) if err != nil { - return input, errors.Wrap(err, "SV1Alert.ValidateUpdateData") + return nil, errors.Wrap(err, "SCommonAlert.ValidateUpdateData") } - return input, nil + return uData, nil } -func (alert *SNodeAlert) getUpdateSetting( +func (alert *SNodeAlert) ValidateUpdateData( + ctx context.Context, + userCred mcclient.TokenCredential, + query jsonutils.JSONObject, + input monitor.NodeAlertUpdateInput, +) (jsonutils.JSONObject, error) { + return alert.GetCommonAlertUpdateData(ctx, userCred, query, &input) +} + +func (alert *SNodeAlert) getUpdateInput( name string, details monitor.NodeAlertDetails, dsId string, -) monitor.AlertSetting { +) monitor.CommonAlertCreateInput { data := monitor.NodeAlertCreateInput{ ResourceAlertV1CreateInput: monitor.ResourceAlertV1CreateInput{ Period: details.Period, @@ -818,24 +871,29 @@ func (alert *SNodeAlert) getUpdateSetting( NodeId: details.NodeId, } data.Level = details.Level - out := data.ToAlertCreateInput(name, details.Field, details.Measurement, details.DB) + out := data.ToCommonAlertCreateInput(name, details.Field, details.Measurement, details.DB) out.Settings = *setAlertDefaultSetting(&out.Settings, dsId) - return out.Settings + return out } func (alert *SNodeAlert) PostUpdate( ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) { - alert.SV1Alert.PostUpdate(ctx, userCred, query, data) + input := new(monitor.NodeAlertUpdateInput) + data.Unmarshal(input) + uData, err := alert.GetCommonAlertUpdateData(ctx, userCred, query, input) + if err != nil { + log.Errorf("GetCommonAlertUpdateData when PostUpdate: %v", err) + } + alert.SCommonAlert.PostUpdate(ctx, userCred, query, uData) } func (alert *SNodeAlert) CustomizeDelete( ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error { - return alert.SV1Alert.CustomizeDelete(ctx, userCred, query, data) + return alert.SCommonAlert.CustomizeDelete(ctx, userCred, query, data) } func (m *SNodeAlertManager) FilterByOwner(q *sqlchemy.SQuery, userCred mcclient.IIdentityProvider, scope rbacutils.TRbacScope) *sqlchemy.SQuery { - return q } diff --git a/pkg/monitor/tasks/delete_alertrecord_task.go b/pkg/monitor/tasks/delete_alertrecord_task.go index 629babe749..7f46b1d97b 100644 --- a/pkg/monitor/tasks/delete_alertrecord_task.go +++ b/pkg/monitor/tasks/delete_alertrecord_task.go @@ -36,10 +36,10 @@ func init() { } func (self *DeleteAlertRecordTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) { - alert := obj.(*models.SCommonAlert) + alert := obj.(models.ICommonAlert) errs := alert.DeleteAttachAlertRecords(ctx, self.GetUserCred()) if len(errs) != 0 { - msg := jsonutils.NewString(fmt.Sprintf("fail to DeleteAttachAlertRecords:%s.err:%v", alert.Name, errors.NewAggregate(errs))) + msg := jsonutils.NewString(fmt.Sprintf("fail to DeleteAttachAlertRecords:%s.err:%v", alert.GetName(), errors.NewAggregate(errs))) self.taskFail(ctx, alert, msg) return } @@ -55,9 +55,8 @@ func (self *DeleteAlertRecordTask) OnInit(ctx context.Context, obj db.IStandalon self.SetStageComplete(ctx, nil) } -func (self *DeleteAlertRecordTask) taskFail(ctx context.Context, alert *models.SCommonAlert, msg jsonutils.JSONObject) { +func (self *DeleteAlertRecordTask) taskFail(ctx context.Context, alert models.ICommonAlert, msg jsonutils.JSONObject) { db.OpsLog.LogEvent(alert, db.ACT_DELETE_FAIL, msg, self.GetUserCred()) logclient.AddActionLogWithStartable(self, alert, logclient.ACT_DELETE, msg, self.UserCred, false) self.SetStageFailed(ctx, msg) - return } diff --git a/pkg/monitor/tasks/detach_alertresource_task.go b/pkg/monitor/tasks/detach_alertresource_task.go index a199a50ed7..a029c22dc8 100644 --- a/pkg/monitor/tasks/detach_alertresource_task.go +++ b/pkg/monitor/tasks/detach_alertresource_task.go @@ -38,10 +38,10 @@ func init() { } func (self *DetachAlertResourceTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) { - alert := obj.(*models.SCommonAlert) + alert := obj.(models.ICommonAlert) errs := alert.DetachAlertResourceOnDisable(ctx, self.GetUserCred()) if len(errs) != 0 { - msg := jsonutils.NewString(fmt.Sprintf("fail to DetachAlertResourceOnAlertDisable:%s.err:%v", alert.Name, errors.NewAggregate(errs))) + msg := jsonutils.NewString(fmt.Sprintf("fail to DetachAlertResourceOnAlertDisable:%s.err:%v", alert.GetName(), errors.NewAggregate(errs))) self.taskFail(ctx, alert, msg) return } @@ -59,7 +59,7 @@ func (self *DetachAlertResourceTask) OnInit(ctx context.Context, obj db.IStandal self.SetStageComplete(ctx, nil) } -func (self *DetachAlertResourceTask) taskFail(ctx context.Context, alert *models.SCommonAlert, msg jsonutils.JSONObject) { +func (self *DetachAlertResourceTask) taskFail(ctx context.Context, alert models.ICommonAlert, msg jsonutils.JSONObject) { db.OpsLog.LogEvent(alert, db.ACT_DETACH, msg, self.GetUserCred()) logclient.AddActionLogWithStartable(self, alert, logclient.ACT_DETACH_ALERTRESOURCE, msg, self.UserCred, false) self.SetStageFailed(ctx, msg) diff --git a/pkg/monitor/tasks/detach_monitor_resource_task.go b/pkg/monitor/tasks/detach_monitor_resource_task.go index 5b2dba6925..56a95b2b6d 100644 --- a/pkg/monitor/tasks/detach_monitor_resource_task.go +++ b/pkg/monitor/tasks/detach_monitor_resource_task.go @@ -35,10 +35,10 @@ func init() { } func (self *DetachMonitorResourceJointTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) { - alert := obj.(*models.SCommonAlert) + alert := obj.(models.ICommonAlert) err := alert.DetachMonitorResourceJoint(ctx, self.GetUserCred()) if err != nil { - msg := jsonutils.NewString(fmt.Sprintf("alert:%s DetachMonitorResourceJoint err:%v", alert.Name, err)) + msg := jsonutils.NewString(fmt.Sprintf("alert:%s DetachMonitorResourceJoint err:%v", alert.GetName(), err)) self.taskFail(ctx, alert, msg) return } @@ -46,7 +46,7 @@ func (self *DetachMonitorResourceJointTask) OnInit(ctx context.Context, obj db.I self.SetStageComplete(ctx, nil) } -func (self *DetachMonitorResourceJointTask) taskFail(ctx context.Context, alert *models.SCommonAlert, msg jsonutils.JSONObject) { +func (self *DetachMonitorResourceJointTask) taskFail(ctx context.Context, alert models.ICommonAlert, msg jsonutils.JSONObject) { db.OpsLog.LogEvent(alert, db.ACT_DETACH_MONITOR_RESOURCE_JOINT, msg, self.GetUserCred()) logclient.AddActionLogWithStartable(self, alert, logclient.ACT_DETACH_MONITOR_RESOURCE_JOINT, msg, self.UserCred, false) self.SetStageFailed(ctx, msg) diff --git a/pkg/monitor/tasks/update_monitor_resource_task.go b/pkg/monitor/tasks/update_monitor_resource_task.go index 820bb478e5..7b306ee850 100644 --- a/pkg/monitor/tasks/update_monitor_resource_task.go +++ b/pkg/monitor/tasks/update_monitor_resource_task.go @@ -35,10 +35,10 @@ func init() { } func (self *UpdateMonitorResourceJointTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) { - alert := obj.(*models.SCommonAlert) + alert := obj.(models.ICommonAlert) err := alert.UpdateMonitorResourceJoint(ctx, self.GetUserCred()) if err != nil { - msg := jsonutils.NewString(fmt.Sprintf("alert:%s UpdateMonitorResourceJoint err:%v", alert.Name, err)) + msg := jsonutils.NewString(fmt.Sprintf("alert:%s UpdateMonitorResourceJoint err:%v", alert.GetName(), err)) self.taskFail(ctx, alert, msg) return } @@ -46,9 +46,8 @@ func (self *UpdateMonitorResourceJointTask) OnInit(ctx context.Context, obj db.I self.SetStageComplete(ctx, nil) } -func (self *UpdateMonitorResourceJointTask) taskFail(ctx context.Context, alert *models.SCommonAlert, msg jsonutils.JSONObject) { +func (self *UpdateMonitorResourceJointTask) taskFail(ctx context.Context, alert models.ICommonAlert, msg jsonutils.JSONObject) { // db.OpsLog.LogEvent(alert, db.ACT_UPDATE_MONITOR_RESOURCE_JOINT, msg, self.GetUserCred()) // logclient.AddActionLogWithStartable(self, alert, logclient.ACT_UPDATE_MONITOR_RESOURCE_JOINT, msg, self.UserCred, false) self.SetStageFailed(ctx, msg) - return } diff --git a/pkg/monitor/validators/validators.go b/pkg/monitor/validators/validators.go index db9ce001db..20acd92478 100644 --- a/pkg/monitor/validators/validators.go +++ b/pkg/monitor/validators/validators.go @@ -38,7 +38,11 @@ var ( EvaluatorDefaultTypes = []string{"gt", "lt", "eq"} EvaluatorRangedTypes = []string{"within_range", "outside_range"} - CommonAlertType = []string{monitor.CommonAlertNomalAlertType, monitor.CommonAlertSystemAlertType} + CommonAlertType = []string{ + monitor.CommonAlertNomalAlertType, + monitor.CommonAlertSystemAlertType, + monitor.CommonAlertServiceAlertType, + } CommonAlertReducerFieldOpts = []string{"/"} CommonAlertNotifyTypes = []string{"email", "mobile", "dingtalk", "webconsole", "feishu"}