/
forwarder.go
78 lines (61 loc) · 1.54 KB
/
forwarder.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
package tunnel
import (
"context"
"sync"
"github.com/loft-sh/devpod/pkg/netstat"
devssh "github.com/loft-sh/devpod/pkg/ssh"
"github.com/loft-sh/log"
"golang.org/x/crypto/ssh"
)
func newForwarder(sshClient *ssh.Client, forwardedPorts []string, log log.Logger) netstat.Forwarder {
return &forwarder{
sshClient: sshClient,
forwardedPorts: forwardedPorts,
portMap: map[string]context.CancelFunc{},
log: log,
}
}
type forwarder struct {
m sync.Mutex
sshClient *ssh.Client
forwardedPorts []string
portMap map[string]context.CancelFunc
log log.Logger
}
func (f *forwarder) Forward(port string) error {
f.m.Lock()
defer f.m.Unlock()
if f.isExcluded(port) || f.portMap[port] != nil {
return nil
}
cancelCtx, cancel := context.WithCancel(context.Background())
f.portMap[port] = cancel
f.log.Infof("Start port-forwarding on port %s", port)
go func(port string) {
// do the forward
err := devssh.PortForward(cancelCtx, f.sshClient, "tcp", "localhost:"+port, "tcp", "localhost:"+port, 0, f.log)
if err != nil {
f.log.Errorf("Error port forwarding %s: %v", port, err)
}
}(port)
return nil
}
func (f *forwarder) StopForward(port string) error {
f.m.Lock()
defer f.m.Unlock()
if f.isExcluded(port) || f.portMap[port] == nil {
return nil
}
f.log.Infof("Stop port-forwarding on port %s", port)
f.portMap[port]()
delete(f.portMap, port)
return nil
}
func (f *forwarder) isExcluded(port string) bool {
for _, p := range f.forwardedPorts {
if p == port {
return true
}
}
return false
}