From 067f2773e608161532cc61b1ef7045162fdf05ed Mon Sep 17 00:00:00 2001 From: Zexi Li Date: Mon, 24 Nov 2025 21:34:26 +0800 Subject: [PATCH] feat(monitor): get records of monitor_resource_alert (#23825) --- pkg/monitor/models/monitor_resource.go | 14 ++++++++++++-- pkg/monitor/models/monitor_resource_alert.go | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/pkg/monitor/models/monitor_resource.go b/pkg/monitor/models/monitor_resource.go index b0c23e42c9..d0b1e3ddae 100644 --- a/pkg/monitor/models/monitor_resource.go +++ b/pkg/monitor/models/monitor_resource.go @@ -131,6 +131,17 @@ func (manager *SMonitorResourceManager) GetMonitorResources(input monitor.Monito return monitorResources, nil } +func (man *SMonitorResourceManager) GetMonitorResourceByResId(id string) (*SMonitorResource, error) { + resources, err := MonitorResourceManager.GetMonitorResources(monitor.MonitorResourceListInput{ResId: []string{id}}) + if err != nil { + return nil, errors.Wrapf(err, "SMonitorResourceManager GetMonitorResources by resId: %s", id) + } + if len(resources) == 0 { + return nil, errors.Errorf("SMonitorResourceManager GetMonitorResources by resId: %s not found", id) + } + return &resources[0], nil +} + type SdeleteRes struct { resType string notIn []string @@ -326,8 +337,7 @@ func (self *SMonitorResource) DetachJoint(ctx context.Context, userCred mcclient } func (self *SMonitorResource) getMoreDetails(out monitor.MonitorResourceDetails) monitor.MonitorResourceDetails { - joints, err := MonitorResourceAlertManager.GetJoinsByListInput(monitor. - MonitorResourceJointListInput{MonitorResourceId: self.ResId}) + joints, err := MonitorResourceAlertManager.GetJoinsByListInput(monitor.MonitorResourceJointListInput{MonitorResourceId: self.ResId}) if err != nil { log.Errorf("getMoreDetails err:%v", err) } diff --git a/pkg/monitor/models/monitor_resource_alert.go b/pkg/monitor/models/monitor_resource_alert.go index f161a40210..7f60aeaac7 100644 --- a/pkg/monitor/models/monitor_resource_alert.go +++ b/pkg/monitor/models/monitor_resource_alert.go @@ -374,3 +374,19 @@ func (m *SMonitorResourceAlertManager) GetResourceAlert(alertId string, resource } return obj, nil } + +// GetAlertRecords 通过 MonitorResourceAlert 查询历史的 AlertRecord +// 查询条件:相同的 AlertId 且 ResIds 包含该 MonitorResourceId 的所有记录 +func (obj *SMonitorResourceAlert) GetAlertRecords() ([]SAlertRecord, error) { + records := make([]SAlertRecord, 0) + q := AlertRecordManager.Query() + q = q.Equals("alert_id", obj.AlertId) + // ResIds 字段存储的是逗号分隔的资源ID列表,使用 ContainsAny 查询 + q = q.Filter(sqlchemy.ContainsAny(q.Field("res_ids"), []string{obj.MonitorResourceId})) + q = q.Desc("created_at") // 按创建时间倒序,最新的在前 + err := db.FetchModelObjects(AlertRecordManager, q, &records) + if err != nil { + return nil, errors.Wrapf(err, "get historical alert records by alert_id: %q, monitor_resource_id: %q", obj.AlertId, obj.MonitorResourceId) + } + return records, nil +}