Clean up ssh tunnels during exit.

pull/11745/head
Vishal Jain 2021-06-22 15:32:07 -07:00
parent 811ff18161
commit bb0e516617
2 changed files with 34 additions and 14 deletions

View File

@ -33,6 +33,7 @@ type sshConn struct {
service string
cmd *exec.Cmd
ports []int
activeConn bool
}
func createSSHConn(name, sshPort, sshKey string, svc *v1.Service) *sshConn {
@ -90,6 +91,7 @@ func createSSHConn(name, sshPort, sshKey string, svc *v1.Service) *sshConn {
name: name,
service: svc.Name,
cmd: cmd,
activeConn: false,
}
}
@ -131,6 +133,7 @@ func createSSHConnWithRandomPorts(name, sshPort, sshKey string, svc *v1.Service)
service: svc.Name,
cmd: cmd,
ports: usedPorts,
activeConn: false,
}, nil
}
@ -142,14 +145,21 @@ func (c *sshConn) startAndWait() error {
return err
}
c.activeConn = true
// we ignore wait error because the process will be killed
_ = c.cmd.Wait()
// Wait is finished for connection, mark false.
c.activeConn = false
return nil
}
func (c *sshConn) stop() error {
if c.activeConn {
out.Step(style.Stopping, "Stopping tunnel for service {{.service}}.", out.V{"service": c.service})
return c.cmd.Process.Kill()
}
out.Step(style.Stopping, "Stopped tunnel for service {{.service}}.", out.V{"service": c.service})
return nil
}

View File

@ -63,6 +63,7 @@ func (t *SSHTunnel) Start() error {
if err != nil {
klog.Errorf("error cleaning up: %v", err)
}
t.stopActiveConnections()
return err
default:
}
@ -120,6 +121,15 @@ func (t *SSHTunnel) startConnection(svc v1.Service) {
}
}
func (t *SSHTunnel) stopActiveConnections() {
for _, conn := range t.conns {
err := conn.stop()
if err != nil {
klog.Errorf("error stopping ssh tunnel: %v", err)
}
}
}
func (t *SSHTunnel) stopMarkedConnections() {
for _, sshConn := range t.connsToStop {
err := sshConn.stop()