/
cmdb.go
82 lines (66 loc) · 1.68 KB
/
cmdb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package cmdb
import (
"path"
"strings"
"github.com/bougou/sail/pkg/ansible"
"github.com/mitchellh/go-homedir"
)
type CMDB struct {
Inventory *ansible.Inventory `yaml:"inventory"` // Ansible 格式的主机清单
Platforms map[string]Platform `yaml:"platforms"` // 非主机部署形态, map key is component name or 'all'
}
type Platform struct {
K8S *K8S `yaml:"k8s,omitempty"`
}
type K8S struct {
KubeConfig string `yaml:"kubeConfig"`
KubeContext string `yaml:"kubeContext"`
Namespace string `yaml:"namespace"`
}
func ExpandTilde(pathstr string) string {
if strings.HasPrefix(pathstr, "~") {
home, err := homedir.Dir()
if err != nil {
return ""
}
s := strings.Replace(pathstr, "~", "", 1)
return path.Join(home, s)
}
return pathstr
}
func NewCMDB() *CMDB {
i := ansible.NewAnsibleInventory()
i.FillAll()
return &CMDB{
Inventory: i,
Platforms: make(map[string]Platform),
}
}
func (c *CMDB) GetHostsForComponent(name string) []string {
g, err := c.Inventory.GetGroup(name)
if err != nil {
return []string{}
}
return g.HostsList()
}
func (c *CMDB) Compute(componentName string, componentEnabled bool) error {
if !componentEnabled {
c.Inventory.RemoveGroup(componentName)
return nil
}
if c.Inventory.HasGroup(componentName) {
return nil
}
compHosts := c.determineHostsForComponent(componentName)
group := ansible.NewGroup(componentName)
group.AddHosts(compHosts...)
return c.Inventory.AddGroup(group)
}
// Todo, recursively
func (c *CMDB) determineHostsForComponent(componentName string) []string {
if c.Inventory.HasGroup("_cluster") {
clusterGroup, _ := c.Inventory.GetGroup("_cluster")
return clusterGroup.HostsList()
}
return []string{}
}