Commit 607372f7 authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

provisioner/chef-solo: massive refactor and style nitpick

parent 4a5a8c60
...@@ -4,20 +4,14 @@ ...@@ -4,20 +4,14 @@
package chefsolo package chefsolo
import ( import (
"bufio"
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/mitchellh/iochan"
"github.com/mitchellh/packer/common" "github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/packer"
"io"
"io/ioutil"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"text/template"
) )
const ( const (
...@@ -32,12 +26,15 @@ var Ui packer.Ui ...@@ -32,12 +26,15 @@ var Ui packer.Ui
type Config struct { type Config struct {
common.PackerConfig `mapstructure:",squash"` common.PackerConfig `mapstructure:",squash"`
CookbooksPaths []string `mapstructure:"cookbooks_paths"` CookbookPaths []string `mapstructure:"cookbook_paths"`
InstallCommand string `mapstructure:"install_command"` ExecuteCommand string `mapstructure:"execute_command"`
Recipes []string InstallCommand string `mapstructure:"install_command"`
Json map[string]interface{} RemoteCookbookPaths []string `mapstructure:"remote_cookbook_paths"`
PreventSudo bool `mapstructure:"prevent_sudo"` Json map[string]interface{}
SkipInstall bool `mapstructure:"skip_install"` PreventSudo bool `mapstructure:"prevent_sudo"`
RunList []string `mapstructure:"run_list"`
SkipInstall bool `mapstructure:"skip_install"`
StagingDir string `mapstructure:"staging_directory"`
tpl *packer.ConfigTemplate tpl *packer.ConfigTemplate
} }
...@@ -46,8 +43,12 @@ type Provisioner struct { ...@@ -46,8 +43,12 @@ type Provisioner struct {
config Config config Config
} }
type ExecuteRecipeTemplate struct { type ConfigTemplate struct {
SoloRbPath string CookbookPaths string
}
type ExecuteTemplate struct {
ConfigPath string
JsonPath string JsonPath string
Sudo bool Sudo bool
} }
...@@ -68,31 +69,26 @@ func (p *Provisioner) Prepare(raws ...interface{}) error { ...@@ -68,31 +69,26 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
} }
p.config.tpl.UserVars = p.config.PackerUserVars p.config.tpl.UserVars = p.config.PackerUserVars
// Accumulate any errors if p.config.ExecuteCommand == "" {
errs := common.CheckUnusedConfig(md) p.config.ExecuteCommand = "{{if .Sudo}}sudo {{end}}chef-solo --no-color -c {{.ConfigPath}} -j {{.JsonPath}}"
if p.config.CookbooksPaths == nil {
p.config.CookbooksPaths = []string{DefaultCookbooksPath}
} }
if p.config.InstallCommand == "" { if p.config.InstallCommand == "" {
p.config.InstallCommand = "curl -L https://www.opscode.com/chef/install.sh | {{if .Sudo}}sudo {{end}}bash" p.config.InstallCommand = "curl -L https://www.opscode.com/chef/install.sh | {{if .Sudo}}sudo {{end}}bash"
} }
if p.config.Recipes == nil { if p.config.RunList == nil {
p.config.Recipes = make([]string, 0) p.config.RunList = make([]string, 0)
} }
if p.config.Json != nil { if p.config.StagingDir == "" {
if _, err := json.Marshal(p.config.Json); err != nil { p.config.StagingDir = "/tmp/packer-chef-solo"
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Bad JSON: %s", err))
}
} else {
p.config.Json = make(map[string]interface{})
} }
for _, path := range p.config.CookbooksPaths { // Accumulate any errors
errs := common.CheckUnusedConfig(md)
for _, path := range p.config.CookbookPaths {
pFileInfo, err := os.Stat(path) pFileInfo, err := os.Stat(path)
if err != nil || !pFileInfo.IsDir() { if err != nil || !pFileInfo.IsDir() {
...@@ -109,218 +105,129 @@ func (p *Provisioner) Prepare(raws ...interface{}) error { ...@@ -109,218 +105,129 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
} }
func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error { func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
var err error
Ui = ui
if !p.config.SkipInstall { if !p.config.SkipInstall {
if err := p.installChef(ui, comm); err != nil { if err := p.installChef(ui, comm); err != nil {
return fmt.Errorf("Error installing Chef: %s", err) return fmt.Errorf("Error installing Chef: %s", err)
} }
} }
err = CreateRemoteDirectory(RemoteCookbookPath, comm) if err := p.createStagingDir(ui, comm); err != nil {
if err != nil { return fmt.Errorf("Error creating staging directory: %s", err)
return fmt.Errorf("Error creating remote staging directory: %s", err)
} }
soloRbPath, err := CreateSoloRb(p.config.CookbooksPaths, comm) // TODO(mitchellh): Upload cookbooks
if err != nil {
return fmt.Errorf("Error creating Chef Solo configuration file: %s", err)
}
jsonPath, err := CreateAttributesJson(p.config.Json, p.config.Recipes, comm) configPath, err := p.createConfig(ui, comm)
if err != nil { if err != nil {
return fmt.Errorf("Error uploading JSON attributes file: %s", err) return fmt.Errorf("Error creating Chef config file: %s", err)
} }
// Upload all cookbooks jsonPath, err := p.createJson(ui, comm)
for _, path := range p.config.CookbooksPaths { if err != nil {
ui.Say(fmt.Sprintf("Copying cookbook path: %s", path)) return fmt.Errorf("Error creating JSON attributes: %s", err)
err = UploadLocalDirectory(path, comm)
if err != nil {
return fmt.Errorf("Error uploading cookbooks: %s", err)
}
} }
// Execute requested recipes if err := p.executeChef(ui, comm, configPath, jsonPath); err != nil {
ui.Say("Beginning Chef Solo run") return fmt.Errorf("Error executing Chef: %s", err)
// Compile the command
var command bytes.Buffer
t := template.Must(template.New("chef-run").Parse("{{if .Sudo}}sudo {{end}}chef-solo --no-color -c {{.SoloRbPath}} -j {{.JsonPath}}"))
t.Execute(&command, &ExecuteRecipeTemplate{soloRbPath, jsonPath, !p.config.PreventSudo})
err = executeCommand(command.String(), comm)
if err != nil {
return fmt.Errorf("Error running Chef Solo: %s", err)
} }
return nil return nil
} }
func UploadLocalDirectory(localDir string, comm packer.Communicator) (err error) { func (p *Provisioner) createConfig(ui packer.Ui, comm packer.Communicator) (string, error) {
visitPath := func(path string, f os.FileInfo, err error) (err2 error) { ui.Message("Creating configuration file 'solo.rb'")
var remotePath = RemoteCookbookPath + "/" + path
if f.IsDir() { cookbook_paths := make([]string, len(p.config.RemoteCookbookPaths))
// Make remote directory for i, path := range p.config.RemoteCookbookPaths {
err = CreateRemoteDirectory(remotePath, comm) cookbook_paths[i] = fmt.Sprintf(`"%s"`, path)
if err != nil {
return err
}
} else {
// Upload file to existing directory
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("Error opening file: %s", err)
}
err = comm.Upload(remotePath, file)
if err != nil {
return fmt.Errorf("Error uploading file: %s", err)
}
}
return
} }
log.Printf("Uploading directory %s", localDir) configString, err := p.config.tpl.Process(DefaultConfigTemplate, &ConfigTemplate{
err = filepath.Walk(localDir, visitPath) CookbookPaths: strings.Join(cookbook_paths, ","),
})
if err != nil { if err != nil {
return fmt.Errorf("Error uploading cookbook %s: %s", localDir, err) return "", err
} }
return nil remotePath := filepath.Join(p.config.StagingDir, "solo.rb")
} if err := comm.Upload(remotePath, bytes.NewReader([]byte(configString))); err != nil {
return "", err
func CreateRemoteDirectory(path string, comm packer.Communicator) (err error) {
log.Printf("Creating remote directory: %s ", path)
var copyCommand = []string{"mkdir -p", path}
var cmd packer.RemoteCmd
cmd.Command = strings.Join(copyCommand, " ")
var stdout bytes.Buffer
cmd.Stdout = &stdout
// Start the command
if err := comm.Start(&cmd); err != nil {
return fmt.Errorf("Unable to create remote directory %s: %d", path, err)
} }
// Wait for it to complete return remotePath, nil
cmd.Wait()
return
} }
func CreateSoloRb(cookbooksPaths []string, comm packer.Communicator) (str string, err error) { func (p *Provisioner) createJson(ui packer.Ui, comm packer.Communicator) (string, error) {
Ui.Say("Creating Chef configuration file...") ui.Message("Creating JSON attribute file")
remotePath := RemoteStagingPath + "/solo.rb"
tf, err := ioutil.TempFile("", "packer-chef-solo-rb")
if err != nil {
return "", fmt.Errorf("Error preparing Chef solo.rb: %s", err)
}
// Write our contents to it jsonData := make(map[string]interface{})
writer := bufio.NewWriter(tf)
var cookbooksPathsFull = make([]string, len(cookbooksPaths)) // Copy the configured JSON
for i, path := range cookbooksPaths { for k, v := range p.config.Json {
cookbooksPathsFull[i] = "\"" + RemoteCookbookPath + "/" + path + "\"" jsonData[k] = v
} }
var contents bytes.Buffer // Set the run list if it was specified
var soloRbText = ` if len(p.config.RunList) > 0 {
file_cache_path "{{.FileCachePath}}" jsonData["run_list"] = p.config.RunList
cookbook_path [{{.CookbookPath}}]
`
t := template.Must(template.New("soloRb").Parse(soloRbText))
t.Execute(&contents, map[string]string{
"FileCachePath": RemoteFileCachePath,
"CookbookPath": strings.Join(cookbooksPathsFull, ","),
})
if _, err := writer.WriteString(contents.String()); err != nil {
return "", fmt.Errorf("Error preparing solo.rb: %s", err)
} }
if err := writer.Flush(); err != nil { jsonBytes, err := json.MarshalIndent(jsonData, "", " ")
return "", fmt.Errorf("Error preparing solo.rb: %s", err) if err != nil {
return "", err
} }
name := tf.Name() // Upload the bytes
tf.Close() remotePath := filepath.Join(p.config.StagingDir, "node.json")
f, err := os.Open(name) if err := comm.Upload(remotePath, bytes.NewReader(jsonBytes)); err != nil {
defer os.Remove(name) return "", err
log.Printf("Chef configuration file contents: %s", contents)
// Upload the Chef Solo configuration file to the cookbook directory.
log.Printf("Uploading chef configuration file to %s", remotePath)
err = comm.Upload(remotePath, f)
if err != nil {
return "", fmt.Errorf("Error uploading Chef Solo configuration file: %s", err)
} }
return remotePath, nil return remotePath, nil
} }
func CreateAttributesJson(jsonAttrs map[string]interface{}, recipes []string, comm packer.Communicator) (str string, err error) { func (p *Provisioner) createStagingDir(ui packer.Ui, comm packer.Communicator) error {
Ui.Say("Creating and uploading Chef attributes file") ui.Message(fmt.Sprintf("Creating staging directory: %s", p.config.StagingDir))
remotePath := RemoteStagingPath + "/node.json" cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("mkdir -p '%s'", p.config.StagingDir),
var formattedRecipes []string
for _, value := range recipes {
formattedRecipes = append(formattedRecipes, "recipe["+value+"]")
} }
// Add Recipes to JSON if err := cmd.StartWithUi(comm, ui); err != nil {
if len(formattedRecipes) > 0 { return err
log.Printf("Overriding node run list: %s", strings.Join(formattedRecipes, ", "))
jsonAttrs["run_list"] = formattedRecipes
} }
// Convert to JSON string if cmd.ExitStatus != 0 {
jsonString, err := json.MarshalIndent(jsonAttrs, "", " ") return fmt.Errorf("Non-zero exit status.")
if err != nil {
return "", fmt.Errorf("Error parsing JSON attributes: %s", err)
} }
tf, err := ioutil.TempFile("", "packer-chef-solo-json") return nil
}
func (p *Provisioner) executeChef(ui packer.Ui, comm packer.Communicator, config string, json string) error {
command, err := p.config.tpl.Process(p.config.InstallCommand, &ExecuteTemplate{
ConfigPath: config,
JsonPath: json,
Sudo: !p.config.PreventSudo,
})
if err != nil { if err != nil {
return "", fmt.Errorf("Error preparing Chef attributes file: %s", err) return err
} }
defer os.Remove(tf.Name())
// Write our contents to it ui.Message(fmt.Sprintf("Executing Chef: %s", command))
writer := bufio.NewWriter(tf)
if _, err := writer.WriteString(string(jsonString)); err != nil {
return "", fmt.Errorf("Error preparing Chef attributes file: %s", err)
}
if err := writer.Flush(); err != nil { cmd := &packer.RemoteCmd{
return "", fmt.Errorf("Error preparing Chef attributes file: %s", err) Command: command,
} }
jsonFile := tf.Name() if err := cmd.StartWithUi(comm, ui); err != nil {
tf.Close() return err
log.Printf("Opening %s for reading", jsonFile)
f, err := os.Open(jsonFile)
if err != nil {
return "", fmt.Errorf("Error opening JSON attributes file: %s", err)
} }
log.Printf("Uploading %s => %s", jsonFile, remotePath) if cmd.ExitStatus != 0 {
err = comm.Upload(remotePath, f) return fmt.Errorf("Non-zero exit status: %d", cmd.ExitStatus)
if err != nil {
return "", fmt.Errorf("Error uploading JSON attributes file: %s", err)
} }
return remotePath, nil return nil
} }
func (p *Provisioner) installChef(ui packer.Ui, comm packer.Communicator) error { func (p *Provisioner) installChef(ui packer.Ui, comm packer.Communicator) error {
...@@ -346,61 +253,6 @@ func (p *Provisioner) installChef(ui packer.Ui, comm packer.Communicator) error ...@@ -346,61 +253,6 @@ func (p *Provisioner) installChef(ui packer.Ui, comm packer.Communicator) error
return nil return nil
} }
func executeCommand(command string, comm packer.Communicator) (err error) { var DefaultConfigTemplate = `
// Setup the remote command cookbook_path [{{.CookbookPaths}}]
stdout_r, stdout_w := io.Pipe() `
stderr_r, stderr_w := io.Pipe()
var cmd packer.RemoteCmd
cmd.Command = command
cmd.Stdout = stdout_w
cmd.Stderr = stderr_w
log.Printf("Executing command: %s", cmd.Command)
err = comm.Start(&cmd)
if err != nil {
return fmt.Errorf("Failed executing command: %s", err)
}
exitChan := make(chan int, 1)
stdoutChan := iochan.DelimReader(stdout_r, '\n')
stderrChan := iochan.DelimReader(stderr_r, '\n')
go func() {
defer stdout_w.Close()
defer stderr_w.Close()
cmd.Wait()
exitChan <- cmd.ExitStatus
}()
OutputLoop:
for {
select {
case output := <-stderrChan:
Ui.Message(strings.TrimSpace(output))
case output := <-stdoutChan:
Ui.Message(strings.TrimSpace(output))
case exitStatus := <-exitChan:
log.Printf("Chef Solo provisioner exited with status %d", exitStatus)
if exitStatus != 0 {
return fmt.Errorf("Command exited with non-zero exit status: %d", exitStatus)
}
break OutputLoop
}
}
// Make sure we finish off stdout/stderr because we may have gotten
// a message from the exit channel first.
for output := range stdoutChan {
Ui.Message(output)
}
for output := range stderrChan {
Ui.Message(output)
}
return nil
}
...@@ -8,9 +8,7 @@ import ( ...@@ -8,9 +8,7 @@ import (
) )
func testConfig() map[string]interface{} { func testConfig() map[string]interface{} {
return map[string]interface{}{ return map[string]interface{}{}
// "inline": []interface{}{"foo", "bar"},
}
} }
func TestProvisioner_Impl(t *testing.T) { func TestProvisioner_Impl(t *testing.T) {
...@@ -21,48 +19,35 @@ func TestProvisioner_Impl(t *testing.T) { ...@@ -21,48 +19,35 @@ func TestProvisioner_Impl(t *testing.T) {
} }
} }
// Cookbook paths func TestProvisionerPrepare_cookbookPaths(t *testing.T) {
//////////////////
func TestProvisionerPrepare_DefaultCookbookPathIsUsed(t *testing.T) {
var p Provisioner
config := testConfig()
err := p.Prepare(config)
if err == nil {
t.Errorf("expected error to be thrown for unavailable cookbook path")
}
if len(p.config.CookbooksPaths) != 1 || p.config.CookbooksPaths[0] != DefaultCookbooksPath {
t.Errorf("unexpected default cookbook path: %s", p.config.CookbooksPaths)
}
}
func TestProvisionerPrepare_GivenCookbookPathsAreAddedToConfig(t *testing.T) {
var p Provisioner var p Provisioner
path1, err := ioutil.TempDir("", "cookbooks_one") path1, err := ioutil.TempDir("", "cookbooks_one")
if err != nil { if err != nil {
t.Errorf("err: %s", err) t.Fatalf("err: %s", err)
} }
path2, err := ioutil.TempDir("", "cookbooks_two") path2, err := ioutil.TempDir("", "cookbooks_two")
if err != nil { if err != nil {
t.Errorf("err: %s", err) t.Fatalf("err: %s", err)
} }
defer os.Remove(path1) defer os.Remove(path1)
defer os.Remove(path2) defer os.Remove(path2)
config := testConfig() config := testConfig()
config["cookbooks_paths"] = []string{path1, path2} config["cookbook_paths"] = []string{path1, path2}
err = p.Prepare(config) err = p.Prepare(config)
if err != nil { if err != nil {
t.Errorf("err: %s", err) t.Fatalf("err: %s", err)
}
if len(p.config.CookbookPaths) != 2 {
t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
} }
if len(p.config.CookbooksPaths) != 2 || p.config.CookbooksPaths[0] != path1 || p.config.CookbooksPaths[1] != path2 { if p.config.CookbookPaths[0] != path1 || p.config.CookbookPaths[1] != path2 {
t.Errorf("unexpected default cookbook path: %s", p.config.CookbooksPaths) t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
} }
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment