Add basic test file for provisioner-chef-solo.

This commit is contained in:
James Van Dyke 2013-07-11 10:47:51 -04:00
parent 24c4b5334b
commit a84f26bfdf
2 changed files with 121 additions and 52 deletions

View File

@ -5,6 +5,7 @@ package chefSolo
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"github.com/mitchellh/iochan" "github.com/mitchellh/iochan"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
@ -13,16 +14,15 @@ import (
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"path/filepath"
"strings" "strings"
"text/template" "text/template"
"path/filepath"
"encoding/json"
) )
const RemoteStagingPath = "/tmp/provision/chef-solo" const RemoteStagingPath = "/tmp/provision/chef-solo"
const RemoteFileCachePath = "/tmp/provision/chef-solo" const RemoteFileCachePath = "/tmp/provision/chef-solo"
const RemoteCookbookPath = "/tmp/provision/chef-solo/cookbooks" const RemoteCookbookPath = "/tmp/provision/chef-solo/cookbooks"
const DefaultCookbookPath = "cookbooks" const DefaultCookbooksPath = "cookbooks"
var Ui packer.Ui var Ui packer.Ui
@ -36,10 +36,10 @@ type config struct {
// A string of JSON that will be used as the JSON attributes for the // A string of JSON that will be used as the JSON attributes for the
// Chef run. // Chef run.
Json map[string]interface{} Json map[string]interface{}
// Option to avoid sudo use when executing commands. Defaults to false. // Option to avoid sudo use when executing commands. Defaults to false.
PreventSudo bool `mapstructure:"prevent_sudo"` PreventSudo bool `mapstructure:"prevent_sudo"`
// If true, skips installing Chef. Defaults to false. // If true, skips installing Chef. Defaults to false.
SkipInstall bool `mapstructure:"skip_install"` SkipInstall bool `mapstructure:"skip_install"`
} }
@ -50,8 +50,8 @@ type Provisioner struct {
type ExecuteRecipeTemplate struct { type ExecuteRecipeTemplate struct {
SoloRbPath string SoloRbPath string
JsonPath string JsonPath string
Sudo bool Sudo bool
} }
type ExecuteInstallChefTemplate struct { type ExecuteInstallChefTemplate struct {
@ -65,9 +65,10 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
return err return err
} }
} }
if p.config.CookbooksPaths == nil { if p.config.CookbooksPaths == nil {
p.config.CookbooksPaths = make([]string, 0) p.config.CookbooksPaths = []string{DefaultCookbooksPath}
} }
if p.config.Recipes == nil { if p.config.Recipes == nil {
@ -84,7 +85,7 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
for _, path := range p.config.CookbooksPaths { for _, path := range p.config.CookbooksPaths {
pFileInfo, err := os.Stat(path) pFileInfo, err := os.Stat(path)
if err != nil || !pFileInfo.IsDir() { if err != nil || !pFileInfo.IsDir() {
errs = append(errs, fmt.Errorf("Bad cookbook path '%s': %s", path, err)) errs = append(errs, fmt.Errorf("Bad cookbook path '%s': %s", path, err))
} }
@ -100,32 +101,32 @@ 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 {
cookbooksPaths := make([]string, len(p.config.CookbooksPaths)) cookbooksPaths := make([]string, len(p.config.CookbooksPaths))
copy(cookbooksPaths, p.config.CookbooksPaths) copy(cookbooksPaths, p.config.CookbooksPaths)
var err error var err error
Ui = ui Ui = ui
if !p.config.SkipInstall { if !p.config.SkipInstall {
err = InstallChefSolo(p.config.PreventSudo, comm) err = InstallChefSolo(p.config.PreventSudo, comm)
if err != nil { if err != nil {
return fmt.Errorf("Error installing Chef Solo: %s", err) return fmt.Errorf("Error installing Chef Solo: %s", err)
} }
} }
err = CreateRemoteDirectory(RemoteCookbookPath, comm) err = CreateRemoteDirectory(RemoteCookbookPath, comm)
if err != nil { if err != nil {
return fmt.Errorf("Error creating remote staging directory: %s", err) return fmt.Errorf("Error creating remote staging directory: %s", err)
} }
soloRbPath, err := CreateSoloRb(p.config.CookbooksPaths, comm) soloRbPath, err := CreateSoloRb(p.config.CookbooksPaths, comm)
if err != nil { if err != nil {
return fmt.Errorf("Error creating Chef Solo configuration file: %s", err) return fmt.Errorf("Error creating Chef Solo configuration file: %s", err)
} }
jsonPath, err := CreateAttributesJson(p.config.Json, p.config.Recipes, comm) jsonPath, err := CreateAttributesJson(p.config.Json, p.config.Recipes, comm)
if err != nil { if err != nil {
return fmt.Errorf("Error uploading JSON attributes file: %s", err) return fmt.Errorf("Error uploading JSON attributes file: %s", err)
} }
// Upload all cookbooks // Upload all cookbooks
for _, path := range cookbooksPaths { for _, path := range cookbooksPaths {
ui.Say(fmt.Sprintf("Copying cookbook path: %s", path)) ui.Say(fmt.Sprintf("Copying cookbook path: %s", path))
@ -134,27 +135,27 @@ func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
return fmt.Errorf("Error uploading cookbooks: %s", err) return fmt.Errorf("Error uploading cookbooks: %s", err)
} }
} }
// Execute requested recipes // Execute requested recipes
ui.Say("Beginning Chef Solo run") ui.Say("Beginning Chef Solo run")
// Compile the command // Compile the command
var command bytes.Buffer 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 := 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}) t.Execute(&command, &ExecuteRecipeTemplate{soloRbPath, jsonPath, !p.config.PreventSudo})
err = executeCommand(command.String(), comm) err = executeCommand(command.String(), comm)
if err != nil { if err != nil {
return fmt.Errorf("Error running Chef Solo: %s", err) return fmt.Errorf("Error running Chef Solo: %s", err)
} }
// return fmt.Errorf("Die") // return fmt.Errorf("Die")
return nil return nil
} }
func UploadLocalDirectory(localDir string, comm packer.Communicator) (err error) { func UploadLocalDirectory(localDir string, comm packer.Communicator) (err error) {
visitPath := func (path string, f os.FileInfo, err error) (err2 error) { visitPath := func(path string, f os.FileInfo, err error) (err2 error) {
var remotePath = RemoteCookbookPath + "/" + path var remotePath = RemoteCookbookPath + "/" + path
if f.IsDir() { if f.IsDir() {
// Make remote directory // Make remote directory
@ -168,7 +169,7 @@ func UploadLocalDirectory(localDir string, comm packer.Communicator) (err error)
if err != nil { if err != nil {
return fmt.Errorf("Error opening file: %s", err) return fmt.Errorf("Error opening file: %s", err)
} }
err = comm.Upload(remotePath, file) err = comm.Upload(remotePath, file)
if err != nil { if err != nil {
return fmt.Errorf("Error uploading file: %s", err) return fmt.Errorf("Error uploading file: %s", err)
@ -176,52 +177,52 @@ func UploadLocalDirectory(localDir string, comm packer.Communicator) (err error)
} }
return return
} }
err = filepath.Walk(localDir, visitPath) err = filepath.Walk(localDir, visitPath)
if err != nil { if err != nil {
return fmt.Errorf("Error uploading cookbook %s: %s", localDir, err) return fmt.Errorf("Error uploading cookbook %s: %s", localDir, err)
} }
return nil return nil
} }
func CreateRemoteDirectory(path string, comm packer.Communicator) (err error) { func CreateRemoteDirectory(path string, comm packer.Communicator) (err error) {
//Ui.Say(fmt.Sprintf("Creating directory: %s", path)) //Ui.Say(fmt.Sprintf("Creating directory: %s", path))
var copyCommand = []string{"mkdir -p", path} var copyCommand = []string{"mkdir -p", path}
var cmd packer.RemoteCmd var cmd packer.RemoteCmd
cmd.Command = strings.Join(copyCommand, " ") cmd.Command = strings.Join(copyCommand, " ")
var stdout bytes.Buffer var stdout bytes.Buffer
cmd.Stdout = &stdout cmd.Stdout = &stdout
// Start the command // Start the command
if err := comm.Start(&cmd); err != nil { if err := comm.Start(&cmd); err != nil {
return fmt.Errorf("Unable to create remote directory %s: %d", path, err) return fmt.Errorf("Unable to create remote directory %s: %d", path, err)
} }
// Wait for it to complete // Wait for it to complete
cmd.Wait() cmd.Wait()
return return
} }
func CreateSoloRb(cookbooksPaths []string, comm packer.Communicator) (str string, err error) { func CreateSoloRb(cookbooksPaths []string, comm packer.Communicator) (str string, err error) {
Ui.Say(fmt.Sprintf("Creating Chef configuration file...")) Ui.Say(fmt.Sprintf("Creating Chef configuration file..."))
remotePath := RemoteStagingPath + "/solo.rb" remotePath := RemoteStagingPath + "/solo.rb"
tf, err := ioutil.TempFile("", "packer-chef-solo-rb") tf, err := ioutil.TempFile("", "packer-chef-solo-rb")
if err != nil { if err != nil {
return "", fmt.Errorf("Error preparing Chef solo.rb: %s", err) return "", fmt.Errorf("Error preparing Chef solo.rb: %s", err)
} }
// Write our contents to it // Write our contents to it
writer := bufio.NewWriter(tf) writer := bufio.NewWriter(tf)
// Messy, messy... // Messy, messy...
cbPathsCat := "\"" + RemoteCookbookPath + "/" + strings.Join(cookbooksPaths, "\",\"" + RemoteCookbookPath + "/") + "\"" cbPathsCat := "\"" + RemoteCookbookPath + "/" + strings.Join(cookbooksPaths, "\",\""+RemoteCookbookPath+"/") + "\""
contents := "file_cache_path \"" + RemoteFileCachePath + "\"\ncookbook_path [" + cbPathsCat + "]\n" contents := "file_cache_path \"" + RemoteFileCachePath + "\"\ncookbook_path [" + cbPathsCat + "]\n"
if _, err := writer.WriteString(contents); err != nil { if _, err := writer.WriteString(contents); err != nil {
return "", fmt.Errorf("Error preparing solo.rb: %s", err) return "", fmt.Errorf("Error preparing solo.rb: %s", err)
} }
@ -229,16 +230,16 @@ func CreateSoloRb(cookbooksPaths []string, comm packer.Communicator) (str string
if err := writer.Flush(); err != nil { if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error preparing solo.rb: %s", err) return "", fmt.Errorf("Error preparing solo.rb: %s", err)
} }
name := tf.Name() name := tf.Name()
tf.Close() tf.Close()
f, err := os.Open(name) f, err := os.Open(name)
comm.Upload(remotePath, f) comm.Upload(remotePath, f)
defer os.Remove(name) defer os.Remove(name)
// Upload the Chef Solo configuration file to the cookbook directory. // Upload the Chef Solo configuration file to the cookbook directory.
if err != nil { if err != nil {
return "", fmt.Errorf("Error uploading Chef Solo configuration file: %s", err) return "", fmt.Errorf("Error uploading Chef Solo configuration file: %s", err)
} }
@ -249,21 +250,21 @@ func CreateSoloRb(cookbooksPaths []string, comm packer.Communicator) (str string
func CreateAttributesJson(jsonAttrs map[string]interface{}, recipes []string, comm packer.Communicator) (str string, err error) { func CreateAttributesJson(jsonAttrs map[string]interface{}, recipes []string, comm packer.Communicator) (str string, err error) {
Ui.Say(fmt.Sprintf("Creating and uploading Chef attributes file")) Ui.Say(fmt.Sprintf("Creating and uploading Chef attributes file"))
remotePath := RemoteStagingPath + "/node.json" remotePath := RemoteStagingPath + "/node.json"
var formattedRecipes []string var formattedRecipes []string
for _, value := range recipes { for _, value := range recipes {
formattedRecipes = append(formattedRecipes, "recipe[" + value + "]") formattedRecipes = append(formattedRecipes, "recipe["+value+"]")
} }
// Add Recipes to JSON // Add Recipes to JSON
jsonAttrs["run_list"] = formattedRecipes jsonAttrs["run_list"] = formattedRecipes
// Convert to JSON string // Convert to JSON string
jsonString, err := json.MarshalIndent(jsonAttrs, "", " ") jsonString, err := json.MarshalIndent(jsonAttrs, "", " ")
if err != nil { if err != nil {
return "", fmt.Errorf("Error parsing JSON attributes: %s", err) return "", fmt.Errorf("Error parsing JSON attributes: %s", err)
} }
tf, err := ioutil.TempFile("", "packer-chef-solo-json") tf, err := ioutil.TempFile("", "packer-chef-solo-json")
if err != nil { if err != nil {
return "", fmt.Errorf("Error preparing Chef attributes file: %s", err) return "", fmt.Errorf("Error preparing Chef attributes file: %s", err)
@ -279,10 +280,10 @@ func CreateAttributesJson(jsonAttrs map[string]interface{}, recipes []string, co
if err := writer.Flush(); err != nil { if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error preparing Chef attributes file: %s", err) return "", fmt.Errorf("Error preparing Chef attributes file: %s", err)
} }
jsonFile := tf.Name() jsonFile := tf.Name()
tf.Close() tf.Close()
log.Printf("Opening %s for reading", jsonFile) log.Printf("Opening %s for reading", jsonFile)
f, err := os.Open(jsonFile) f, err := os.Open(jsonFile)
if err != nil { if err != nil {
@ -294,22 +295,22 @@ func CreateAttributesJson(jsonAttrs map[string]interface{}, recipes []string, co
if err != nil { if err != nil {
return "", fmt.Errorf("Error uploading JSON attributes file: %s", err) return "", fmt.Errorf("Error uploading JSON attributes file: %s", err)
} }
return remotePath, nil return remotePath, nil
} }
func InstallChefSolo(preventSudo bool, comm packer.Communicator) (err error) { func InstallChefSolo(preventSudo bool, comm packer.Communicator) (err error) {
Ui.Say(fmt.Sprintf("Installing Chef Solo")) Ui.Say(fmt.Sprintf("Installing Chef Solo"))
var command bytes.Buffer var command bytes.Buffer
t := template.Must(template.New("install-chef").Parse("curl -L https://www.opscode.com/chef/install.sh | {{if .sudo}}sudo {{end}}bash")) t := template.Must(template.New("install-chef").Parse("curl -L https://www.opscode.com/chef/install.sh | {{if .sudo}}sudo {{end}}bash"))
t.Execute(&command, map[string]bool{"sudo": !preventSudo}) t.Execute(&command, map[string]bool{"sudo": !preventSudo})
err = executeCommand(command.String(), comm) err = executeCommand(command.String(), comm)
if err != nil { if err != nil {
return fmt.Errorf("Unable to install Chef Solo: %d", err) return fmt.Errorf("Unable to install Chef Solo: %d", err)
} }
return nil return nil
} }
@ -322,7 +323,7 @@ func executeCommand(command string, comm packer.Communicator) (err error) {
cmd.Command = command cmd.Command = command
cmd.Stdout = stdout_w cmd.Stdout = stdout_w
cmd.Stderr = stderr_w cmd.Stderr = stderr_w
//Ui.Say(fmt.Sprintf("Executing command: %s", cmd.Command)) //Ui.Say(fmt.Sprintf("Executing command: %s", cmd.Command))
log.Printf("Executing command: %s", cmd.Command) log.Printf("Executing command: %s", cmd.Command)
err = comm.Start(&cmd) err = comm.Start(&cmd)
@ -369,6 +370,6 @@ OutputLoop:
for output := range stderrChan { for output := range stderrChan {
Ui.Message(output) Ui.Message(output)
} }
return nil return nil
} }

View File

@ -0,0 +1,68 @@
package chefSolo
import (
"github.com/mitchellh/packer/packer"
"io/ioutil"
"os"
"testing"
)
func testConfig() map[string]interface{} {
return map[string]interface{}{
// "inline": []interface{}{"foo", "bar"},
}
}
func TestProvisioner_Impl(t *testing.T) {
var raw interface{}
raw = &Provisioner{}
if _, ok := raw.(packer.Provisioner); !ok {
t.Fatalf("must be a Provisioner")
}
}
// Cookbook paths
//////////////////
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
path1, err := ioutil.TempDir("", "cookbooks_one")
if err != nil {
t.Errorf("err: %s", err)
}
path2, err := ioutil.TempDir("", "cookbooks_two")
if err != nil {
t.Errorf("err: %s", err)
}
defer os.Remove(path1)
defer os.Remove(path2)
config := testConfig()
config["cookbooks_paths"] = []string{path1, path2}
err = p.Prepare(config)
if err != nil {
t.Errorf("err: %s", err)
}
if len(p.config.CookbooksPaths) != 2 || p.config.CookbooksPaths[0] != path1 || p.config.CookbooksPaths[1] != path2 {
t.Errorf("unexpected default cookbook path: %s", p.config.CookbooksPaths)
}
}