2013-11-09 01:17:46 -05:00
|
|
|
package docker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
2013-11-09 02:43:41 -05:00
|
|
|
"log"
|
2013-11-09 01:17:46 -05:00
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type StepRun struct {
|
|
|
|
containerId string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepRun) Run(state multistep.StateBag) multistep.StepAction {
|
|
|
|
config := state.Get("config").(*Config)
|
2013-11-09 02:43:41 -05:00
|
|
|
tempDir := state.Get("temp_dir").(string)
|
2013-11-09 01:17:46 -05:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
|
|
|
|
ui.Say("Starting docker container with /bin/bash")
|
|
|
|
|
2013-11-09 02:43:41 -05:00
|
|
|
// Args that we're going to pass to Docker
|
|
|
|
args := []string{
|
|
|
|
"run",
|
|
|
|
"-d", "-i", "-t",
|
|
|
|
"-v", fmt.Sprintf("%s:/packer-files", tempDir),
|
|
|
|
config.Image,
|
|
|
|
"/bin/bash",
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start the container
|
2013-11-09 01:17:46 -05:00
|
|
|
var stdout, stderr bytes.Buffer
|
2013-11-09 02:43:41 -05:00
|
|
|
cmd := exec.Command("docker", args...)
|
2013-11-09 01:17:46 -05:00
|
|
|
cmd.Stdout = &stdout
|
|
|
|
cmd.Stderr = &stderr
|
2013-11-09 02:43:41 -05:00
|
|
|
|
|
|
|
log.Printf("Starting container with args: %v", args)
|
2013-11-09 01:17:46 -05:00
|
|
|
if err := cmd.Start(); err != nil {
|
|
|
|
err := fmt.Errorf("Error running container: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := cmd.Wait(); err != nil {
|
2013-11-09 02:43:41 -05:00
|
|
|
err := fmt.Errorf("Error running container: %s\nStderr: %s",
|
|
|
|
err, stderr.String())
|
2013-11-09 01:17:46 -05:00
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
2013-11-09 02:43:41 -05:00
|
|
|
// Capture the container ID, which is alone on stdout
|
2013-11-09 01:17:46 -05:00
|
|
|
s.containerId = strings.TrimSpace(stdout.String())
|
|
|
|
ui.Message(fmt.Sprintf("Container ID: %s", s.containerId))
|
|
|
|
|
2013-11-09 02:43:41 -05:00
|
|
|
state.Put("container_id", s.containerId)
|
2013-11-09 01:17:46 -05:00
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepRun) Cleanup(state multistep.StateBag) {
|
|
|
|
if s.containerId == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-11-09 02:43:41 -05:00
|
|
|
// Kill the container. We don't handle errors because errors usually
|
|
|
|
// just mean that the container doesn't exist anymore, which isn't a
|
|
|
|
// big deal.
|
2013-11-09 01:17:46 -05:00
|
|
|
exec.Command("docker", "kill", s.containerId).Run()
|
|
|
|
}
|