github.com/technosophos/deis@v1.7.1-0.20150915173815-f9005256004b/builder/commands.go (about)

     1  package builder
     2  
     3  import (
     4  	"os"
     5  	"os/signal"
     6  	"time"
     7  
     8  	"github.com/Masterminds/cookoo"
     9  	"github.com/Masterminds/cookoo/log"
    10  	"github.com/Masterminds/cookoo/safely"
    11  )
    12  
    13  // Sleep delays the execution of the remainder of the chain of commands.
    14  //
    15  // Params:
    16  // 	-duration (time.Duration): Time to sleep.
    17  //  -message (string): The message to log when entering sleep.
    18  func Sleep(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
    19  	dur := p.Get("duration", 10*time.Millisecond).(time.Duration)
    20  	msg := p.Get("messages", "Sleeping").(string)
    21  	log.Info(c, msg)
    22  	time.Sleep(dur)
    23  	log.Info(c, "Woke up.")
    24  	return true, nil
    25  }
    26  
    27  // KillOnExit kills PIDs when the program exits.
    28  //
    29  // Otherwise, this blocks until an os.Interrupt or os.Kill is received.
    30  //
    31  // Params:
    32  //  This treats Params as a map of process names (unimportant) to PIDs. It then
    33  // attempts to kill all of the pids that it receives.
    34  func KillOnExit(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
    35  	sigs := make(chan os.Signal, 1)
    36  	signal.Notify(sigs, os.Interrupt, os.Kill)
    37  
    38  	safely.GoDo(c, func() {
    39  		log.Info(c, "Builder is running.")
    40  
    41  		<-sigs
    42  
    43  		c.Log("info", "Builder received signal to stop.")
    44  		pids := p.AsMap()
    45  		killed := 0
    46  		for name, pid := range pids {
    47  			if pid, ok := pid.(int); ok {
    48  				if proc, err := os.FindProcess(pid); err == nil {
    49  					log.Infof(c, "Killing %s (pid=%d)", name, pid)
    50  					proc.Kill()
    51  					killed++
    52  				}
    53  			}
    54  		}
    55  	})
    56  	return nil, nil
    57  }