Skip to content

Commit

Permalink
Merge pull request shadowsocks#149 from lixin9311/plugin-lifecycle
Browse files Browse the repository at this point in the history
Improving the lifecycle management of the plugin
  • Loading branch information
lixin9311 authored Sep 22, 2019
2 parents b423f77 + 5f7ec9f commit 3ebf450
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
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
40 changes: 35 additions & 5 deletions 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,34 @@ func startPlugin(plugin, pluginOpts, ssAddr string, isServer bool) (newAddr stri
return
}

func execPlugin(plugin, pluginOpts, remoteHost, remotePort, localHost, localPort string) error {
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) (err error) {
pluginFile := plugin
if fileExists(plugin) {
plugin = "./" + plugin
if !filepath.IsAbs(plugin) {
pluginFile = "./" + plugin
}
} else {
pluginFile, err = exec.LookPath(plugin)
if err != nil {
return err
}
}
logH := newLogHelper("[" + plugin + "]: ")
env := append(os.Environ(),
Expand All @@ -44,15 +74,15 @@ func execPlugin(plugin, pluginOpts, remoteHost, remotePort, localHost, localPort
"SS_PLUGIN_OPTIONS="+pluginOpts,
)
cmd := &exec.Cmd{
Path: plugin,
Args: []string{plugin},
Path: pluginFile,
Env: env,
Stdout: logH,
Stderr: logH,
}
if err := cmd.Start(); err != nil {
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 3ebf450

Please sign in to comment.