-
Notifications
You must be signed in to change notification settings - Fork 32
/
app.go
116 lines (100 loc) · 2.49 KB
/
app.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
110
111
112
113
114
115
116
package hosts
import (
"fmt"
"io"
"text/template"
"github.com/mackerelio/mackerel-client-go"
"github.com/mackerelio/mkr/format"
"github.com/mackerelio/mkr/mackerelclient"
)
type appLogger interface {
Log(string, string)
Error(error)
}
type hostApp struct {
client mackerelclient.Client
logger appLogger
outStream io.Writer
jqFilter string
}
type findHostsParam struct {
verbose bool
name string
service string
roles []string
statuses []string
format string
}
func (ha *hostApp) findHosts(param findHostsParam) error {
hosts, err := ha.client.FindHosts(&mackerel.FindHostsParam{
Name: param.name,
Service: param.service,
Roles: param.roles,
Statuses: param.statuses,
})
if err != nil {
return err
}
switch {
case param.format != "" && ha.jqFilter != "":
return fmt.Errorf("--format and --jq options are incompatible.")
case param.format != "":
t, err := template.New("format").Parse(param.format)
if err != nil {
return err
}
return t.Execute(ha.outStream, hosts)
case param.verbose:
return format.PrettyPrintJSON(ha.outStream, hosts, ha.jqFilter)
default:
hostsFormat := make([]*format.Host, 0)
for _, host := range hosts {
hostsFormat = append(hostsFormat, &format.Host{
ID: host.ID,
Name: host.Name,
DisplayName: host.DisplayName,
Status: host.Status,
RoleFullnames: host.GetRoleFullnames(),
IsRetired: host.IsRetired,
CreatedAt: format.ISO8601Extended(host.DateFromCreatedAt()),
IPAddresses: host.IPAddresses(),
})
}
return format.PrettyPrintJSON(ha.outStream, hostsFormat, ha.jqFilter)
}
}
type createHostParam struct {
name string
roleFullnames []string
status string
customIdentifier string
memo string
}
func (ha *hostApp) createHost(param createHostParam) error {
hostID, err := ha.client.CreateHost(&mackerel.CreateHostParam{
Name: param.name,
RoleFullnames: param.roleFullnames,
CustomIdentifier: param.customIdentifier,
Memo: param.memo,
})
if err != nil {
ha.error(err)
return err
}
ha.log("created", hostID)
if param.status != "" {
err := ha.client.UpdateHostStatus(hostID, param.status)
if err != nil {
ha.error(err)
return err
}
ha.log("updated", fmt.Sprintf("%s %s", hostID, param.status))
}
return nil
}
func (ha *hostApp) log(prefix, message string) {
ha.logger.Log(prefix, message)
}
func (ha *hostApp) error(err error) {
ha.logger.Error(err)
}