netbird/relay/server/server.go

66 lines
1.3 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"
"time"
2024-05-17 17:43:28 +02:00
log "github.com/sirupsen/logrus"
2024-07-24 16:26:26 +02:00
"go.opentelemetry.io/otel/metric"
2024-05-17 17:43:28 +02:00
2024-07-08 17:01:11 +02:00
"github.com/netbirdio/netbird/relay/auth"
2024-05-17 17:43:28 +02:00
"github.com/netbirdio/netbird/relay/server/listener"
"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 {
2024-07-25 11:03:54 +02:00
relay *Relay
wSListener listener.Listener
2024-05-17 17:43:28 +02:00
}
2024-07-24 16:26:26 +02:00
func NewServer(meter metric.Meter, exposedAddress string, tlsSupport bool, authValidator auth.Validator) (*Server, error) {
relay, err := NewRelay(meter, exposedAddress, tlsSupport, authValidator)
if err != nil {
return nil, err
2024-05-17 17:43:28 +02:00
}
2024-07-24 16:26:26 +02:00
return &Server{
relay: relay,
}, nil
2024-05-17 17:43:28 +02:00
}
2024-07-02 11:57:17 +02:00
func (r *Server) Listen(cfg ListenerConfig) error {
2024-07-01 11:50:18 +02:00
r.wSListener = &ws.Listener{
Address: cfg.Address,
TLSConfig: cfg.TLSConfig,
}
2024-07-26 14:45:34 +02:00
wslErr := r.wSListener.Listen(r.relay.Accept)
if wslErr != nil {
log.Errorf("failed to bind ws server: %s", wslErr)
}
2024-05-26 22:14:33 +02:00
2024-07-25 11:03:54 +02:00
return wslErr
2024-05-17 17:43:28 +02:00
}
2024-07-25 11:03:54 +02:00
func (r *Server) Close() (err error) {
// stop service new connections
if r.wSListener != nil {
2024-07-25 11:03:54 +02:00
err = r.wSListener.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-07-25 11:03:54 +02:00
return
2024-05-17 17:43:28 +02:00
}
func (r *Server) InstanceURL() string {
2024-07-24 16:34:47 +02:00
return r.relay.instanceURL
}