forked from ghostunnel/ghostunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus_test.go
More file actions
373 lines (312 loc) · 10.3 KB
/
status_test.go
File metadata and controls
373 lines (312 loc) · 10.3 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*-
* Copyright 2015 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
// Mock net.Conn for testing
type fakeConn struct {
io.ReadWriteCloser
}
func (c fakeConn) LocalAddr() net.Addr {
return nil
}
func (c fakeConn) RemoteAddr() net.Addr {
return nil
}
func (c fakeConn) SetDeadline(t time.Time) error {
return nil
}
func (c fakeConn) SetReadDeadline(t time.Time) error {
return nil
}
func (c fakeConn) SetWriteDeadline(t time.Time) error {
return nil
}
func dummyDial(ctx context.Context) (net.Conn, error) {
f, err := os.Open(os.DevNull)
panicOnError(err)
return fakeConn{f}, nil
}
func dummyDialError(ctx context.Context) (net.Conn, error) {
return nil, errors.New("fail")
}
func TestStatusHandleWatchdogError(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip()
return
}
// Trigger watchdog functionality
os.Setenv("WATCHDOG_PID", strconv.Itoa(os.Getpid()))
os.Setenv("WATCHDOG_USEC", "X")
defer os.Unsetenv("WATCHDOG_PID")
defer os.Unsetenv("WATCHDOG_USEC")
err := handleServiceWatchdog(func() bool { return true }, nil)
if err == nil {
t.Error("handleServiceWatchdog did not handle invalid watchdog settings correctly")
}
}
func TestStatusHandleWatchdog(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip()
return
}
// Trigger watchdog functionality
os.Setenv("WATCHDOG_PID", strconv.Itoa(os.Getpid()))
os.Setenv("WATCHDOG_USEC", "1000000")
defer os.Unsetenv("WATCHDOG_PID")
defer os.Unsetenv("WATCHDOG_USEC")
// Run watchdog, kill it after one iteration
shutdown := make(chan bool, 1)
done := make(chan bool, 1)
go func() {
err := handleServiceWatchdog(func() bool {
// Send shutdown signal to stop handler
shutdown <- true
return true
}, shutdown)
if err != nil {
t.Error(err)
}
done <- true
}()
timeout := time.NewTicker(30 * time.Second)
defer timeout.Stop()
select {
case <-done:
return
case <-timeout.C:
shutdown <- true
t.Error("watchdog handler timed out, did not call health check")
return
}
}
func TestStatusHandlerNew(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
response := httptest.NewRecorder()
handler.ServeHTTP(response, &http.Request{})
if response.Code != 503 {
t.Error("status should return 503 if not yet listening")
}
if response.Header().Get("Content-Type") != "application/json" {
t.Error("status response should be application/json")
}
}
func TestStatusHandlerListeningTCP(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
response := httptest.NewRecorder()
handler.Listening()
handler.ServeHTTP(response, &http.Request{})
if response.Code != 200 {
t.Error("status should return 200 once listening")
}
if response.Header().Get("Content-Type") != "application/json" {
t.Error("status response should be application/json")
}
}
func TestStatusHandlerListeningBackendDown(t *testing.T) {
handler := newStatusHandler(dummyDialError, "", "", "", "")
response := httptest.NewRecorder()
handler.Listening()
handler.ServeHTTP(response, &http.Request{})
if response.Code != 503 {
t.Error("status should return 503 if backend is down")
}
}
func TestStatusHandlerReloading(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
response := httptest.NewRecorder()
handler.Listening()
handler.Reloading()
handler.ServeHTTP(response, &http.Request{})
if response.Code != 200 {
t.Error("status should return 200 during reload")
}
}
func TestStatusHandlerStopping(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
response := httptest.NewRecorder()
handler.Listening()
handler.Stopping()
handler.ServeHTTP(response, &http.Request{})
if response.Code != 503 {
t.Error("status should return 503 when stopping")
}
}
func TestStatusHandlerResponses(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
resp := handler.status(context.Background())
if resp.Message != "initializing" {
t.Error("status should say 'initializing' on startup")
}
handler.Listening()
resp = handler.status(context.Background())
if resp.Message != "listening" {
t.Error("status should say 'listening' after startup")
}
handler.Reloading()
resp = handler.status(context.Background())
if resp.Message != "reloading" {
t.Error("status should say 'reloading' when reload initiated")
}
handler.Stopping()
resp = handler.status(context.Background())
if resp.Message != "stopping" {
t.Error("status should say 'stopping' when shutdown initiated")
}
}
func TestStatusTargetHTTP2XX(t *testing.T) {
statusResp, statusRespCode := statusTargetWithResponseStatusCode(200)
if !statusResp.Ok || statusResp.BackendStatus != "ok" || statusRespCode != 200 {
t.Error("status should return 200 when status backend returns 200, but got:", statusResp, statusRespCode)
}
}
func TestStatusTargetHTTPNon2XX(t *testing.T) {
statusResp, statusRespCode := statusTargetWithResponseStatusCode(503)
if statusResp.Ok || statusResp.BackendStatus == "ok" || statusRespCode != 503 {
t.Error("status should return 503 when status backend returns something other than 200, but got:", statusResp, statusRespCode)
}
}
func TestStatusTargetHTTPWithError(t *testing.T) {
statusResp, statusRespCode := statusTargetWithResponseStatusCode(-1)
if statusResp.Ok || statusResp.BackendStatus == "ok" || statusRespCode != 503 {
t.Error("status should return 503 when status backend returns something other than 200, but got:", statusResp, statusRespCode)
}
}
func TestServeHTTPReturnsJSON(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
handler.Listening()
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
if response.Code != 200 {
t.Errorf("expected status 200, got %d", response.Code)
}
var resp statusResponse
if err := json.Unmarshal(response.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response body: %v", err)
}
if resp.Message != "listening" {
t.Errorf("expected message 'listening', got %q", resp.Message)
}
if !resp.Ok {
t.Error("expected ok=true when listening with working backend")
}
}
func TestServeHTTPBackendUnhealthy(t *testing.T) {
handler := newStatusHandler(dummyDialError, "", "", "", "")
handler.Listening()
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
if response.Code != http.StatusServiceUnavailable {
t.Errorf("expected status 503, got %d", response.Code)
}
if got := response.Header().Get("Content-Type"); got != "application/json" {
t.Errorf("expected Content-Type application/json, got %q", got)
}
var resp statusResponse
if err := json.Unmarshal(response.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response body: %v", err)
}
if resp.Ok {
t.Error("expected resp.Ok=false when backend dial fails")
}
if resp.BackendOk {
t.Error("expected resp.BackendOk=false when backend dial fails")
}
if resp.BackendStatus != "critical" {
t.Errorf("expected BackendStatus=critical, got %q", resp.BackendStatus)
}
if resp.BackendError == "" {
t.Error("expected non-empty BackendError describing dial failure")
}
if resp.Status != "critical" {
t.Errorf("expected top-level Status=critical, got %q", resp.Status)
}
}
func TestNonLinuxNotifyHelpersDoNotPanic(t *testing.T) {
if runtime.GOOS == "linux" {
t.Skip("Linux uses the real systemd implementation")
}
// These should not panic
notifyServiceStatus("test")
notifyServiceReady()
notifyServiceReloading()
notifyServiceStopping()
err := handleServiceWatchdog(func() bool { return true }, nil)
if err != nil {
t.Errorf("handleServiceWatchdog stub should return nil, got: %v", err)
}
}
func TestHandleWatchdogCallsSystemd(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "")
handler.Listening()
// HandleWatchdog should not panic regardless of platform
handler.HandleWatchdog()
}
// TestCheckBackendStatusInvalidURL covers the early-return error path in
// checkBackendStatus for when http.NewRequestWithContext fails to parse the
// configured statusTargetAddress. A control character in the URL is rejected
// by net/url before any dial is attempted.
func TestCheckBackendStatusInvalidURL(t *testing.T) {
handler := newStatusHandler(dummyDial, "", "", "", "http://\x7f/")
err := handler.checkBackendStatus(context.Background())
if err == nil {
t.Fatal("expected error from invalid statusTargetAddress")
}
if !strings.Contains(err.Error(), "invalid control character in URL") {
t.Errorf("error = %q, want it to mention parse failure", err.Error())
}
}
// statusTargetWithResponseStatusCode creates a stub status target that returns the status code specified by "code".
func statusTargetWithResponseStatusCode(code int) (statusResponse, int) {
statusTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
}))
defer statusTarget.Close()
response := httptest.NewRecorder()
handler := newStatusHandler(func(ctx context.Context) (net.Conn, error) {
if code < 0 {
return nil, errors.New("simulating error when talking to backend")
}
u, _ := url.Parse(statusTarget.URL) // NOTE: I tried using statusTarget.Config.Addr instead, but it wasn't set.
return net.Dial("tcp", net.JoinHostPort(u.Hostname(), u.Port()))
}, "", "", "", statusTarget.URL)
req := httptest.NewRequest(http.MethodGet, "/not-empty", nil)
handler.Listening() // NOTE: required for non-503 backend response code.
handler.ServeHTTP(response, req)
res := response.Result()
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
statusResp := statusResponse{}
_ = json.Unmarshal(data, &statusResp)
return statusResp, res.StatusCode
}