netbird/relay/client/manager.go

76 lines
1.2 KiB
Go
Raw Normal View History

2024-05-23 13:24:02 +02:00
package client
import (
"context"
2024-05-26 22:14:33 +02:00
"net"
2024-05-23 13:24:02 +02:00
"sync"
2024-05-26 22:14:33 +02:00
"time"
log "github.com/sirupsen/logrus"
2024-05-23 13:24:02 +02:00
)
type Manager struct {
ctx context.Context
srvAddress string
peerID string
2024-05-26 22:14:33 +02:00
reconnectTime time.Duration
2024-05-23 13:24:02 +02:00
2024-05-26 22:14:33 +02:00
mu sync.Mutex
client *Client
2024-05-23 13:24:02 +02:00
}
func NewManager(ctx context.Context, serverAddress string, peerID string) *Manager {
return &Manager{
2024-05-26 22:14:33 +02:00
ctx: ctx,
srvAddress: serverAddress,
peerID: peerID,
reconnectTime: 5 * time.Second,
2024-05-23 13:24:02 +02:00
}
}
2024-05-26 22:14:33 +02:00
func (m *Manager) Serve() {
ok := m.mu.TryLock()
if !ok {
2024-05-23 13:24:02 +02:00
return
}
2024-05-26 22:14:33 +02:00
m.client = NewClient(m.ctx, m.srvAddress, m.peerID)
go func() {
defer m.mu.Unlock()
// todo this is not thread safe
for {
select {
case <-m.ctx.Done():
return
default:
m.connect()
}
select {
case <-m.ctx.Done():
return
case <-time.After(2 * time.Second): //timeout
}
}
}()
}
func (m *Manager) OpenConn(peerKey string) (net.Conn, error) {
// todo m.client nil check
return m.client.OpenConn(peerKey)
}
// connect is blocking
func (m *Manager) connect() {
err := m.client.Connect()
if err != nil {
if m.ctx.Err() != nil {
return
}
log.Errorf("connection error with '%s': %s", m.srvAddress, err)
}
2024-05-23 13:24:02 +02:00
}