This repository has been archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentity.go
109 lines (100 loc) · 2.28 KB
/
entity.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package mackerel
import (
"errors"
"github.com/mackerelio-labs/mackerelexporter-go/internal/tag"
"github.com/mackerelio/mackerel-client-go"
)
func (e *Exporter) registerService(name string) error {
if _, ok := e.serviceRoles[name]; ok {
return nil
}
a, err := e.c.FindServices()
if err != nil {
return err
}
for _, s := range a {
if s.Name == name {
e.serviceRoles[name] = make(map[string]struct{})
return nil
}
}
param := mackerel.CreateServiceParam{
Name: name,
}
if _, err = e.c.CreateService(¶m); err != nil {
return err
}
e.serviceRoles[name] = make(map[string]struct{})
return nil
}
func (e *Exporter) registerServiceRole(s, role string) error {
if err := e.registerService(s); err != nil {
return err
}
if _, ok := e.serviceRoles[s][role]; ok {
return nil
}
a, err := e.c.FindRoles(s)
if err != nil {
return err
}
for _, r := range a {
if r.Name == role {
e.serviceRoles[s][role] = struct{}{}
return nil
}
}
param := mackerel.CreateRoleParam{
Name: role,
}
if _, err := e.c.CreateRole(s, ¶m); err != nil {
return err
}
e.serviceRoles[s][role] = struct{}{}
return nil
}
// upsertHost update or insert the host with r.
func (e *Exporter) upsertHost(r *tag.Resource) (string, error) {
param := mackerel.CreateHostParam{
Name: r.Hostname(),
CustomIdentifier: r.CustomIdentifier(),
}
if roleFullname := r.RoleFullname(); roleFullname != "" {
s := r.ServiceName()
role := r.RoleName()
if err := e.registerServiceRole(s, role); err != nil {
return "", err
}
param.RoleFullnames = []string{roleFullname}
}
if r.Cloud.Provider != "" {
param.Meta = mackerel.HostMeta{
Cloud: &mackerel.Cloud{
Provider: r.Cloud.Provider,
},
}
}
hostID, err := e.lookupHostID(param.CustomIdentifier)
if err != nil {
return "", err
}
if hostID == "" {
return e.c.CreateHost(¶m)
}
return e.c.UpdateHost(hostID, (*mackerel.UpdateHostParam)(¶m))
}
func (e *Exporter) lookupHostID(customIdentifier string) (string, error) {
if customIdentifier == "" {
return "", errors.New("customIdentifier must be specified")
}
a, err := e.c.FindHosts(&mackerel.FindHostsParam{
CustomIdentifier: customIdentifier,
})
if err != nil {
return "", err
}
if len(a) == 0 {
return "", nil
}
return a[0].ID, nil
}