-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
257 lines (236 loc) · 7.5 KB
/
main.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/* Portions of this code are based on and/or derived from the HTTP
check found in the NCR DevOps Platform nagiosfoundation collection of
checks found at https://github.com/ncr-devops-platform/nagiosfoundation */
package main
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-go/types"
"github.com/sensu/sensu-plugin-sdk/sensu"
)
// Config represents the check plugin config.
type Config struct {
sensu.PluginConfig
URL string
SearchString string
TrustedCAFile string
InsecureSkipVerify bool
RedirectOK bool
Timeout int
Headers []string
MTLSKeyFile string
MTLSCertFile string
}
var (
tlsConfig tls.Config
plugin = Config{
PluginConfig: sensu.PluginConfig{
Name: "http-check",
Short: "HTTP Status/String Check",
Keyspace: "sensu.io/plugins/http-check/config",
},
}
options = []*sensu.PluginConfigOption{
{
Path: "url",
Env: "CHECK_URL",
Argument: "url",
Shorthand: "u",
Default: "http://localhost:80/",
Usage: "URL to test",
Value: &plugin.URL,
},
{
Path: "search-string",
Env: "CHECK_SEARCH_STRING",
Argument: "search-string",
Shorthand: "s",
Default: "",
Usage: "String to search for, if not provided do status check only",
Value: &plugin.SearchString,
},
{
Path: "insecure-skip-verify",
Env: "",
Argument: "insecure-skip-verify",
Shorthand: "i",
Default: false,
Usage: "Skip TLS certificate verification (not recommended!)",
Value: &plugin.InsecureSkipVerify,
},
{
Path: "trusted-ca-file",
Env: "",
Argument: "trusted-ca-file",
Shorthand: "t",
Default: "",
Usage: "TLS CA certificate bundle in PEM format",
Value: &plugin.TrustedCAFile,
},
{
Path: "redirect-ok",
Env: "",
Argument: "redirect-ok",
Shorthand: "r",
Default: false,
Usage: "Allow redirects",
Value: &plugin.RedirectOK,
},
{
Path: "timeout",
Env: "",
Argument: "timeout",
Shorthand: "T",
Default: 15,
Usage: "Request timeout in seconds",
Value: &plugin.Timeout,
},
{
Path: "header",
Env: "",
Argument: "header",
Shorthand: "H",
Default: []string{},
Usage: "Additional header(s) to send in check request",
Value: &plugin.Headers,
},
{
Path: "mtls-key-file",
Env: "",
Argument: "mtls-key-file",
Shorthand: "K",
Default: "",
Usage: "Key file for mutual TLS auth in PEM format",
Value: &plugin.MTLSKeyFile,
},
{
Path: "mtls-cert-file",
Env: "",
Argument: "mtls-cert-file",
Shorthand: "C",
Default: "",
Usage: "Certificate file for mutual TLS auth in PEM format",
Value: &plugin.MTLSCertFile,
},
}
)
func main() {
check := sensu.NewGoCheck(&plugin.PluginConfig, options, checkArgs, executeCheck, false)
check.Execute()
}
func checkArgs(event *types.Event) (int, error) {
if len(plugin.URL) == 0 {
return sensu.CheckStateWarning, fmt.Errorf("--url or CHECK_URL environment variable is required")
}
if len(plugin.Headers) > 0 {
for _, header := range plugin.Headers {
headerSplit := strings.SplitN(header, ":", 2)
if len(headerSplit) != 2 {
return sensu.CheckStateWarning, fmt.Errorf("--header %q value malformed should be \"Header-Name: Header Value\"", header)
}
}
}
if len(plugin.TrustedCAFile) > 0 {
caCertPool, err := corev2.LoadCACerts(plugin.TrustedCAFile)
if err != nil {
return sensu.CheckStateWarning, fmt.Errorf("Error loading specified CA file")
}
tlsConfig.RootCAs = caCertPool
}
tlsConfig.InsecureSkipVerify = plugin.InsecureSkipVerify
if (len(plugin.MTLSKeyFile) > 0 && len(plugin.MTLSCertFile) == 0) || (len(plugin.MTLSCertFile) > 0 && len(plugin.MTLSKeyFile) == 0) {
return sensu.CheckStateWarning, fmt.Errorf("mTLS auth requires both --mtls-key-file and --mtls-cert-file")
}
if len(plugin.MTLSKeyFile) > 0 && len(plugin.MTLSCertFile) > 0 {
cert, err := tls.LoadX509KeyPair(plugin.MTLSCertFile, plugin.MTLSKeyFile)
if err != nil {
return sensu.CheckStateWarning, fmt.Errorf("Failed to load mTLS key pair %s/%s: %v", plugin.MTLSCertFile, plugin.MTLSKeyFile, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return sensu.CheckStateOK, nil
}
func executeCheck(event *types.Event) (int, error) {
client := http.DefaultClient
client.Transport = http.DefaultTransport
client.Timeout = time.Duration(plugin.Timeout) * time.Second
if !plugin.RedirectOK {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
}
checkURL, err := url.Parse(plugin.URL)
if err != nil {
fmt.Printf("url parse error: %s\n", err)
return sensu.CheckStateCritical, nil
}
if checkURL.Scheme == "https" {
client.Transport.(*http.Transport).TLSClientConfig = &tlsConfig
}
req, err := http.NewRequest("GET", plugin.URL, nil)
if err != nil {
fmt.Printf("request creation error: %s\n", err)
return sensu.CheckStateCritical, nil
}
if len(plugin.Headers) > 0 {
for _, header := range plugin.Headers {
headerSplit := strings.SplitN(header, ":", 2)
headerKey := strings.TrimSpace(headerSplit[0])
headerValue := strings.TrimSpace(headerSplit[1])
if strings.EqualFold(headerKey, "host") {
req.Host = headerValue
continue
}
req.Header.Set(headerKey, headerValue)
}
}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("request error: %s\n", err)
return sensu.CheckStateCritical, nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("response body read error: %s\n", err)
return sensu.CheckStateCritical, nil
}
if len(plugin.SearchString) > 0 {
if strings.Contains(string(body), plugin.SearchString) {
fmt.Printf("%s OK: found \"%s\" at %s\n", plugin.PluginConfig.Name, plugin.SearchString, resp.Request.URL)
return sensu.CheckStateOK, nil
}
fmt.Printf("%s CRITICAL: \"%s\" not found at %s\n", plugin.PluginConfig.Name, plugin.SearchString, resp.Request.URL)
return sensu.CheckStateCritical, nil
}
switch {
case resp.StatusCode >= http.StatusBadRequest:
fmt.Printf("%s CRITICAL: HTTP Status %v for %s\n", plugin.PluginConfig.Name, resp.StatusCode, plugin.URL)
return sensu.CheckStateCritical, nil
// resp.StatusCode will ultimately be 200 for successful redirects
// so instead we check to see if the current URL matches the requested
// URL
case resp.Request.URL.String() != plugin.URL && plugin.RedirectOK:
fmt.Printf("%s OK: HTTP Status %v for %s (redirect from %s)\n", plugin.PluginConfig.Name, resp.StatusCode, resp.Request.URL, plugin.URL)
return sensu.CheckStateOK, nil
// But, if we've disabled redirects, this should work
case resp.StatusCode >= http.StatusMultipleChoices:
var extra string
redirectURL := resp.Header.Get("Location")
if len(redirectURL) > 0 {
extra = fmt.Sprintf(" (redirects to %s)", redirectURL)
}
fmt.Printf("%s WARNING: HTTP Status %v for %s %s\n", plugin.PluginConfig.Name, resp.StatusCode, plugin.URL, extra)
return sensu.CheckStateWarning, nil
case resp.StatusCode == -1:
fmt.Printf("%s UNKNOWN: HTTP Status %v for %s\n", plugin.PluginConfig.Name, resp.StatusCode, plugin.URL)
return sensu.CheckStateUnknown, nil
default:
fmt.Printf("%s OK: HTTP Status %v for %s\n", plugin.PluginConfig.Name, resp.StatusCode, plugin.URL)
return sensu.CheckStateOK, nil
}
}