bugfix: 主机分组不可过深,并防止死循环的host分组 (#2886)

* bugfix: 主机分组不可过深,并防止死循环的host分组

* bugfix: 主机分组不可过深,并防止死循环的host分组

Signed-off-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>

bugfix: 主机分组不可过深,并防止死循环的host分组

Signed-off-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>

bugfix: 主机分组不可过深,并防止死循环的host分组

Signed-off-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>

bugfix: 主机分组不可过深,并防止死循环的host分组

Signed-off-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>

---------

Signed-off-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>
Co-authored-by: xuesongzuo@yunify.com <xuesongzuo@yunify.com>
This commit is contained in:
Mr-Mu 2025-12-08 16:45:56 +08:00 committed by GitHub
parent 782b65a36d
commit 0c859e8e1f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 5 deletions

View File

@ -33,6 +33,7 @@ import (
_const "github.com/kubesphere/kubekey/v4/pkg/const"
"github.com/kubesphere/kubekey/v4/pkg/converter/tmpl"
"github.com/kubesphere/kubekey/v4/pkg/utils"
)
// CombineVariables merge multiple variables into one variable.
@ -149,8 +150,10 @@ func ConvertGroup(inv kkcorev1.Inventory) map[string][]string {
groups[_const.VariableGroupsAll] = all
groupsGraph := utils.NewKahnGraph()
for gn := range inv.Spec.Groups {
groups[gn] = hostsInGroup(inv, gn)
groups[gn] = hostsInGroup(inv, gn, groupsGraph)
if hosts, ok := groups[gn]; ok {
for _, v := range hosts {
if slices.Contains(ungrouped, v) {
@ -167,16 +170,21 @@ func ConvertGroup(inv kkcorev1.Inventory) map[string][]string {
// hostsInGroup get a host_name slice in a given group
// if the given group contains other group. convert other group to host_name slice.
func hostsInGroup(inv kkcorev1.Inventory, groupName string) []string {
func hostsInGroup(inv kkcorev1.Inventory, groupName string, groupsGraph *utils.KahnGraph) []string {
if v, ok := inv.Spec.Groups[groupName]; ok {
var hosts []string
for _, cg := range v.Groups {
hosts = CombineSlice(hostsInGroup(inv, cg), hosts)
if groupsGraph != nil {
if groupsGraph.AddEdgeAndCheckCycle(groupName, cg) {
klog.Warningf("group host found cycle by %s -> %s", groupName, cg)
return []string{}
}
}
hosts = CombineSlice(hostsInGroup(inv, cg, groupsGraph), hosts)
}
return CombineSlice(hosts, v.Hosts)
}
return make([]string, 0)
}

View File

@ -22,6 +22,8 @@ import (
kkcorev1 "github.com/kubesphere/kubekey/api/core/v1"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime"
"github.com/kubesphere/kubekey/v4/pkg/utils"
)
func TestCombineSlice(t *testing.T) {
@ -126,7 +128,7 @@ func TestHostsInGroup(t *testing.T) {
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
assert.ElementsMatch(t, tc.except, hostsInGroup(tc.inventory, tc.groupName))
assert.ElementsMatch(t, tc.except, hostsInGroup(tc.inventory, tc.groupName, utils.NewKahnGraph()))
})
}
}