packer-cn/command/build/command.go

200 lines
4.2 KiB
Go
Raw Normal View History

2013-05-07 14:39:32 -04:00
package build
import (
2013-06-04 17:13:02 -04:00
"flag"
"fmt"
"github.com/mitchellh/packer/packer"
"io/ioutil"
2013-05-08 19:59:36 -04:00
"log"
"os"
"os/signal"
2013-06-02 18:17:04 -04:00
"strings"
"sync"
)
2013-05-07 14:39:32 -04:00
type Command byte
func (Command) Help() string {
2013-06-02 18:17:04 -04:00
return strings.TrimSpace(helpText)
}
2013-06-02 18:17:04 -04:00
func (c Command) Run(env packer.Environment, args []string) int {
2013-06-04 17:13:02 -04:00
var cfgOnly []string
cmdFlags := flag.NewFlagSet("build", flag.ContinueOnError)
cmdFlags.Usage = func() { env.Ui().Say(c.Help()) }
cmdFlags.Var((*stringSliceValue)(&cfgOnly), "only", "only build the given builds by name")
if err := cmdFlags.Parse(args); err != nil {
return 1
}
args = cmdFlags.Args()
if len(args) != 1 {
2013-06-04 17:13:02 -04:00
cmdFlags.Usage()
return 1
}
// Read the file into a byte array so that we can parse the template
log.Printf("Reading template: %s", args[0])
tplData, err := ioutil.ReadFile(args[0])
if err != nil {
env.Ui().Error(fmt.Sprintf("Failed to read template file: %s", err))
return 1
}
// Parse the template into a machine-usable format
2013-05-08 19:59:36 -04:00
log.Println("Parsing template...")
tpl, err := packer.ParseTemplate(tplData)
if err != nil {
env.Ui().Error(fmt.Sprintf("Failed to parse template: %s", err))
return 1
}
// The component finder for our builds
components := &packer.ComponentFinder{
2013-05-24 00:59:03 -04:00
Builder: env.Builder,
Hook: env.Hook,
Provisioner: env.Provisioner,
}
// Go through each builder and compile the builds that we care about
2013-05-08 19:59:36 -04:00
buildNames := tpl.BuildNames()
builds := make([]packer.Build, 0, len(buildNames))
for _, buildName := range buildNames {
2013-06-04 17:13:02 -04:00
if len(cfgOnly) > 0 {
found := false
for _, only := range cfgOnly {
if buildName == only {
found = true
break
}
}
if !found {
log.Printf("Skipping build '%s' because not specified by -only.", buildName)
continue
}
}
log.Printf("Creating build: %s", buildName)
build, err := tpl.Build(buildName, components)
2013-05-08 19:59:36 -04:00
if err != nil {
env.Ui().Error(fmt.Sprintf("Failed to create build '%s': \n\n%s", buildName, err))
2013-05-08 19:59:36 -04:00
return 1
}
builds = append(builds, build)
}
// Compile all the UIs for the builds
2013-06-03 16:43:38 -04:00
colors := [5]packer.UiColor{
packer.UiColorGreen,
packer.UiColorYellow,
packer.UiColorBlue,
packer.UiColorMagenta,
packer.UiColorCyan,
}
buildUis := make(map[string]packer.Ui)
2013-06-03 16:43:38 -04:00
for i, b := range builds {
var ui packer.Ui
ui = &packer.ColoredUi{
colors[i%len(colors)],
env.Ui(),
}
2013-06-03 16:43:38 -04:00
ui = &packer.PrefixedUi{
fmt.Sprintf("==> %s", b.Name()),
2013-06-03 14:40:08 -04:00
fmt.Sprintf(" %s", b.Name()),
ui,
}
2013-06-03 16:43:38 -04:00
buildUis[b.Name()] = ui
ui.Say(fmt.Sprintf("%s output will be in this color.", b.Name()))
}
2013-05-09 14:32:03 -04:00
// Prepare all the builds
for _, b := range builds {
log.Printf("Preparing build: %s", b.Name())
2013-05-22 19:20:40 -04:00
err := b.Prepare(buildUis[b.Name()])
if err != nil {
env.Ui().Error(err.Error())
return 1
}
2013-05-09 14:32:03 -04:00
}
// Run all the builds in parallel and wait for them to complete
var wg sync.WaitGroup
2013-05-22 01:38:56 -04:00
artifacts := make(map[string]packer.Artifact)
for _, b := range builds {
log.Printf("Starting build run: %s", b.Name())
// Increment the waitgroup so we wait for this item to finish properly
wg.Add(1)
// Run the build in a goroutine
go func() {
defer wg.Done()
2013-05-22 01:38:56 -04:00
artifacts[b.Name()] = b.Run(buildUis[b.Name()])
}()
}
// Handle signals
var interruptWg sync.WaitGroup
interrupted := false
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
go func() {
<-sigCh
interruptWg.Add(1)
defer interruptWg.Done()
interrupted = true
log.Println("Interrupted! Cancelling builds...")
var wg sync.WaitGroup
for _, b := range builds {
wg.Add(1)
go func() {
defer wg.Done()
log.Printf("Stopping build: %s", b.Name())
b.Cancel()
}()
}
wg.Wait()
}()
// Wait for both the builds to complete and the interrupt handler,
// if it is interrupted.
wg.Wait()
interruptWg.Wait()
if interrupted {
env.Ui().Say("Cleanly cancelled builds after being interrupted.")
return 1
}
2013-05-22 01:38:56 -04:00
// Output all the artifacts
2013-05-22 16:25:12 -04:00
env.Ui().Say("\n==> The build completed! The artifacts created were:")
2013-05-22 01:38:56 -04:00
for name, artifact := range artifacts {
env.Ui().Say(fmt.Sprintf("--> %s:", name))
if artifact != nil {
env.Ui().Say(artifact.String())
} else {
env.Ui().Say("<nothing>")
}
2013-05-22 01:38:56 -04:00
}
return 0
}
func (Command) Synopsis() string {
return "build image(s) from template"
}