forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.go
195 lines (155 loc) · 4.86 KB
/
http_client.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package monit
import (
"encoding/xml"
"io"
"net/http"
"net/url"
"path"
"strings"
"golang.org/x/net/html/charset"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . HTTPClient
type HTTPClient interface {
Do(request *http.Request) (*http.Response, error)
}
type httpClient struct {
startClient HTTPClient
stopClient HTTPClient
unmonitorClient HTTPClient
statusClient HTTPClient
host string
username string
password string
logger boshlog.Logger
}
// NewHTTPClient creates a new monit client
//
// status & start use the shortClient
// unmonitor & stop use the longClient
func NewHTTPClient(
host, username, password string,
shortClient HTTPClient,
longClient HTTPClient,
logger boshlog.Logger,
) Client {
return httpClient{
host: host,
username: username,
password: password,
startClient: shortClient,
stopClient: longClient,
unmonitorClient: longClient,
statusClient: shortClient,
logger: logger,
}
}
func (c httpClient) ServicesInGroup(name string) (services []string, err error) {
status, err := c.status()
if err != nil {
return nil, bosherr.WrapError(err, "Getting status from Monit")
}
serviceGroup, found := status.ServiceGroups.Get(name)
if !found {
return []string{}, nil
}
return serviceGroup.Services, nil
}
func (c httpClient) StartService(serviceName string) error {
response, err := c.makeRequest(c.startClient, c.monitURL(serviceName), "POST", "action=start")
if err != nil {
return bosherr.WrapError(err, "Sending start request to monit")
}
defer response.Body.Close()
err = c.validateResponse(response)
if err != nil {
return bosherr.WrapErrorf(err, "Starting Monit service %s", serviceName)
}
return nil
}
func (c httpClient) StopService(serviceName string) error {
var response *http.Response
response, err := c.makeRequest(c.stopClient, c.monitURL(serviceName), "POST", "action=stop")
if err != nil {
return bosherr.WrapErrorf(err, "Sending stop request for service '%s'", serviceName)
}
defer response.Body.Close()
err = c.validateResponse(response)
if err != nil {
return bosherr.WrapErrorf(err, "Stopping Monit service '%s'", serviceName)
}
return nil
}
func (c httpClient) UnmonitorService(serviceName string) error {
response, err := c.makeRequest(c.unmonitorClient, c.monitURL(serviceName), "POST", "action=unmonitor")
if err != nil {
return bosherr.WrapError(err, "Sending unmonitor request to monit")
}
defer response.Body.Close()
err = c.validateResponse(response)
if err != nil {
return bosherr.WrapErrorf(err, "Unmonitoring Monit service %s", serviceName)
}
return nil
}
func (c httpClient) Status() (Status, error) {
return c.status()
}
func (c httpClient) status() (status, error) {
c.logger.Debug("http-client", "status function called")
url := c.monitURL("_status2")
url.RawQuery = "format=xml"
response, err := c.makeRequest(c.statusClient, url, "GET", "")
if err != nil {
return status{}, bosherr.WrapError(err, "Sending status request to monit")
}
defer func() {
if err = response.Body.Close(); err != nil {
c.logger.Warn("http-client", "Failed to close monit status GET response body: %s", err.Error())
}
}()
err = c.validateResponse(response)
if err != nil {
return status{}, bosherr.WrapError(err, "Getting monit status")
}
decoder := xml.NewDecoder(response.Body)
decoder.CharsetReader = charset.NewReaderLabel
var st status
err = decoder.Decode(&st)
if err != nil {
return status{}, bosherr.WrapError(err, "Unmarshalling Monit status")
}
for _, stat := range st.Services.Services {
c.logger.Debug("http-client", "Unmarshalled Monit status: %+v", stat)
}
return st, nil
}
func (c httpClient) monitURL(thing string) url.URL {
return url.URL{
Scheme: "http",
Host: c.host,
Path: path.Join("/", thing),
}
}
func (c httpClient) validateResponse(response *http.Response) error {
if response.StatusCode == http.StatusOK {
return nil
}
body, err := io.ReadAll(response.Body)
if err != nil {
return bosherr.WrapError(err, "Reading body of failed Monit response")
}
c.logger.Debug("http-client", "Request failed with %s: %s", response.Status, string(body))
return bosherr.Errorf("Request failed with %s: %s", response.Status, string(body))
}
func (c httpClient) makeRequest(client HTTPClient, target url.URL, method, requestBody string) (*http.Response, error) {
c.logger.Debug("http-client", "Monit request: url='%s' body='%s'", target.String(), requestBody)
request, err := http.NewRequest(method, target.String(), strings.NewReader(requestBody)) //nolint:noctx
if err != nil {
return nil, err
}
request.SetBasicAuth(c.username, c.password)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return client.Do(request)
}