netbird/relay/server/server.go

86 lines
1.6 KiB
Go
Raw Normal View History

2024-05-17 17:43:28 +02:00
package server
import (
"context"
2024-07-01 11:50:18 +02:00
"crypto/tls"
2024-05-26 22:14:33 +02:00
"errors"
"sync"
"time"
2024-05-17 17:43:28 +02:00
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/relay/server/listener"
"github.com/netbirdio/netbird/relay/server/listener/udp"
"github.com/netbirdio/netbird/relay/server/listener/ws"
2024-06-26 15:26:19 +02:00
)
2024-07-02 11:57:17 +02:00
type ListenerConfig struct {
2024-07-01 11:50:18 +02:00
Address string
TLSConfig *tls.Config
}
2024-05-17 17:43:28 +02:00
type Server struct {
relay *Relay
uDPListener listener.Listener
wSListener listener.Listener
2024-05-17 17:43:28 +02:00
}
2024-07-02 11:57:17 +02:00
func NewServer(exposedAddress string, tlsSupport bool) *Server {
2024-05-17 17:43:28 +02:00
return &Server{
2024-07-02 11:57:17 +02:00
relay: NewRelay(exposedAddress, tlsSupport),
2024-05-17 17:43:28 +02:00
}
}
2024-07-02 11:57:17 +02:00
func (r *Server) Listen(cfg ListenerConfig) error {
2024-05-26 22:14:33 +02:00
wg := sync.WaitGroup{}
wg.Add(2)
2024-07-01 11:50:18 +02:00
r.wSListener = &ws.Listener{
Address: cfg.Address,
TLSConfig: cfg.TLSConfig,
}
2024-05-26 22:14:33 +02:00
var wslErr error
go func() {
defer wg.Done()
wslErr = r.wSListener.Listen(r.relay.Accept)
2024-05-26 22:14:33 +02:00
if wslErr != nil {
log.Errorf("failed to bind ws server: %s", wslErr)
}
}()
2024-07-01 11:50:18 +02:00
r.uDPListener = udp.NewListener(cfg.Address)
2024-05-26 22:14:33 +02:00
var udpLErr error
go func() {
defer wg.Done()
udpLErr = r.uDPListener.Listen(r.relay.Accept)
2024-05-26 22:14:33 +02:00
if udpLErr != nil {
log.Errorf("failed to bind ws server: %s", udpLErr)
}
}()
err := errors.Join(wslErr, udpLErr)
return err
2024-05-17 17:43:28 +02:00
}
func (r *Server) Close() error {
2024-05-26 22:14:33 +02:00
var wErr error
// stop service new connections
if r.wSListener != nil {
wErr = r.wSListener.Close()
2024-05-26 22:14:33 +02:00
}
var uErr error
if r.uDPListener != nil {
uErr = r.uDPListener.Close()
2024-05-17 17:43:28 +02:00
}
2024-06-05 19:49:30 +02:00
// close accepted connections gracefully
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
r.relay.Close(ctx)
2024-06-05 19:49:30 +02:00
2024-05-26 22:14:33 +02:00
err := errors.Join(wErr, uErr)
return err
2024-05-17 17:43:28 +02:00
}