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
|
package bootstrap
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path"
"strconv"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type mockUpgrader struct {
exit chan struct{}
hasParent bool
}
func (m *mockUpgrader) Exit() <-chan struct{} {
return m.exit
}
func (m *mockUpgrader) HasParent() bool {
return m.hasParent
}
func (m *mockUpgrader) Ready() error { return nil }
func (m *mockUpgrader) Upgrade() error {
// to upgrade we close the exit channel
close(m.exit)
return nil
}
type testServer struct {
server *http.Server
listeners map[string]net.Listener
url string
}
func (s *testServer) slowRequest(duration time.Duration) <-chan error {
done := make(chan error)
go func() {
r, err := http.Get(fmt.Sprintf("%sslow?seconds=%d", s.url, int(duration.Seconds())))
if r != nil {
r.Body.Close()
}
done <- err
}()
return done
}
func TestCreateUnixListener(t *testing.T) {
socketPath := path.Join(os.TempDir(), "gitaly-test-unix-socket")
if err := os.Remove(socketPath); err != nil {
require.True(t, os.IsNotExist(err), "cannot delete dangling socket: %v", err)
}
// simulate a dangling socket
require.NoError(t, ioutil.WriteFile(socketPath, nil, 0755))
listen := func(network, addr string) (net.Listener, error) {
require.Equal(t, "unix", network)
require.Equal(t, socketPath, addr)
return net.Listen(network, addr)
}
u := &mockUpgrader{}
b, err := _new(u, listen, false)
require.NoError(t, err)
// first boot
l, err := b.listen("unix", socketPath)
require.NoError(t, err, "failed to bind on first boot")
require.NoError(t, l.Close())
// simulate binding during an upgrade
u.hasParent = true
l, err = b.listen("unix", socketPath)
require.NoError(t, err, "failed to bind on upgrade")
require.NoError(t, l.Close())
}
func waitWithTimeout(t *testing.T, waitCh <-chan error, timeout time.Duration) error {
select {
case <-time.After(timeout):
t.Fatal("time out waiting for waitCh")
case waitErr := <-waitCh:
return waitErr
}
return nil
}
func TestImmediateTerminationOnSocketError(t *testing.T) {
b, server := makeBootstrap(t)
waitCh := make(chan error)
go func() { waitCh <- b.Wait(2 * time.Second) }()
require.NoError(t, server.listeners["tcp"].Close(), "Closing first listener")
err := waitWithTimeout(t, waitCh, 1*time.Second)
require.Error(t, err)
require.Contains(t, err.Error(), "use of closed network connection")
}
func TestImmediateTerminationOnSignal(t *testing.T) {
for _, sig := range []syscall.Signal{syscall.SIGTERM, syscall.SIGINT} {
t.Run(sig.String(), func(t *testing.T) {
b, server := makeBootstrap(t)
done := server.slowRequest(3 * time.Minute)
waitCh := make(chan error)
go func() { waitCh <- b.Wait(2 * time.Second) }()
// make sure we are inside b.Wait() or we'll kill the test suite
time.Sleep(100 * time.Millisecond)
self, err := os.FindProcess(os.Getpid())
require.NoError(t, err)
require.NoError(t, self.Signal(sig))
waitErr := waitWithTimeout(t, waitCh, 1*time.Second)
require.Error(t, waitErr)
require.Contains(t, waitErr.Error(), "received signal")
require.Contains(t, waitErr.Error(), sig.String())
server.server.Close()
require.Error(t, <-done)
})
}
}
func TestGracefulTerminationStuck(t *testing.T) {
b, server := makeBootstrap(t)
err := testGracefulUpdate(t, server, b, 3*time.Second, 2*time.Second, nil)
require.Contains(t, err.Error(), "grace period expired")
}
func TestGracefulTerminationWithSignals(t *testing.T) {
self, err := os.FindProcess(os.Getpid())
require.NoError(t, err)
for _, sig := range []syscall.Signal{syscall.SIGTERM, syscall.SIGINT} {
t.Run(sig.String(), func(t *testing.T) {
b, server := makeBootstrap(t)
err := testGracefulUpdate(t, server, b, 1*time.Second, 2*time.Second, func() {
require.NoError(t, self.Signal(sig))
})
require.Contains(t, err.Error(), "force shutdown")
})
}
}
func TestGracefulTerminationServerErrors(t *testing.T) {
b, server := makeBootstrap(t)
done := make(chan error, 1)
// This is a simulation of receiving a listener error during waitGracePeriod
b.StopAction = func() {
// we close the unix listener in order to test that the shutdown will not fail, but it keep waiting for the TCP request
require.NoError(t, server.listeners["unix"].Close())
// we start a new TCP request that if faster than the grace period
req := server.slowRequest(time.Second)
done <- <-req
close(done)
server.server.Shutdown(context.Background())
}
err := testGracefulUpdate(t, server, b, 3*time.Second, 2*time.Second, nil)
require.Contains(t, err.Error(), "grace period expired")
require.NoError(t, <-done)
}
func TestGracefulTermination(t *testing.T) {
b, server := makeBootstrap(t)
// Using server.Close we bypass the graceful shutdown faking a completed shutdown
b.StopAction = func() { server.server.Close() }
err := testGracefulUpdate(t, server, b, 1*time.Second, 2*time.Second, nil)
require.Contains(t, err.Error(), "completed")
}
func TestPortReuse(t *testing.T) {
var addr string
b, err := New()
require.NoError(t, err)
l, err := b.listen("tcp", "0.0.0.0:")
require.NoError(t, err, "failed to bind")
addr = l.Addr().String()
_, port, err := net.SplitHostPort(addr)
require.NoError(t, err)
l, err = b.listen("tcp", "0.0.0.0:"+port)
require.NoError(t, err, "failed to bind")
require.NoError(t, l.Close())
}
func testGracefulUpdate(t *testing.T, server *testServer, b *Bootstrap, waitTimeout, gracefulWait time.Duration, duringGracePeriodCallback func()) error {
waitCh := make(chan error)
go func() { waitCh <- b.Wait(gracefulWait) }()
// Start a slow request to keep the old server from shutting down immediately.
req := server.slowRequest(2 * gracefulWait)
// make sure slow request is being handled
time.Sleep(100 * time.Millisecond)
// Simulate an upgrade request after entering into the blocking b.Wait() and during the slowRequest execution
b.upgrader.Upgrade()
if duringGracePeriodCallback != nil {
// make sure we are on the grace period
time.Sleep(100 * time.Millisecond)
duringGracePeriodCallback()
}
waitErr := waitWithTimeout(t, waitCh, waitTimeout)
require.Error(t, waitErr)
require.Contains(t, waitErr.Error(), "graceful upgrade")
server.server.Close()
clientErr := waitWithTimeout(t, req, 1*time.Second)
require.Error(t, clientErr, "slow request not terminated after the grace period")
return waitErr
}
func makeBootstrap(t *testing.T) (*Bootstrap, *testServer) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
})
mux.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
sec, err := strconv.Atoi(r.URL.Query().Get("seconds"))
require.NoError(t, err)
t.Logf("Serving a slow request for %d seconds", sec)
time.Sleep(time.Duration(sec) * time.Second)
w.WriteHeader(200)
})
s := http.Server{Handler: mux}
u := &mockUpgrader{exit: make(chan struct{})}
b, err := _new(u, net.Listen, false)
require.NoError(t, err)
b.StopAction = func() { s.Shutdown(context.Background()) }
listeners := make(map[string]net.Listener)
start := func(network, address string) Starter {
return func(listen ListenFunc, errors chan<- error) error {
l, err := listen(network, address)
if err != nil {
return err
}
listeners[network] = l
go func() {
errors <- s.Serve(l)
}()
return nil
}
}
for network, address := range map[string]string{
"tcp": "127.0.0.1:0",
"unix": path.Join(os.TempDir(), "gitaly-test-unix-socket"),
} {
b.RegisterStarter(start(network, address))
}
require.NoError(t, b.Start())
require.Equal(t, 2, len(listeners))
// test connection
testAllListeners(t, listeners)
addr := listeners["tcp"].Addr()
url := fmt.Sprintf("http://%s/", addr.String())
return b, &testServer{
server: &s,
listeners: listeners,
url: url,
}
}
func testAllListeners(t *testing.T, listeners map[string]net.Listener) {
for network, listener := range listeners {
addr := listener.Addr().String()
// overriding Client.Transport.Dial we can connect to TCP and UNIX sockets
client := &http.Client{
Transport: &http.Transport{
Dial: func(_, _ string) (net.Conn, error) {
return net.Dial(network, addr)
},
},
}
// we don't need a real address because we forced it on Dial
r, err := client.Get("http://fakeHost/")
require.NoError(t, err)
r.Body.Close()
require.Equal(t, 200, r.StatusCode)
}
}
|