2019-06-17 21:18:47 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/pkg/errors"
|
2019-11-21 17:03:13 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2019-06-17 21:18:47 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2019-11-21 17:03:13 +00:00
|
|
|
|
|
|
|
"github.com/cloudflare/cloudflared/cmd/cloudflared/buildinfo"
|
|
|
|
"github.com/cloudflare/cloudflared/h2mux"
|
|
|
|
"github.com/cloudflare/cloudflared/streamhandler"
|
|
|
|
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
2019-06-17 21:18:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2019-11-05 20:37:40 +00:00
|
|
|
quickStartLink = "https://developers.cloudflare.com/argo-tunnel/quickstart/"
|
|
|
|
faqLink = "https://developers.cloudflare.com/argo-tunnel/faq/"
|
|
|
|
defaultRetryAfter = time.Second * 5
|
|
|
|
packageNamespace = "connection"
|
|
|
|
edgeManagerSubsystem = "edgemanager"
|
2019-06-17 21:18:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// EdgeManager manages connections with the edge
|
|
|
|
type EdgeManager struct {
|
|
|
|
// streamHandler handles stream opened by the edge
|
2019-10-23 21:02:33 +00:00
|
|
|
streamHandler *streamhandler.StreamHandler
|
2019-06-17 21:18:47 +00:00
|
|
|
// TLSConfig is the TLS configuration to connect with edge
|
|
|
|
tlsConfig *tls.Config
|
|
|
|
// cloudflaredConfig is the cloudflared configuration that is determined when the process first starts
|
|
|
|
cloudflaredConfig *CloudflaredConfig
|
|
|
|
// serviceDiscoverer returns the next edge addr to connect to
|
|
|
|
serviceDiscoverer EdgeServiceDiscoverer
|
|
|
|
// state is attributes of ConnectionManager that can change during runtime.
|
|
|
|
state *edgeManagerState
|
|
|
|
|
|
|
|
logger *logrus.Entry
|
2019-11-05 20:37:40 +00:00
|
|
|
|
|
|
|
metrics *metrics
|
|
|
|
}
|
|
|
|
|
|
|
|
type metrics struct {
|
|
|
|
// activeStreams is a gauge shared by all muxers of this process to expose the total number of active streams
|
|
|
|
activeStreams prometheus.Gauge
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
2019-11-05 20:37:40 +00:00
|
|
|
func newMetrics(namespace, subsystem string) *metrics {
|
|
|
|
return &metrics{
|
|
|
|
activeStreams: h2mux.NewActiveStreamsMetrics(namespace, subsystem),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// EdgeManagerConfigurable is the configurable attributes of a EdgeConnectionManager
|
2019-06-17 21:18:47 +00:00
|
|
|
type EdgeManagerConfigurable struct {
|
|
|
|
TunnelHostnames []h2mux.TunnelHostname
|
2019-11-21 17:03:13 +00:00
|
|
|
*tunnelpogs.EdgeConnectionConfig
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type CloudflaredConfig struct {
|
|
|
|
CloudflaredID uuid.UUID
|
2019-11-21 17:03:13 +00:00
|
|
|
Tags []tunnelpogs.Tag
|
2019-06-17 21:18:47 +00:00
|
|
|
BuildInfo *buildinfo.BuildInfo
|
2019-09-18 19:57:20 +00:00
|
|
|
IntentLabel string
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewEdgeManager(
|
2019-10-23 21:02:33 +00:00
|
|
|
streamHandler *streamhandler.StreamHandler,
|
2019-06-17 21:18:47 +00:00
|
|
|
edgeConnMgrConfigurable *EdgeManagerConfigurable,
|
|
|
|
userCredential []byte,
|
|
|
|
tlsConfig *tls.Config,
|
|
|
|
serviceDiscoverer EdgeServiceDiscoverer,
|
|
|
|
cloudflaredConfig *CloudflaredConfig,
|
|
|
|
logger *logrus.Logger,
|
|
|
|
) *EdgeManager {
|
|
|
|
return &EdgeManager{
|
|
|
|
streamHandler: streamHandler,
|
|
|
|
tlsConfig: tlsConfig,
|
|
|
|
cloudflaredConfig: cloudflaredConfig,
|
|
|
|
serviceDiscoverer: serviceDiscoverer,
|
|
|
|
state: newEdgeConnectionManagerState(edgeConnMgrConfigurable, userCredential),
|
|
|
|
logger: logger.WithField("subsystem", "connectionManager"),
|
2019-11-05 20:37:40 +00:00
|
|
|
metrics: newMetrics(packageNamespace, edgeManagerSubsystem),
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) Run(ctx context.Context) error {
|
|
|
|
defer em.shutdown()
|
|
|
|
|
|
|
|
resolveEdgeIPTicker := time.Tick(resolveEdgeAddrTTL)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return errors.Wrap(ctx.Err(), "EdgeConnectionManager terminated")
|
|
|
|
case <-resolveEdgeIPTicker:
|
|
|
|
if err := em.serviceDiscoverer.Refresh(); err != nil {
|
|
|
|
em.logger.WithError(err).Warn("Cannot refresh Cloudflare edge addresses")
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
}
|
|
|
|
// Create/delete connection one at a time, so we don't need to adjust for connections that are being created/deleted
|
|
|
|
// in shouldCreateConnection or shouldReduceConnection calculation
|
|
|
|
if em.state.shouldCreateConnection(em.serviceDiscoverer.AvailableAddrs()) {
|
2019-09-17 21:58:49 +00:00
|
|
|
if connErr := em.newConnection(ctx); connErr != nil {
|
|
|
|
if !connErr.ShouldRetry {
|
|
|
|
em.logger.WithError(connErr).Error(em.noRetryMessage())
|
|
|
|
return connErr
|
|
|
|
}
|
|
|
|
em.logger.WithError(connErr).Error("cannot create new connection")
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
} else if em.state.shouldReduceConnection() {
|
|
|
|
if err := em.closeConnection(ctx); err != nil {
|
|
|
|
em.logger.WithError(err).Error("cannot close connection")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) UpdateConfigurable(newConfigurable *EdgeManagerConfigurable) {
|
|
|
|
em.logger.Infof("New edge connection manager configuration %+v", newConfigurable)
|
|
|
|
em.state.updateConfigurable(newConfigurable)
|
|
|
|
}
|
|
|
|
|
2019-11-21 17:03:13 +00:00
|
|
|
func (em *EdgeManager) newConnection(ctx context.Context) *tunnelpogs.ConnectError {
|
2019-12-13 23:05:21 +00:00
|
|
|
edgeTCPAddr, err := em.serviceDiscoverer.Addr()
|
|
|
|
if err != nil {
|
|
|
|
return retryConnection(fmt.Sprintf("edge address discovery error: %v", err))
|
|
|
|
}
|
2019-11-21 18:10:44 +00:00
|
|
|
configurable := em.state.getConfigurable()
|
|
|
|
edgeConn, err := DialEdge(ctx, configurable.Timeout, em.tlsConfig, edgeTCPAddr)
|
2019-06-17 21:18:47 +00:00
|
|
|
if err != nil {
|
2019-09-17 21:58:49 +00:00
|
|
|
return retryConnection(fmt.Sprintf("dial edge error: %v", err))
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
// Establish a muxed connection with the edge
|
|
|
|
// Client mux handshake with agent server
|
|
|
|
muxer, err := h2mux.Handshake(edgeConn, edgeConn, h2mux.MuxerConfig{
|
|
|
|
Timeout: configurable.Timeout,
|
|
|
|
Handler: em.streamHandler,
|
|
|
|
IsClient: true,
|
|
|
|
HeartbeatInterval: configurable.HeartbeatInterval,
|
|
|
|
MaxHeartbeats: configurable.MaxFailedHeartbeats,
|
|
|
|
Logger: em.logger.WithField("subsystem", "muxer"),
|
2019-11-05 20:37:40 +00:00
|
|
|
}, em.metrics.activeStreams)
|
2019-06-17 21:18:47 +00:00
|
|
|
if err != nil {
|
2019-09-17 21:58:49 +00:00
|
|
|
retryConnection(fmt.Sprintf("couldn't perform handshake with edge: %v", err))
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
2019-12-13 23:05:21 +00:00
|
|
|
h2muxConn, err := newConnection(muxer, edgeTCPAddr)
|
2019-06-17 21:18:47 +00:00
|
|
|
if err != nil {
|
2019-09-17 21:58:49 +00:00
|
|
|
return retryConnection(fmt.Sprintf("couldn't create h2mux connection: %v", err))
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
go em.serveConn(ctx, h2muxConn)
|
|
|
|
|
2019-11-21 17:03:13 +00:00
|
|
|
connResult, err := h2muxConn.Connect(ctx, &tunnelpogs.ConnectParameters{
|
2019-06-17 21:18:47 +00:00
|
|
|
CloudflaredID: em.cloudflaredConfig.CloudflaredID,
|
|
|
|
CloudflaredVersion: em.cloudflaredConfig.BuildInfo.CloudflaredVersion,
|
2019-07-30 18:55:34 +00:00
|
|
|
NumPreviousAttempts: 0,
|
|
|
|
OriginCert: em.state.getUserCredential(),
|
2019-09-18 19:57:20 +00:00
|
|
|
IntentLabel: em.cloudflaredConfig.IntentLabel,
|
2019-07-30 18:55:34 +00:00
|
|
|
Tags: em.cloudflaredConfig.Tags,
|
2019-06-17 21:18:47 +00:00
|
|
|
}, em.logger)
|
|
|
|
if err != nil {
|
|
|
|
h2muxConn.Shutdown()
|
2019-09-17 21:58:49 +00:00
|
|
|
return retryConnection(fmt.Sprintf("couldn't connect to edge: %v", err))
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
2019-09-17 21:58:49 +00:00
|
|
|
if connErr := connResult.ConnectError(); connErr != nil {
|
|
|
|
return connErr
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
em.state.newConnection(h2muxConn)
|
2019-09-17 21:58:49 +00:00
|
|
|
em.logger.Infof("connected to %s", connResult.ConnectedTo())
|
2019-10-23 21:02:33 +00:00
|
|
|
|
2019-11-05 20:37:40 +00:00
|
|
|
if connResult.ClientConfig() != nil {
|
|
|
|
em.streamHandler.UseConfiguration(ctx, connResult.ClientConfig())
|
|
|
|
}
|
2019-06-17 21:18:47 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) closeConnection(ctx context.Context) error {
|
|
|
|
conn := em.state.getFirstConnection()
|
|
|
|
if conn == nil {
|
|
|
|
return fmt.Errorf("no connection to close")
|
|
|
|
}
|
|
|
|
conn.Shutdown()
|
2019-12-13 23:05:21 +00:00
|
|
|
// teardown will be handled by EdgeManager.serveConn in another goroutine
|
2019-06-17 21:18:47 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) serveConn(ctx context.Context, conn *Connection) {
|
|
|
|
err := conn.Serve(ctx)
|
|
|
|
em.logger.WithError(err).Warn("Connection closed")
|
|
|
|
em.state.closeConnection(conn)
|
2019-12-13 23:05:21 +00:00
|
|
|
em.serviceDiscoverer.ReplaceAddr(conn.addr)
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) noRetryMessage() string {
|
|
|
|
messageTemplate := "cloudflared could not register an Argo Tunnel on your account. Please confirm the following before trying again:" +
|
|
|
|
"1. You have Argo Smart Routing enabled in your account, See Enable Argo section of %s." +
|
|
|
|
"2. Your credential at %s is still valid. See %s."
|
|
|
|
return fmt.Sprintf(messageTemplate, quickStartLink, em.state.getConfigurable().UserCredentialPath, faqLink)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (em *EdgeManager) shutdown() {
|
|
|
|
em.state.shutdown()
|
|
|
|
}
|
|
|
|
|
|
|
|
type edgeManagerState struct {
|
|
|
|
sync.RWMutex
|
|
|
|
configurable *EdgeManagerConfigurable
|
|
|
|
userCredential []byte
|
|
|
|
conns map[uuid.UUID]*Connection
|
|
|
|
}
|
|
|
|
|
|
|
|
func newEdgeConnectionManagerState(configurable *EdgeManagerConfigurable, userCredential []byte) *edgeManagerState {
|
|
|
|
return &edgeManagerState{
|
|
|
|
configurable: configurable,
|
|
|
|
userCredential: userCredential,
|
|
|
|
conns: make(map[uuid.UUID]*Connection),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-13 23:05:21 +00:00
|
|
|
func (ems *edgeManagerState) shouldCreateConnection(availableEdgeAddrs int) bool {
|
2019-06-17 21:18:47 +00:00
|
|
|
ems.RLock()
|
|
|
|
defer ems.RUnlock()
|
2019-12-13 23:05:21 +00:00
|
|
|
expectedHAConns := int(ems.configurable.NumHAConnections)
|
2019-06-17 21:18:47 +00:00
|
|
|
if availableEdgeAddrs < expectedHAConns {
|
|
|
|
expectedHAConns = availableEdgeAddrs
|
|
|
|
}
|
2019-12-13 23:05:21 +00:00
|
|
|
return len(ems.conns) < expectedHAConns
|
2019-06-17 21:18:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) shouldReduceConnection() bool {
|
|
|
|
ems.RLock()
|
|
|
|
defer ems.RUnlock()
|
|
|
|
return uint8(len(ems.conns)) > ems.configurable.NumHAConnections
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) newConnection(conn *Connection) {
|
|
|
|
ems.Lock()
|
|
|
|
defer ems.Unlock()
|
|
|
|
ems.conns[conn.id] = conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) closeConnection(conn *Connection) {
|
|
|
|
ems.Lock()
|
|
|
|
defer ems.Unlock()
|
|
|
|
delete(ems.conns, conn.id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) getFirstConnection() *Connection {
|
|
|
|
ems.RLock()
|
|
|
|
defer ems.RUnlock()
|
|
|
|
|
|
|
|
for _, conn := range ems.conns {
|
|
|
|
return conn
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) shutdown() {
|
|
|
|
ems.Lock()
|
|
|
|
defer ems.Unlock()
|
|
|
|
for _, conn := range ems.conns {
|
|
|
|
conn.Shutdown()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) getConfigurable() *EdgeManagerConfigurable {
|
|
|
|
ems.Lock()
|
|
|
|
defer ems.Unlock()
|
|
|
|
return ems.configurable
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) updateConfigurable(newConfigurable *EdgeManagerConfigurable) {
|
|
|
|
ems.Lock()
|
|
|
|
defer ems.Unlock()
|
|
|
|
ems.configurable = newConfigurable
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ems *edgeManagerState) getUserCredential() []byte {
|
|
|
|
ems.RLock()
|
|
|
|
defer ems.RUnlock()
|
|
|
|
return ems.userCredential
|
|
|
|
}
|
2019-09-17 21:58:49 +00:00
|
|
|
|
2019-11-21 17:03:13 +00:00
|
|
|
func retryConnection(cause string) *tunnelpogs.ConnectError {
|
|
|
|
return &tunnelpogs.ConnectError{
|
2019-09-17 21:58:49 +00:00
|
|
|
Cause: cause,
|
|
|
|
RetryAfter: defaultRetryAfter,
|
|
|
|
ShouldRetry: true,
|
|
|
|
}
|
|
|
|
}
|