Skip to content

Commit

Permalink
Better plugin life-cycle management
Browse files Browse the repository at this point in the history
  • Loading branch information
lixin9311 committed Sep 22, 2019
1 parent b423f77 commit 550ec5f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ func main() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
killPlugin()
}

func parseURL(s string) (addr, cipher, password string, err error) {
Expand Down
27 changes: 26 additions & 1 deletion plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@ import (
"net"
"os"
"os/exec"
"path/filepath"
"syscall"
"time"
)

var pluginCmd *exec.Cmd

func startPlugin(plugin, pluginOpts, ssAddr string, isServer bool) (newAddr string, err error) {
logf("starting plugin (%s) with option (%s)....", plugin, pluginOpts)
freePort, err := getFreePort()
Expand All @@ -31,9 +36,28 @@ func startPlugin(plugin, pluginOpts, ssAddr string, isServer bool) (newAddr stri
return
}

func killPlugin() {
if pluginCmd != nil {
pluginCmd.Process.Signal(syscall.SIGTERM)
waitCh := make(chan struct{})
go func() {
pluginCmd.Wait()
close(waitCh)
}()
timeout := time.After(3 * time.Second)
select {
case <-waitCh:
case <-timeout:
pluginCmd.Process.Kill()
}
}
}

func execPlugin(plugin, pluginOpts, remoteHost, remotePort, localHost, localPort string) error {
if fileExists(plugin) {
plugin = "./" + plugin
if !filepath.IsAbs(plugin) {
plugin = "./" + plugin
}
}
logH := newLogHelper("[" + plugin + "]: ")
env := append(os.Environ(),
Expand All @@ -53,6 +77,7 @@ func execPlugin(plugin, pluginOpts, remoteHost, remotePort, localHost, localPort
if err := cmd.Start(); err != nil {
return err
}
pluginCmd = cmd
go func() {
if err := cmd.Wait(); err != nil {
logf("plugin exited (%v)\n", err)
Expand Down

0 comments on commit 550ec5f

Please sign in to comment.