netbird/relay/server/server.go

76 lines
1.4 KiB
Go
Raw Normal View History

2024-05-17 17:43:28 +02:00
package server
import (
"context"
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-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
}
func NewServer() *Server {
return &Server{
relay: NewRelay(),
2024-05-17 17:43:28 +02:00
}
}
func (r *Server) Listen(address string) error {
2024-05-26 22:14:33 +02:00
wg := sync.WaitGroup{}
wg.Add(2)
r.wSListener = ws.NewListener(address)
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)
}
}()
r.uDPListener = udp.NewListener(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
}