2020-04-22 16:59:29 -04:00
|
|
|
// +build !windows
|
|
|
|
|
|
|
|
package googlecompute
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"os/exec"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewTunnelDriver() TunnelDriver {
|
|
|
|
return &TunnelDriverLinux{}
|
|
|
|
}
|
|
|
|
|
|
|
|
type TunnelDriverLinux struct {
|
|
|
|
cmd *exec.Cmd
|
|
|
|
}
|
|
|
|
|
2020-07-07 18:37:45 -04:00
|
|
|
func (t *TunnelDriverLinux) StartTunnel(cancelCtx context.Context, tempScriptFileName string, timeout int) error {
|
2020-04-22 16:59:29 -04:00
|
|
|
cmd := exec.CommandContext(cancelCtx, tempScriptFileName)
|
|
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
|
|
|
|
2020-07-07 18:37:45 -04:00
|
|
|
err := RunTunnelCommand(cmd, timeout)
|
2020-04-22 16:59:29 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store successful command on step so we can access it to cancel it
|
|
|
|
// later.
|
|
|
|
t.cmd = cmd
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TunnelDriverLinux) StopTunnel() {
|
|
|
|
if t.cmd != nil && t.cmd.Process != nil {
|
|
|
|
log.Printf("Cleaning up the IAP tunnel...")
|
2020-04-22 17:26:50 -04:00
|
|
|
// Why not just cmd.Process.Kill()? I'm glad you asked. The gcloud
|
2020-04-22 16:59:29 -04:00
|
|
|
// call spawns a python subprocess that listens on the port, and you
|
2020-04-24 14:09:00 -04:00
|
|
|
// need to use the process _group_ id to halt this process and its
|
2020-04-22 16:59:29 -04:00
|
|
|
// daemon child. We create the group ID with the syscall.SysProcAttr
|
|
|
|
// call inside the retry loop above, and then store that ID on the
|
2020-04-24 14:09:00 -04:00
|
|
|
// command so we can halt it here.
|
2020-04-23 17:30:38 -04:00
|
|
|
err := syscall.Kill(-t.cmd.Process.Pid, syscall.SIGINT)
|
2020-04-22 17:20:29 -04:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Issue stopping IAP tunnel: %s", err)
|
|
|
|
}
|
2020-04-22 16:59:29 -04:00
|
|
|
} else {
|
|
|
|
log.Printf("Couldn't find IAP tunnel process to kill. Continuing.")
|
|
|
|
}
|
|
|
|
}
|