mirror of
https://github.com/netbirdio/netbird.git
synced 2026-10-08 22:49:10 +02:00
* [relay] Bind listeners before serving to fix the shutdown race A shutdown signal that arrives while the relay is still starting races the listener goroutines. Server.Shutdown read the listener's server field while Listen was writing it, which the race detector reported, and when Shutdown won it saw a nil server, returned as if nothing was running, and the listener then bound and served with nothing left to stop it. Server.Listen never returned and the process hung on exit. The listener lifecycle is now split into Bind and Serve. Server.Listen binds every listener under its mutex before spawning the accept loops, so the fields Shutdown reads are written before the goroutines exist. A closed flag on the server makes a Listen that runs after Shutdown return without binding. A bind failure on one listener shuts down the ones already bound and surfaces the error at once instead of holding it in a channel until the surviving listener exits. * [relay] Mark the server closed before shutting down the relay Shutdown set the closed flag only after the relay had finished closing peers, so a Listen that started during that window could bind sockets and start serving on a server that was already going down. The flag is now set under listenerMux before the relay shutdown, and Accept closes connections it receives once the relay is closed instead of leaving them to the client's timeout. The tests now cover the public Listen bind failure and a QUIC listener shut down while blocked in Accept, and they pick ports that are free for both TCP and UDP, reporting a bind error instead of a timeout. * Fix tests * [relay] Test the Listen and Shutdown race and the QUIC bind rollback The existing tests order Listen and Shutdown deterministically, so the race the fix targets was never exercised. A new test fires both from a shared start channel across repeated rounds so either side can take the lock first, and fails on the hang the old code produced. The rollback test now drives Server.Listen with the real ws and quic listeners and a UDP blocker, so the ws socket is bound and released when the quic bind fails. Both tests pass a real TLS config because a nil one only yields a quic listener in the devcert build. * [relay] Bound the Shutdown wait in the concurrent Listen and Shutdown test * [relay] Keep the default WS port for an empty listen address net.Listen picks a random port for an empty address, while ListenAndServe used :http or :https. Apply the same default in Bind so an empty address keeps listening where it did before. * [relay] Release the WS socket when Serve fails ServeTLS can return before it takes ownership of the listener, for example when no certificate is configured, leaving the socket opened in Bind bound until Shutdown. Close it in Serve on any error other than a server close. * [relay] Drain the relay outside the listener lock Shutdown held listenerMux while the relay closed its peers gracefully, so ListenerProtocols, and with it the healthcheck, blocked for the whole drain. Mark the server closed and take the listeners under the lock, then drain and stop them after releasing it. The closed flag still keeps Listen from registering new listeners.
231 lines
6.7 KiB
Go
231 lines
6.7 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"math/big"
|
|
"net"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/netbirdio/netbird/relay/server/listener/quic"
|
|
"github.com/netbirdio/netbird/shared/relay/auth/allow"
|
|
)
|
|
|
|
func TestServer_ShutdownBeforeListen(t *testing.T) {
|
|
addr := freeAddress(t)
|
|
srv := newTestServer(t, addr)
|
|
require.NoError(t, srv.Shutdown(context.Background()))
|
|
|
|
errChan := make(chan error, 1)
|
|
go func() {
|
|
errChan <- srv.Listen(ListenerConfig{Address: addr})
|
|
}()
|
|
|
|
assert.NoError(t, waitForReturn(t, "Listen", errChan))
|
|
assert.Empty(t, srv.ListenerProtocols(), "a shut down server must not register listeners")
|
|
requireAddressFree(t, addr)
|
|
}
|
|
|
|
func TestServer_ShutdownStopsListen(t *testing.T) {
|
|
addr := freeAddress(t)
|
|
srv := newTestServer(t, addr)
|
|
|
|
errChan := make(chan error, 1)
|
|
go func() {
|
|
errChan <- srv.Listen(ListenerConfig{Address: addr})
|
|
}()
|
|
|
|
waitForListeners(t, srv, errChan)
|
|
|
|
require.NoError(t, srv.Shutdown(context.Background()))
|
|
assert.NoError(t, waitForReturn(t, "Listen", errChan))
|
|
requireAddressFree(t, addr)
|
|
}
|
|
|
|
func TestServer_ConcurrentListenAndShutdown(t *testing.T) {
|
|
tlsCfg := testTLSConfig(t)
|
|
for round := 0; round < 20; round++ {
|
|
t.Run(fmt.Sprintf("round-%d", round), func(t *testing.T) {
|
|
addr := freeAddress(t)
|
|
srv := newTestServer(t, addr)
|
|
|
|
start := make(chan struct{})
|
|
listenErr := make(chan error, 1)
|
|
shutdownErr := make(chan error, 1)
|
|
go func() {
|
|
<-start
|
|
listenErr <- srv.Listen(ListenerConfig{Address: addr, TLSConfig: tlsCfg})
|
|
}()
|
|
go func() {
|
|
<-start
|
|
shutdownErr <- srv.Shutdown(context.Background())
|
|
}()
|
|
close(start)
|
|
|
|
// Either side may take the lock first: Listen then returns without binding,
|
|
// or Shutdown stops its accept loops. Listen must return in both cases.
|
|
assert.NoError(t, waitForReturn(t, "Listen", listenErr))
|
|
assert.NoError(t, waitForReturn(t, "Shutdown", shutdownErr))
|
|
assert.Empty(t, srv.ListenerProtocols(), "no listener may stay registered after shutdown")
|
|
requireAddressFree(t, addr)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestServer_ListenReturnsBindError(t *testing.T) {
|
|
blocker, err := net.Listen("tcp", "127.0.0.1:0")
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() { _ = blocker.Close() })
|
|
addr := blocker.Addr().String()
|
|
srv := newTestServer(t, addr)
|
|
|
|
errChan := make(chan error, 1)
|
|
go func() {
|
|
errChan <- srv.Listen(ListenerConfig{Address: addr})
|
|
}()
|
|
|
|
assert.Error(t, waitForReturn(t, "Listen", errChan), "Listen must return the bind error instead of serving")
|
|
assert.Empty(t, srv.ListenerProtocols(), "a failed Listen must not register listeners")
|
|
|
|
require.NoError(t, blocker.Close())
|
|
requireAddressFree(t, addr)
|
|
}
|
|
|
|
func TestServer_ListenRollsBackOnBindError(t *testing.T) {
|
|
addr := freeAddress(t)
|
|
blocker, err := net.ListenPacket("udp", addr)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() { _ = blocker.Close() })
|
|
srv := newTestServer(t, addr)
|
|
tlsCfg := testTLSConfig(t)
|
|
|
|
errChan := make(chan error, 1)
|
|
go func() {
|
|
errChan <- srv.Listen(ListenerConfig{Address: addr, TLSConfig: tlsCfg})
|
|
}()
|
|
|
|
err = waitForReturn(t, "Listen", errChan)
|
|
require.Error(t, err, "Listen must fail when the QUIC port is taken")
|
|
assert.ErrorContains(t, err, string(quic.Proto)+" listener", "the QUIC listener must be the one that failed to bind")
|
|
assert.Empty(t, srv.ListenerProtocols(), "a failed Listen must not register listeners")
|
|
|
|
// The WS listener binds first, so a free TCP port proves the rollback closed it.
|
|
ln, err := net.Listen("tcp", addr)
|
|
require.NoError(t, err, "the WS socket must be released after the QUIC bind failure")
|
|
require.NoError(t, ln.Close())
|
|
}
|
|
|
|
func newTestServer(t *testing.T, addr string) *Server {
|
|
t.Helper()
|
|
srv, err := NewServer(Config{
|
|
ExposedAddress: "rel://" + addr,
|
|
AuthValidator: &allow.Auth{},
|
|
})
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
assert.NoError(t, srv.Shutdown(context.Background()))
|
|
})
|
|
return srv
|
|
}
|
|
|
|
// The server binds TCP and UDP on the same port, so a port is only picked when
|
|
// both are free. The probes are closed before Listen binds, which leaves a small
|
|
// window for another process to take the port; waitForListeners then reports the
|
|
// bind error instead of a timeout.
|
|
func freeAddress(t *testing.T) string {
|
|
t.Helper()
|
|
for attempt := 0; attempt < 10; attempt++ {
|
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
require.NoError(t, err)
|
|
addr := ln.Addr().String()
|
|
require.NoError(t, ln.Close())
|
|
|
|
conn, err := net.ListenPacket("udp", addr)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
require.NoError(t, conn.Close())
|
|
return addr
|
|
}
|
|
t.Fatal("no address with both tcp and udp ports free")
|
|
return ""
|
|
}
|
|
|
|
// Listen registers its listeners under the same lock that starts serving, so a
|
|
// non-empty ListenerProtocols means the sockets are bound. A Listen that returns
|
|
// before that has failed to bind, and its error is reported instead of a timeout.
|
|
func waitForListeners(t *testing.T, srv *Server, errChan <-chan error) {
|
|
t.Helper()
|
|
deadline := time.After(5 * time.Second)
|
|
for len(srv.ListenerProtocols()) == 0 {
|
|
select {
|
|
case err := <-errChan:
|
|
t.Fatalf("Listen returned before binding: %v", err)
|
|
case <-deadline:
|
|
t.Fatal("listeners were not bound")
|
|
case <-time.After(10 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|
|
|
|
func waitForReturn(t *testing.T, op string, errChan <-chan error) error {
|
|
t.Helper()
|
|
select {
|
|
case err := <-errChan:
|
|
return err
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatalf("%s did not return", op)
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// The QUIC listener releases its UDP socket from the read loop after Close returns,
|
|
// so both sockets are polled instead of checked once.
|
|
func requireAddressFree(t *testing.T, addr string) {
|
|
t.Helper()
|
|
require.Eventually(t, func() bool {
|
|
ln, err := net.Listen("tcp", addr)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
_ = ln.Close()
|
|
|
|
conn, err := net.ListenPacket("udp", addr)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
_ = conn.Close()
|
|
return true
|
|
}, 5*time.Second, 10*time.Millisecond, "address %s must be released", addr)
|
|
}
|
|
|
|
// A nil TLS config only yields a QUIC listener in the devcert build, so the tests
|
|
// that need both listeners pass a real one and bind them regardless of build tags.
|
|
func testTLSConfig(t *testing.T) *tls.Config {
|
|
t.Helper()
|
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
require.NoError(t, err)
|
|
|
|
template := &x509.Certificate{
|
|
SerialNumber: big.NewInt(1),
|
|
NotBefore: time.Now().Add(-time.Hour),
|
|
NotAfter: time.Now().Add(time.Hour),
|
|
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
|
}
|
|
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
|
require.NoError(t, err)
|
|
|
|
return &tls.Config{
|
|
Certificates: []tls.Certificate{{Certificate: [][]byte{certDER}, PrivateKey: key}},
|
|
}
|
|
}
|