packer/plugin: Managed clients for automatic cleanup
This commit is contained in:
parent
c8079a4290
commit
26a998f721
|
@ -8,7 +8,6 @@ import (
|
|||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@ -41,6 +40,6 @@ func main() {
|
|||
}
|
||||
|
||||
exitCode, _ := env.Cli(os.Args[1:])
|
||||
time.Sleep(1 * time.Second)
|
||||
plugin.CleanupClients()
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
|
|
@ -8,15 +8,39 @@ import (
|
|||
"log"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This is a slice of the "managed" clients which are cleaned up when
|
||||
// calling Cleanup
|
||||
var managedClients = make([]*client, 0, 5)
|
||||
|
||||
type client struct {
|
||||
cmd *exec.Cmd
|
||||
exited bool
|
||||
doneLogging bool
|
||||
}
|
||||
|
||||
// This makes sure all the managed subprocesses are killed and properly
|
||||
// logged. This should be called before the parent process running the
|
||||
// plugins exits.
|
||||
func CleanupClients() {
|
||||
// Kill all the managed clients in parallel and use a WaitGroup
|
||||
// to wait for them all to finish up.
|
||||
var wg sync.WaitGroup
|
||||
for _, client := range managedClients {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
client.Kill()
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func NewClient(cmd *exec.Cmd) *client {
|
||||
return &client{
|
||||
cmd,
|
||||
|
@ -25,6 +49,12 @@ func NewClient(cmd *exec.Cmd) *client {
|
|||
}
|
||||
}
|
||||
|
||||
func NewManagedClient(cmd *exec.Cmd) (result *client) {
|
||||
result = NewClient(cmd)
|
||||
managedClients = append(managedClients, result)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *client) Exited() bool {
|
||||
return c.exited
|
||||
}
|
||||
|
|
|
@ -52,7 +52,7 @@ func (c *cmdCommand) checkExit(p interface{}, cb func()) {
|
|||
//
|
||||
// This function guarantees the subprocess will end in a timely manner.
|
||||
func Command(cmd *exec.Cmd) (result packer.Command, err error) {
|
||||
cmdClient := NewClient(cmd)
|
||||
cmdClient := NewManagedClient(cmd)
|
||||
address, err := cmdClient.Start()
|
||||
if err != nil {
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue