fix: 修复主机组多项bug - 组列表/成员数/主机保存/前端显示

This commit is contained in:
Hermes Agent
2026-05-13 18:34:54 +08:00
förälder 9c1f44e91a
incheckning 6a7f74aac5
5 ändrade filer med 114 tillägg och 63 borttagningar
+53 -21
Visa fil
@@ -47,10 +47,30 @@ func NewAnsibleService(cfg *Config) *AnsibleService {
// 加载现有数据
svc.loadHosts()
svc.loadGroups()
return svc
}
// loadGroups 加载主机组列表
func (s *AnsibleService) loadGroups() {
groupsFile := filepath.Join(s.config.InventoryDir, "groups.json")
data, err := os.ReadFile(groupsFile)
if err != nil {
return
}
var groups map[string]models.HostGroup
if err := json.Unmarshal(data, &groups); err == nil {
for name, g := range groups {
if name != "all" && name != "ungrouped" {
gcopy := g
s.groups[name] = &gcopy
}
}
}
}
// generateID 生成唯一ID
func (s *AnsibleService) generateID() string {
hash := md5.New()
@@ -121,22 +141,22 @@ func (s *AnsibleService) loadHosts() {
var hosts []models.Host
if err := json.Unmarshal(data, &hosts); err == nil {
for _, h := range hosts {
hcopy := h
if hcopy.ID == "" {
hcopy.ID = s.generateID()
}
if hcopy.Port == 0 {
hcopy.Port = 22
}
if hcopy.Username == "" {
hcopy.Username = "root"
}
if hcopy.Status == "" {
hcopy.Status = "pending"
}
s.hosts[hcopy.ID] = &hcopy
for _, h := range hosts {
host := h // 避免循环变量指针问题
if host.ID == "" {
host.ID = s.generateID()
}
if host.Port == 0 {
host.Port = 22
}
if host.Username == "" {
host.Username = "root"
}
if host.Status == "" {
host.Status = "pending"
}
s.hosts[host.ID] = &host
}
// 保存以持久化补全的字段
s.saveHosts()
}
@@ -147,7 +167,13 @@ func (s *AnsibleService) saveHosts() error {
hostsFile := filepath.Join(s.config.InventoryDir, "hosts.json")
var hosts []models.Host
for _, h := range s.hosts {
hosts = append(hosts, *h)
hcopy := *h
// 确保每个主机都有ID,并更新map中的指针
if hcopy.ID == "" {
hcopy.ID = s.generateID()
h.ID = hcopy.ID // 更新map中的指针
}
hosts = append(hosts, hcopy)
}
data, _ := json.MarshalIndent(hosts, "", " ")
@@ -246,15 +272,21 @@ func (s *AnsibleService) ListGroups() []models.HostGroup {
var groups []models.HostGroup
for _, g := range s.groups {
gcopy := *g
// 展开组内主机的详细信息
// 动态展开组内主机(通过 host.Groups 字段关联,而非 group.Hosts
var hostList []models.Host
for _, hName := range g.Hosts {
for _, h := range s.hosts {
if h.Name == hName {
hostList = append(hostList, *h)
for _, h := range s.hosts {
for _, hGroup := range h.Groups {
if hGroup == gcopy.Name {
hcopy := *h
hostList = append(hostList, hcopy)
break
}
}
// 也检查主机的默认组(all/ungrouped
if len(h.Groups) == 0 && gcopy.Name == "ungrouped" {
hcopy := *h
hostList = append(hostList, hcopy)
}
}
gcopy.HostList = hostList
groups = append(groups, gcopy)