diff --git a/pkg/apis/compute/loadbalancercluster.go b/pkg/apis/compute/loadbalancercluster.go index 48498b5bf7..452997380f 100644 --- a/pkg/apis/compute/loadbalancercluster.go +++ b/pkg/apis/compute/loadbalancercluster.go @@ -22,6 +22,8 @@ type LoadbalancerClusterDetails struct { WireResourceInfoBase SLoadbalancerCluster + + RefCounts map[string]int } type LoadbalancerClusterResourceInfo struct { diff --git a/pkg/compute/models/loadbalancerclusters.go b/pkg/compute/models/loadbalancerclusters.go index 677c6dce6f..f80964921f 100644 --- a/pkg/compute/models/loadbalancerclusters.go +++ b/pkg/compute/models/loadbalancerclusters.go @@ -238,26 +238,40 @@ func (lbc *SLoadbalancerCluster) ValidateUpdateData( } func (lbc *SLoadbalancerCluster) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error { - men := []db.IModelManager{ - LoadbalancerManager, + refCnts, err := lbc.refCounts() + if err != nil { + return errors.Wrap(err, "refCounts") } - lbcId := lbc.Id - for _, man := range men { - t := man.TableSpec().Instance() - n, err := t.Query(). - Equals("cluster_id", lbcId). - CountWithError() - if err != nil { - return httperrors.NewInternalServerError("get lbcluster refcount fail %v", err) - } - if n > 0 { - return httperrors.NewResourceBusyError("lbcluster %s(%s) is still referred to by %d %s", - lbcId, lbc.Name, n, man.KeywordPlural()) - } + errs := make([]error, 0) + for k, cnt := range refCnts { + errs = append(errs, httperrors.NewResourceBusyError("lbcluster %s(%s) is still referred to by %d %s", + lbc.Id, lbc.Name, cnt, k)) + } + if len(errs) > 0 { + return errors.NewAggregate(errs) } return lbc.SStandaloneResourceBase.ValidateDeleteCondition(ctx, nil) } +func (lbc *SLoadbalancerCluster) refCounts() (map[string]int, error) { + ret := make(map[string]int) + men := []db.IModelManager{ + LoadbalancerManager, + LoadbalancerAgentManager, + } + for _, man := range men { + q := man.Query().Equals("cluster_id", lbc.Id) + n, err := q.CountWithError() + if err != nil { + return nil, httperrors.NewInternalServerError("get lbcluster refcount fail %v", err) + } + if n > 0 { + ret[man.KeywordPlural()] = n + } + } + return ret, nil +} + func (man *SLoadbalancerClusterManager) FetchCustomizeColumns( ctx context.Context, userCred mcclient.TokenCredential, @@ -278,6 +292,8 @@ func (man *SLoadbalancerClusterManager) FetchCustomizeColumns( ZoneResourceInfo: zoneRows[i], WireResourceInfoBase: wireRows[i].WireResourceInfoBase, } + lbc := objs[i].(*SLoadbalancerCluster) + rows[i].RefCounts, _ = lbc.refCounts() } return rows