forked from gravitational/teleport
/
agentpool.go
798 lines (688 loc) · 21.8 KB
/
agentpool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*
Copyright 2015-2019 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reversetunnel
import (
"context"
"crypto/tls"
"errors"
"io"
"net"
"sync"
"time"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"github.com/zmb3/teleport"
"github.com/zmb3/teleport/api/client/webclient"
"github.com/zmb3/teleport/api/defaults"
"github.com/zmb3/teleport/api/types"
"github.com/zmb3/teleport/api/utils/retryutils"
"github.com/zmb3/teleport/api/utils/sshutils"
"github.com/zmb3/teleport/lib"
"github.com/zmb3/teleport/lib/auth"
"github.com/zmb3/teleport/lib/reversetunnel/track"
alpncommon "github.com/zmb3/teleport/lib/srv/alpnproxy/common"
"github.com/zmb3/teleport/lib/utils"
"github.com/zmb3/teleport/lib/utils/proxy"
)
const (
// defaultAgentConnectionCount is the default connection count used when in
// proxy peering mode.
defaultAgentConnectionCount = 1
// maxBackoff sets the maximum backoff for creating new agents.
maxBackoff = time.Second * 8
// remotePingCacheTTL sets the time between calls to webclient.Find.
remotePingCacheTTL = time.Second * 5
)
// ServerHandler implements an interface which can handle a connection
// (perform a handshake then process). This is needed because importing
// lib/srv in lib/reversetunnel causes a circular import.
type ServerHandler interface {
// HandleConnection performs a handshake then process the connection.
HandleConnection(conn net.Conn)
}
type newAgentFunc func(context.Context, *track.Tracker, track.Lease) (Agent, error)
// AgentPool manages a pool of reverse tunnel agents.
type AgentPool struct {
AgentPoolConfig
active *agentStore
tracker *track.Tracker
// runtimeConfig contains dynamic configuration values.
runtimeConfig *agentPoolRuntimeConfig
// events receives agent state change events.
events chan Agent
// newAgentFunc is used during testing to mock new agents.
newAgentFunc newAgentFunc
// wg waits for the pool and all agents to complete.
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
// backoff limits the rate at which new agents are created.
backoff retryutils.Retry
log logrus.FieldLogger
}
// AgentPoolConfig holds configuration parameters for the agent pool
type AgentPoolConfig struct {
// Client is client to the auth server this agent connects to receive
// a list of pools
Client auth.ClientI
// AccessPoint is a lightweight access point
// that can optionally cache some values
AccessPoint auth.AccessCache
// HostSigner is a host signer this agent presents itself as
HostSigner ssh.Signer
// HostUUID is a unique ID of this host
HostUUID string
// LocalCluster is a cluster name this client is a member of.
LocalCluster string
// Clock is a clock used to get time, if not set,
// system clock is used
Clock clockwork.Clock
// KubeDialAddr is an address of a kubernetes proxy
KubeDialAddr utils.NetAddr
// Server is either an SSH or application server. It can handle a connection
// (perform handshake and handle request).
Server ServerHandler
// Component is the Teleport component this agent pool is running in. It can
// either be proxy (trusted clusters) or node (dial back).
Component string
// ReverseTunnelServer holds all reverse tunnel connections.
ReverseTunnelServer Server
// Resolver retrieves the reverse tunnel address
Resolver Resolver
// Cluster is a cluster name of the proxy.
Cluster string
// FIPS indicates if Teleport was started in FIPS mode.
FIPS bool
// ProxiedServiceUpdater updates a proxied service with the proxies it is connected to.
ConnectedProxyGetter *ConnectedProxyGetter
// IsRemoteCluster indicates the agent pool is connecting to a remote cluster.
// This means the tunnel strategy should be ignored and tls routing is determined
// by the remote cluster.
IsRemoteCluster bool
// DisableCreateHostUser disables host user creation on a node.
DisableCreateHostUser bool
// LocalAuthAddresses is a list of auth servers to use when dialing back to
// the local cluster.
LocalAuthAddresses []string
}
// CheckAndSetDefaults checks and sets defaults.
func (cfg *AgentPoolConfig) CheckAndSetDefaults() error {
if cfg.Client == nil {
return trace.BadParameter("missing 'Client' parameter")
}
if cfg.AccessPoint == nil {
return trace.BadParameter("missing 'AccessPoint' parameter")
}
if cfg.HostSigner == nil {
return trace.BadParameter("missing 'HostSigner' parameter")
}
if len(cfg.HostUUID) == 0 {
return trace.BadParameter("missing 'HostUUID' parameter")
}
if cfg.Cluster == "" {
return trace.BadParameter("missing 'Cluster' parameter")
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.ConnectedProxyGetter == nil {
cfg.ConnectedProxyGetter = NewConnectedProxyGetter()
}
return nil
}
// Agent represents a reverse tunnel agent.
type Agent interface {
// Start starts the agent in the background.
Start(context.Context) error
// Stop closes the agent and releases resources.
Stop() error
// GetState returns the current state of the agent.
GetState() AgentState
// GetProxyID returns the proxy id of the proxy the agent is connected to.
GetProxyID() (string, bool)
}
// NewAgentPool returns new instance of the agent pool.
func NewAgentPool(ctx context.Context, config AgentPoolConfig) (*AgentPool, error) {
if err := config.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
retry, err := retryutils.NewLinear(retryutils.LinearConfig{
Step: time.Second,
Max: maxBackoff,
Jitter: retryutils.NewJitter(),
AutoReset: 4,
})
if err != nil {
return nil, trace.Wrap(err)
}
pool := &AgentPool{
AgentPoolConfig: config,
active: newAgentStore(),
events: make(chan Agent),
wg: sync.WaitGroup{},
backoff: retry,
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentReverseTunnelAgent,
trace.ComponentFields: logrus.Fields{
"cluster": config.Cluster,
},
}),
runtimeConfig: newAgentPoolRuntimeConfig(),
}
pool.runtimeConfig.isRemoteCluster = pool.IsRemoteCluster
pool.newAgentFunc = pool.newAgent
pool.ctx, pool.cancel = context.WithCancel(ctx)
pool.tracker, err = track.New(pool.ctx, track.Config{ClusterName: pool.Cluster})
if err != nil {
return nil, trace.Wrap(err)
}
pool.tracker.Start()
return pool, nil
}
// GetConnectedProxyGetter returns the ConnectedProxyGetter for this agent pool.
func (p *AgentPool) GetConnectedProxyGetter() *ConnectedProxyGetter {
return p.ConnectedProxyGetter
}
func (p *AgentPool) updateConnectedProxies() {
if p.IsRemoteCluster {
trustedClustersStats.WithLabelValues(p.Cluster).Set(float64(p.active.len()))
}
if !p.runtimeConfig.reportConnectedProxies() {
p.ConnectedProxyGetter.setProxyIDs(nil)
return
}
proxies := p.active.proxyIDs()
p.log.Debugf("Updating connected proxies: %v", proxies)
p.AgentPoolConfig.ConnectedProxyGetter.setProxyIDs(proxies)
}
// Count is the number connected agents.
func (p *AgentPool) Count() int {
return p.active.len()
}
// Start starts the agent pool in the background.
func (p *AgentPool) Start() error {
p.log.Debugf("Starting agent pool %s.%s...", p.HostUUID, p.Cluster)
p.tracker.Start()
p.wg.Add(1)
go func() {
err := p.run()
p.log.WithError(err).Warn("Agent pool exited.")
p.cancel()
p.wg.Done()
}()
return nil
}
// run connects agents until the agent pool context is done.
func (p *AgentPool) run() error {
for {
if p.ctx.Err() != nil {
return trace.Wrap(p.ctx.Err())
}
agent, err := p.connectAgent(p.ctx, p.tracker.Acquire(), p.events)
if err != nil {
p.log.WithError(err).Debugf("Failed to connect agent.")
} else {
p.wg.Add(1)
p.active.add(agent)
p.updateConnectedProxies()
}
err = p.waitForBackoff(p.ctx, p.events)
if err != nil {
p.log.WithError(err).Debugf("Failed to wait for backoff.")
}
}
}
// connectAgent connects a new agent and processes any agent events blocking until a
// new agent is connected or an error occurs.
func (p *AgentPool) connectAgent(ctx context.Context, leases <-chan track.Lease, events <-chan Agent) (Agent, error) {
lease, err := p.waitForLease(ctx, leases, events)
if err != nil {
return nil, trace.Wrap(err)
}
// Ensure the lease is released on error.
defer func() {
if err != nil {
lease.Release()
}
}()
err = p.processEvents(ctx, events)
if err != nil {
return nil, trace.Wrap(err)
}
agent, err := p.newAgentFunc(ctx, p.tracker, lease)
if err != nil {
return nil, trace.Wrap(err)
}
err = agent.Start(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
return agent, nil
}
func (p *AgentPool) updateRuntimeConfig(ctx context.Context) error {
netConfig, err := p.AccessPoint.GetClusterNetworkingConfig(ctx)
if err != nil {
return trace.Wrap(err)
}
p.runtimeConfig.update(netConfig)
p.log.Debugf("Runtime config: tunnel_strategy: %v connection_count: %v", p.runtimeConfig.tunnelStrategyType, p.runtimeConfig.connectionCount)
return nil
}
// processEvents handles all events in the queue. Unblocking when a new agent
// is required.
func (p *AgentPool) processEvents(ctx context.Context, events <-chan Agent) error {
// Processes any queued events without blocking.
for {
select {
case <-ctx.Done():
return trace.Wrap(ctx.Err())
case agent := <-events:
p.handleEvent(ctx, agent)
continue
default:
}
break
}
err := p.updateRuntimeConfig(ctx)
if err != nil {
return trace.Wrap(err)
}
p.disconnectAgents()
if p.isAgentRequired() {
return nil
}
// Continue to process new events until an agent is required.
for {
p.log.Debugf("processing events...")
select {
case <-ctx.Done():
return trace.Wrap(ctx.Err())
case agent := <-events:
p.handleEvent(ctx, agent)
err := p.updateRuntimeConfig(ctx)
if err != nil {
return trace.Wrap(err)
}
p.disconnectAgents()
if p.isAgentRequired() {
return nil
}
}
}
}
// isAgentRequired returns true if a new agent is required.
func (p *AgentPool) isAgentRequired() bool {
if !p.runtimeConfig.restrictConnectionCount() {
return true
}
return p.active.len() < p.runtimeConfig.connectionCount
}
// disconnectAgents handles disconnecting agents that are no longer required.
func (p *AgentPool) disconnectAgents() {
if !p.runtimeConfig.restrictConnectionCount() {
return
}
for {
agent, ok := p.active.poplen(p.runtimeConfig.connectionCount)
if !ok {
p.updateConnectedProxies()
return
}
p.log.Debugf("Disconnecting agent %s.", agent)
go func() {
agent.Stop()
p.wg.Done()
}()
}
}
// waitForLease processes events while waiting to acquire a lease.
func (p *AgentPool) waitForLease(ctx context.Context, leases <-chan track.Lease, events <-chan Agent) (track.Lease, error) {
for {
select {
case <-ctx.Done():
return track.Lease{}, trace.Wrap(ctx.Err())
case lease := <-leases:
return lease, nil
case agent := <-events:
p.handleEvent(ctx, agent)
}
}
}
// waitForBackoff processes events while waiting for the backoff.
func (p *AgentPool) waitForBackoff(ctx context.Context, events <-chan Agent) error {
backoffC := p.backoff.After()
for {
select {
case <-ctx.Done():
return trace.Wrap(ctx.Err())
case <-backoffC:
p.backoff.Inc()
return nil
case agent := <-events:
p.handleEvent(ctx, agent)
}
}
}
// handleEvent processes a single event.
func (p *AgentPool) handleEvent(ctx context.Context, agent Agent) {
state := agent.GetState()
switch state {
case AgentConnecting:
return
case AgentConnected:
case AgentClosed:
if ok := p.active.remove(agent); ok {
p.wg.Done()
}
}
p.updateConnectedProxies()
p.log.Debugf("Active agent count: %d", p.active.len())
}
// stateCallback adds events to the queue for each agent state change.
func (p *AgentPool) getStateCallback(agent Agent) AgentStateCallback {
return func(_ AgentState) {
select {
case <-p.ctx.Done():
// Handle events directly when the pool is closing.
p.handleEvent(p.ctx, agent)
case p.events <- agent:
}
}
}
// newAgent creates a new agent instance.
func (p *AgentPool) newAgent(ctx context.Context, tracker *track.Tracker, lease track.Lease) (Agent, error) {
addr, _, err := p.Resolver(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
err = p.runtimeConfig.updateRemote(ctx, addr)
if err != nil {
p.log.WithError(err).Debugf("Failed to update remote config.")
}
options := []proxy.DialerOptionFunc{proxy.WithInsecureSkipTLSVerify(lib.IsInsecureDevMode())}
if p.runtimeConfig.useALPNRouting() {
tlsConfig := &tls.Config{
NextProtos: []string{string(alpncommon.ProtocolReverseTunnel)},
}
if p.runtimeConfig.useReverseTunnelV2() {
tlsConfig.NextProtos = []string{
string(alpncommon.ProtocolReverseTunnelV2),
string(alpncommon.ProtocolReverseTunnel),
}
}
options = append(options, proxy.WithALPNDialer(tlsConfig))
}
dialer := &agentDialer{
client: p.Client,
fips: p.FIPS,
authMethods: []ssh.AuthMethod{ssh.PublicKeys(p.HostSigner)},
options: options,
username: p.HostUUID,
log: p.log,
}
agent, err := newAgent(agentConfig{
addr: *addr,
keepAlive: p.runtimeConfig.keepAliveInterval,
sshDialer: dialer,
transporter: p,
versionGetter: p,
tracker: tracker,
lease: lease,
clock: p.Clock,
log: p.log,
localAuthAddresses: p.LocalAuthAddresses,
})
if err != nil {
return nil, trace.Wrap(err)
}
agent.stateCallback = p.getStateCallback(agent)
return agent, nil
}
// Wait blocks until the pool context is stopped.
func (p *AgentPool) Wait() {
if p == nil {
return
}
<-p.ctx.Done()
p.wg.Wait()
}
// Stop stops the pool and waits for all resources to be released.
func (p *AgentPool) Stop() {
if p == nil {
return
}
p.cancel()
p.wg.Wait()
}
// getVersion gets the connected auth server version.
func (p *AgentPool) getVersion(ctx context.Context) (string, error) {
pong, err := p.Client.Ping(ctx)
if err != nil {
return "", trace.Wrap(err)
}
return pong.ServerVersion, nil
}
// transport creates a new transport instance.
func (p *AgentPool) transport(ctx context.Context, channel ssh.Channel, requests <-chan *ssh.Request, conn sshutils.Conn) *transport {
return &transport{
closeContext: ctx,
component: p.Component,
localClusterName: p.LocalCluster,
kubeDialAddr: p.KubeDialAddr,
authClient: p.Client,
reverseTunnelServer: p.ReverseTunnelServer,
server: p.Server,
emitter: p.Client,
sconn: conn,
channel: channel,
requestCh: requests,
log: p.log,
authServers: p.LocalAuthAddresses,
}
}
// agentPoolRuntimeConfig contains configurations dynamically set and updated
// during runtime.
type agentPoolRuntimeConfig struct {
proxyListenerMode types.ProxyListenerMode
// tunnelStrategyType is the tunnel strategy configured for the cluster.
tunnelStrategyType types.TunnelStrategyType
// connectionCount determines how many proxy servers the agent pool will
// connect to. This settings is ignored for the AgentMesh tunnel strategy.
connectionCount int
// keepAliveInterval is the interval agents will send heartbeats at.
keepAliveInterval time.Duration
// isRemoteCluster forces the agent pool to connect to all proxies
// regardless of the configured tunnel strategy.
isRemoteCluster bool
// remoteTLSRoutingEnabled caches a remote clusters tls routing setting. This helps prevent
// proxy endpoint stagnation where an even numbers of proxies are hidden behind a round robin
// load balancer. For instance in a situation where there are two proxies [A, B] due to the
// the agent pools sequential webclient.Find and ssh dial, the Find call will always reach
// Proxy A and the ssh dial call will always be forwarded to Proxy B.
remoteTLSRoutingEnabled bool
// lastRemotePing is the time of the last ping attempt.
lastRemotePing *time.Time
mu sync.RWMutex
updateRemoteMu sync.Mutex
clock clockwork.Clock
}
func newAgentPoolRuntimeConfig() *agentPoolRuntimeConfig {
return &agentPoolRuntimeConfig{
tunnelStrategyType: types.AgentMesh,
connectionCount: defaultAgentConnectionCount,
proxyListenerMode: types.ProxyListenerMode_Separate,
keepAliveInterval: defaults.KeepAliveInterval(),
clock: clockwork.NewRealClock(),
}
}
// reportConnectedProxies returns true if the connected proxies should be reported.
func (c *agentPoolRuntimeConfig) reportConnectedProxies() bool {
c.mu.RLock()
defer c.mu.RUnlock()
if c.isRemoteCluster {
return false
}
return c.tunnelStrategyType == types.ProxyPeering
}
// reportConnectedProxies returns true if the the number of agents should be restricted.
func (c *agentPoolRuntimeConfig) restrictConnectionCount() bool {
c.mu.RLock()
defer c.mu.RUnlock()
if c.isRemoteCluster {
return false
}
return c.tunnelStrategyType == types.ProxyPeering
}
// useReverseTunnelV2 returns true if reverse tunnel should be used.
func (c *agentPoolRuntimeConfig) useReverseTunnelV2() bool {
c.mu.RLock()
defer c.mu.RUnlock()
if c.isRemoteCluster {
return false
}
return c.tunnelStrategyType == types.ProxyPeering
}
// useALPNRouting returns true agents should connect using alpn routing.
func (c *agentPoolRuntimeConfig) useALPNRouting() bool {
c.mu.RLock()
defer c.mu.RUnlock()
if c.isRemoteCluster {
return c.remoteTLSRoutingEnabled
}
return c.proxyListenerMode == types.ProxyListenerMode_Multiplex
}
func (c *agentPoolRuntimeConfig) updateRemote(ctx context.Context, addr *utils.NetAddr) error {
c.updateRemoteMu.Lock()
defer c.updateRemoteMu.Unlock()
c.mu.RLock()
if !c.isRemoteCluster {
c.mu.RUnlock()
return nil
}
if c.lastRemotePing != nil && c.clock.Since(*c.lastRemotePing) < remotePingCacheTTL {
c.mu.RUnlock()
return nil
}
c.mu.RUnlock()
ctx, cancel := context.WithTimeout(ctx, defaults.DefaultDialTimeout)
defer cancel()
tlsRoutingEnabled := false
ping, err := webclient.Find(&webclient.Config{
Context: ctx,
ProxyAddr: addr.Addr,
Insecure: lib.IsInsecureDevMode(),
})
if err != nil {
// If TLS Routing is disabled the address is the proxy reverse tunnel
// address the ping call will always fail with tls.RecordHeaderError.
if ok := errors.As(err, &tls.RecordHeaderError{}); !ok {
return trace.Wrap(err)
}
}
if ping != nil {
// Only use the ping results if they weren't from a minimal handler.
// The minimal API handler only exists when the proxy and reverse tunnel are
// listening on separate ports, so it will never do TLS routing.
isMinimalHandler := addr.Addr == ping.Proxy.SSH.TunnelListenAddr &&
ping.Proxy.SSH.TunnelListenAddr != ping.Proxy.SSH.WebListenAddr
if !isMinimalHandler {
tlsRoutingEnabled = ping.Proxy.TLSRoutingEnabled
}
}
c.mu.Lock()
defer c.mu.Unlock()
now := c.clock.Now()
c.lastRemotePing = &now
c.remoteTLSRoutingEnabled = tlsRoutingEnabled
return nil
}
func (c *agentPoolRuntimeConfig) update(netConfig types.ClusterNetworkingConfig) {
c.mu.Lock()
defer c.mu.Unlock()
c.keepAliveInterval = netConfig.GetKeepAliveInterval()
c.proxyListenerMode = netConfig.GetProxyListenerMode()
// Fallback to agent mesh strategy if there is an error.
strategyType, err := netConfig.GetTunnelStrategyType()
if err != nil {
c.tunnelStrategyType = types.AgentMesh
return
}
c.tunnelStrategyType = strategyType
if c.tunnelStrategyType == types.ProxyPeering {
strategy := netConfig.GetProxyPeeringTunnelStrategy()
c.connectionCount = int(strategy.AgentConnectionCount)
}
if c.connectionCount <= 0 {
c.connectionCount = defaultAgentConnectionCount
}
}
// Make sure ServerHandlerToListener implements both interfaces.
var _ = net.Listener(ServerHandlerToListener{})
var _ = ServerHandler(ServerHandlerToListener{})
// ServerHandlerToListener is an adapter from ServerHandler to net.Listener. It
// can be used as a Server field in AgentPoolConfig, while also being passed to
// http.Server.Serve (or any other func Serve(net.Listener)).
type ServerHandlerToListener struct {
connCh chan net.Conn
closeOnce *sync.Once
tunnelAddr string
}
// NewServerHandlerToListener creates a new ServerHandlerToListener adapter.
func NewServerHandlerToListener(tunnelAddr string) ServerHandlerToListener {
return ServerHandlerToListener{
connCh: make(chan net.Conn),
closeOnce: new(sync.Once),
tunnelAddr: tunnelAddr,
}
}
func (l ServerHandlerToListener) HandleConnection(c net.Conn) {
// HandleConnection must block as long as c is used.
// Wrap c to only return after c.Close() has been called.
cc := newConnCloser(c)
l.connCh <- cc
cc.wait()
}
func (l ServerHandlerToListener) Accept() (net.Conn, error) {
c, ok := <-l.connCh
if !ok {
return nil, io.EOF
}
return c, nil
}
func (l ServerHandlerToListener) Close() error {
l.closeOnce.Do(func() { close(l.connCh) })
return nil
}
func (l ServerHandlerToListener) Addr() net.Addr {
return reverseTunnelAddr(l.tunnelAddr)
}
type connCloser struct {
net.Conn
closeOnce *sync.Once
closed chan struct{}
}
func newConnCloser(c net.Conn) connCloser {
return connCloser{Conn: c, closeOnce: new(sync.Once), closed: make(chan struct{})}
}
func (c connCloser) Close() error {
c.closeOnce.Do(func() { close(c.closed) })
return c.Conn.Close()
}
func (c connCloser) wait() { <-c.closed }
// reverseTunnelAddr is a net.Addr implementation for a listener based on a
// reverse tunnel.
type reverseTunnelAddr string
func (reverseTunnelAddr) Network() string { return "ssh-reversetunnel" }
func (a reverseTunnelAddr) String() string { return string(a) }