smegmesh/pkg/conn/connection.go

72 lines
1.7 KiB
Go
Raw Normal View History

2023-10-24 01:12:38 +02:00
// conn manages gRPC connections between peers.
// Includes timers.
package conn
import (
"crypto/tls"
"errors"
logging "github.com/tim-beatham/wgmesh/pkg/log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// PeerConnection represents a client-side connection between two
// peers.
type PeerConnection interface {
Close() error
GetClient() (*grpc.ClientConn, error)
}
2023-11-05 19:03:58 +01:00
type PeerConnectionFactory = func(clientConfig *tls.Config, server string) (PeerConnection, error)
2023-10-24 01:12:38 +02:00
// WgCtrlConnection implements PeerConnection.
type WgCtrlConnection struct {
clientConfig *tls.Config
conn *grpc.ClientConn
endpoint string
}
// NewWgCtrlConnection creates a new instance of a WireGuard control connection
2023-11-05 19:03:58 +01:00
func NewWgCtrlConnection(clientConfig *tls.Config, server string) (PeerConnection, error) {
2023-10-24 01:12:38 +02:00
var conn WgCtrlConnection
conn.clientConfig = clientConfig
conn.endpoint = server
2023-11-05 19:03:58 +01:00
if err := conn.CreateGrpcConnection(); err != nil {
2023-10-24 01:12:38 +02:00
return nil, err
}
return &conn, nil
}
// ConnectWithToken: Connects to a new gRPC peer given the address of the other server.
2023-11-05 19:03:58 +01:00
func (c *WgCtrlConnection) CreateGrpcConnection() error {
2023-10-24 01:12:38 +02:00
conn, err := grpc.Dial(c.endpoint,
2023-11-03 16:24:18 +01:00
grpc.WithTransportCredentials(credentials.NewTLS(c.clientConfig)))
2023-10-24 01:12:38 +02:00
if err != nil {
logging.Log.WriteErrorf("Could not connect: %s\n", err.Error())
return err
}
c.conn = conn
return nil
}
// Close: Closes the client connections
func (c *WgCtrlConnection) Close() error {
return c.conn.Close()
}
// GetClient: Gets the client connection
func (c *WgCtrlConnection) GetClient() (*grpc.ClientConn, error) {
var err error = nil
if c.conn == nil {
2023-11-05 19:03:58 +01:00
err = errors.New("the client's config does not exist")
2023-10-24 01:12:38 +02:00
}
return c.conn, err
}