func DeleteTestStateBagStepDeleteResourceGroup() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")
	stateBag.Put(constants.ArmIsResourceGroupCreated, "Unit Test: IsResourceGroupCreated")

	return stateBag
}
Ejemplo n.º 2
0
func TestStepInjectConfiguration(t *testing.T) {
	env := new(multistep.BasicStateBag)
	os.Mkdir("tmp", 0777)
	env.Put("config_path", "tmp/")

	conf := config.NewDefault()

	// Create the configuration file sections and items
	conf.AddSection("gethub")
	conf.AddSection("github")
	conf.AddSection("ignores")
	conf.AddOption("gethub", "path", "tmp")
	conf.AddOption("github", "username", "foo")
	conf.AddOption("github", "token", "bar")
	conf.AddOption("ignores", "repo", "facebook")
	conf.AddOption("ignores", "owner", "pearkes")

	conf.WriteFile("tmp/.gethubconfig", 0644, "")

	step := &StepInjectConfiguration{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}

	os.RemoveAll("tmp")
}
func createTestStateBagStepGetIPAddress() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmPublicIPAddressName, "Unit Test: PublicIPAddressName")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")

	return stateBag
}
func createTestStateBagStepCreateResourceGroup() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmLocation, "Unit Test: Location")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")

	return stateBag
}
Ejemplo n.º 5
0
func createTestStateBagStepGetOSDisk() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmComputeName, "Unit Test: ComputeName")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")

	return stateBag
}
func createTestStateBagStepValidateTemplate() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmDeploymentName, "Unit Test: DeploymentName")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")

	return stateBag
}
Ejemplo n.º 7
0
func testStepCreateFloppyState(t *testing.T) multistep.StateBag {
	state := new(multistep.BasicStateBag)
	state.Put("ui", &packer.BasicUi{
		Reader: new(bytes.Buffer),
		Writer: new(bytes.Buffer),
	})
	return state
}
Ejemplo n.º 8
0
// getTestState is a utility function that sets up a BasicStateBag with a
// BasicUi
func getTestState() *multistep.BasicStateBag {
	state := new(multistep.BasicStateBag)
	state.Put("ui", &packer.BasicUi{
		Reader: new(bytes.Buffer),
		Writer: new(bytes.Buffer),
	})

	return state
}
Ejemplo n.º 9
0
func testState(t *testing.T) multistep.StateBag {
	state := new(multistep.BasicStateBag)
	state.Put("driver", new(vmwcommon.DriverMock))
	state.Put("ui", &packer.BasicUi{
		Reader: new(bytes.Buffer),
		Writer: new(bytes.Buffer),
	})
	return state
}
Ejemplo n.º 10
0
func testState(t *testing.T) multistep.StateBag {
	state := new(multistep.BasicStateBag)
	state.Put("hook", &packer.MockHook{})
	state.Put("ui", &packer.BasicUi{
		Reader: new(bytes.Buffer),
		Writer: new(bytes.Buffer),
	})
	return state
}
Ejemplo n.º 11
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	steps := []multistep.Step{
		&communicator.StepConnect{
			Config: &b.config.CommConfig,
			Host:   CommHost(b.config.CommConfig.Host()),
			SSHConfig: SSHConfig(
				b.config.CommConfig.SSHUsername,
				b.config.CommConfig.SSHPassword,
				b.config.CommConfig.SSHPrivateKey),
		},
		&common.StepProvision{},
	}

	// Setup the state bag and initial state for the steps
	state := new(multistep.BasicStateBag)
	state.Put("config", b.config)
	state.Put("hook", hook)
	state.Put("ui", ui)

	// Run!
	b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
	b.runner.Run(state)

	// If there was an error, return that
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// No errors, must've worked
	artifact := &NullArtifact{}
	return artifact, nil
}
Ejemplo n.º 12
0
func TestProcessStepResultShouldContinueForNonErrors(t *testing.T) {
	stateBag := new(multistep.BasicStateBag)

	code := processStepResult(nil, func(error) { t.Fatal("Should not be called!") }, stateBag)
	if _, ok := stateBag.GetOk(constants.Error); ok {
		t.Errorf("Error was nil, but was still in the state bag.")
	}

	if code != multistep.ActionContinue {
		t.Errorf("Expected ActionContinue(%d), but got=%d", multistep.ActionContinue, code)
	}
}
Ejemplo n.º 13
0
func TestStepCheckPath_Not_Exists(t *testing.T) {
	env := new(multistep.BasicStateBag)

	env.Put("path", "foobar/")

	step := &StepCheckPath{}

	results := step.Run(env)

	if results != multistep.ActionHalt {
		t.Fatal("step did not return ActionContinue")
	}
}
func testState(t *testing.T) multistep.StateBag {
	state := new(multistep.BasicStateBag)
	state.Put("config", testConfigStruct(t))
	state.Put("driver", &MockDriver{})
	state.Put("hook", &packer.MockHook{})
	state.Put("ui", &packer.BasicUi{
		Reader: new(bytes.Buffer),
		Writer: new(bytes.Buffer),
	})
	return state
}
Ejemplo n.º 15
0
func TestStepCheckPath_Exists(t *testing.T) {
	env := new(multistep.BasicStateBag)

	env.Put("path", "tmp/")
	os.Mkdir("tmp", 0777)

	step := &StepCheckPath{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}
	os.RemoveAll("tmp")
}
func TestStepCheckConfigurationFile_No_Config(t *testing.T) {
	env := new(multistep.BasicStateBag)

	os.Mkdir("tmp", 0777)
	env.Put("config_path", "tmp/")

	step := &StepCheckConfigurationFile{}

	results := step.Run(env)
	// Output: It seems as though you haven't set-up gethub. Please run `gethub authorize`

	if results != multistep.ActionHalt {
		t.Fatal("step did not return ActionHalt")
	}
	os.RemoveAll("tmp")
}
Ejemplo n.º 17
0
func TestProcessStepResultShouldHaltWhenTaskIsCancelled(t *testing.T) {
	stateBag := new(multistep.BasicStateBag)
	result := common.InterruptibleTaskResult{
		IsCancelled: true,
		Err:         nil,
	}

	code := processInterruptibleResult(result, func(error) { t.Fatal("Should not be called!") }, stateBag)
	if _, ok := stateBag.GetOk(constants.Error); ok {
		t.Errorf("Error was nil, but was still in the state bag.")
	}

	if code != multistep.ActionHalt {
		t.Errorf("Expected ActionHalt(%d), but got=%d", multistep.ActionHalt, code)
	}
}
Ejemplo n.º 18
0
func TestProcessStepResultShouldHaltOnError(t *testing.T) {
	stateBag := new(multistep.BasicStateBag)
	isSaidError := false

	code := processStepResult(fmt.Errorf("boom"), func(error) { isSaidError = true }, stateBag)
	if _, ok := stateBag.GetOk(constants.Error); !ok {
		t.Errorf("Error was non nil, but was not in the state bag.")
	}

	if !isSaidError {
		t.Errorf("Expected error to be said, but it was not.")
	}

	if code != multistep.ActionHalt {
		t.Errorf("Expected ActionHalt(%d), but got=%d", multistep.ActionHalt, code)
	}
}
Ejemplo n.º 19
0
func createTestStateBagStepCaptureImage() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmComputeName, "Unit Test: ComputeName")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")
	stateBag.Put(constants.ArmVirtualMachineCaptureParameters, &compute.VirtualMachineCaptureParameters{})

	return stateBag
}
func TestStepCheckConfigurationFile_Good_Config(t *testing.T) {
	env := new(multistep.BasicStateBag)

	os.Mkdir("tmp", 0777)
	env.Put("config_path", "tmp/")

	file, _ := os.Create("tmp/.gethubconfig")

	file.WriteString("\n[gethub]\npath: tmp/\n")

	step := &StepCheckConfigurationFile{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}

	os.RemoveAll("tmp")
}
func TestWinRMAddressFunc_UsesPortForwarding(t *testing.T) {
	config := wincommon.WinRMConfig{
		WinRMHost: "localhost",
		WinRMPort: 456,
	}

	state := new(multistep.BasicStateBag)
	state.Put("winrmHostPort", uint(123))

	f := WinRMAddressFunc(config)
	address, err := f(state)

	if err != nil {
		t.Fatalf("unexpected err %v", err)
	}

	if address != "localhost:123" {
		t.Errorf("should have forwarded to port 123, but was %s", address)
	}
}
Ejemplo n.º 22
0
func TestProcessStepResultShouldHaltOnTaskError(t *testing.T) {
	stateBag := new(multistep.BasicStateBag)
	isSaidError := false
	result := common.InterruptibleTaskResult{
		IsCancelled: false,
		Err:         fmt.Errorf("boom"),
	}

	code := processInterruptibleResult(result, func(error) { isSaidError = true }, stateBag)
	if _, ok := stateBag.GetOk(constants.Error); !ok {
		t.Errorf("Error was *not* nil, but was not in the state bag.")
	}

	if !isSaidError {
		t.Errorf("Expected error to be said, but it was not.")
	}

	if code != multistep.ActionHalt {
		t.Errorf("Expected ActionHalt(%d), but got=%d", multistep.ActionHalt, code)
	}
}
Ejemplo n.º 23
0
func main() {
	// Debugging and version flags
	debug := flag.Bool("debug", false, "Logs debugging information to STDOUT.")
	version := flag.Bool("version", false, "Prints the version and exits.")
	flag.BoolVar(debug, "d", false, "Logs debugging information to STDOUT.")
	flag.BoolVar(version, "v", false, "Prints the version and exits.")

	// Override the flag.Usage function to print custom usage info.
	flag.Usage = usage
	flag.Parse()
	arg := flag.Arg(0)

	// Discard logging if debug is turned off.
	if *debug == false {
		log.SetOutput(ioutil.Discard)
	}

	// Print the version and exit
	if *version {
		fmt.Println(versionString)
		os.Exit(1)
	}

	// Log enabled debugging
	log.Println("Debugging enabled for", versionString)

	state := new(multistep.BasicStateBag)
	state.Put("debug", *debug)
	state.Put("config_path", os.Getenv("GETCONFIG_PATH"))

	if arg == "authorize" {
		authorizeRunner(state)
	} else if arg == "" {
		updateRunner(state)
	} else {
		fmt.Println("Invalid argument: " + arg)
		// Prints the usage and exits
		usage()
	}
}
Ejemplo n.º 24
0
func TestESX5Driver_CommHost(t *testing.T) {
	const expected_host = "127.0.0.1"

	config := testConfig()
	config["communicator"] = "winrm"
	config["winrm_username"] = "******"
	config["winrm_password"] = "******"
	config["winrm_host"] = expected_host

	var b Builder
	warns, err := b.Prepare(config)
	if len(warns) > 0 {
		t.Fatalf("bad: %#v", warns)
	}
	if err != nil {
		t.Fatalf("should not have error: %s", err)
	}
	if host := b.config.CommConfig.Host(); host != expected_host {
		t.Fatalf("setup failed, bad host name: %s", host)
	}

	state := new(multistep.BasicStateBag)
	state.Put("config", &b.config)

	var driver ESX5Driver
	host, err := driver.CommHost(state)
	if err != nil {
		t.Fatalf("should not have error: %s", err)
	}
	if host != expected_host {
		t.Errorf("bad host name: %s", host)
	}
	address, ok := state.GetOk("vm_address")
	if !ok {
		t.Error("state not updated with vm_address")
	}
	if address.(string) != expected_host {
		t.Errorf("bad vm_address: %s", address.(string))
	}
}
func TestStepCheckConfigurationFile_Corrupt_Config(t *testing.T) {
	env := new(multistep.BasicStateBag)

	os.Mkdir("tmp", 0777)

	env.Put("config_path", "tmp/")
	file, _ := os.Create("tmp/.gethubconfig")

	// Some messy string
	file.WriteString("foobar!baz:bar\n\nfoob:ar")

	step := &StepCheckConfigurationFile{}

	results := step.Run(env)
	// Output: Something seems to be wrong with your ~/.gethubconfig file. Please run `gethub authorize`

	if results != multistep.ActionHalt {
		t.Fatal("step did not return ActionHalt")
	}

	os.RemoveAll("tmp")
}
func TestStepUpdateRepositories(t *testing.T) {
	env := new(multistep.BasicStateBag)
	env.Put("path", "tmp")
	env.Put("ignored_owners", []string{})
	env.Put("ignored_repos", []string{})

	originPath := "tmp/pearkes/origin"

	os.MkdirAll(originPath, 0777)

	// Create a fake repository to clone from
	cmdInit := exec.Command("git", "init", originPath)

	// Commit to the repoistory to avoid warnings
	os.Create(originPath + "/test")
	cmdAdd := exec.Command("git", "add", "test")
	cmdAdd.Dir = originPath
	cmdCommit := exec.Command("git", "commit", "-m", "initial commit")
	cmdCommit.Dir = originPath

	// Clone the repository
	cmdClone := exec.Command("git", "clone", originPath, "tmp/pearkes/test")

	cmdInit.Run()
	cmdAdd.Run()
	cmdCommit.Run()
	cmdClone.Run()

	repo := Repo{FullName: "pearkes/test", SSHUrl: "../origin"}
	env.Put("repos", []Repo{repo})

	step := &StepUpdateRepositories{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}
}
func createTestStateBagStepCreateResourceGroup() multistep.StateBag {
	stateBag := new(multistep.BasicStateBag)

	stateBag.Put(constants.ArmLocation, "Unit Test: Location")
	stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName")

	value := "Unit Test: Tags"
	tags := map[string]*string{
		"tag01": &value,
	}

	stateBag.Put(constants.ArmTags, &tags)

	return stateBag
}
Ejemplo n.º 28
0
func (b *Builder) validateAzureOptions(ui packer.Ui, state *multistep.BasicStateBag) error {

	var err error

	// Check Storage account (& container)
	ui.Message("Checking Storage Account...")
	availabilityResponse, err := storageservice.NewClient(b.client).CheckStorageAccountNameAvailability(b.config.StorageAccount)
	if err != nil {
		return err
	}

	if availabilityResponse.Result {
		return fmt.Errorf("Can't Find Storage Account '%s'", b.config.StorageAccount)
	}

	// Check image exists
	imageList, err := osimage.NewClient(b.client).ListOSImages()
	if err != nil {
		log.Printf("OS image client returned error: %s", err)
		return err
	}

	if osImage, found := FindOSImage(imageList.OSImages, b.config.OSImageLabel, b.config.Location); found {
		state.Put(constants.OSImageName, osImage.Name)
		state.Put(constants.IsOSImage, true)
		return nil
	} else {
		imageList, err := vmimage.NewClient(b.client).ListVirtualMachineImages()
		if err != nil {
			log.Printf("VM image client returned error: %s", err)
			return err
		}

		if vmImage, found := FindVmImage(imageList.VMImages, "", b.config.OSImageLabel, b.config.Location); found {
			state.Put(constants.OSImageName, vmImage.Name)
			state.Put(constants.IsOSImage, false)
			return nil
		} else {
			return fmt.Errorf("Can't find VM or OS image '%s' Located at '%s'", b.config.OSImageLabel, b.config.Location)
		}
	}
}
Ejemplo n.º 29
0
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
	steps := []multistep.Step{
		&common.StepConnectSSH{
			SSHAddress:     SSHAddress(b.config.Host, b.config.Port),
			SSHConfig:      SSHConfig(b.config.SSHUsername, b.config.SSHPassword, b.config.SSHPrivateKeyFile),
			SSHWaitTimeout: 1 * time.Minute,
		},
		&common.StepProvision{},
	}

	// Setup the state bag and initial state for the steps
	state := new(multistep.BasicStateBag)
	state.Put("config", b.config)
	state.Put("hook", hook)
	state.Put("ui", ui)

	// Run!
	if b.config.PackerDebug {
		b.runner = &multistep.DebugRunner{
			Steps:   steps,
			PauseFn: common.MultistepDebugFn(ui),
		}
	} else {
		b.runner = &multistep.BasicRunner{Steps: steps}
	}

	b.runner.Run(state)

	// If there was an error, return that
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// No errors, must've worked
	artifact := &NullArtifact{}
	return artifact, nil
}
Ejemplo n.º 30
0
func (p *Processor) process(ctx gocontext.Context, buildJob Job) {
	state := new(multistep.BasicStateBag)
	state.Put("hostname", p.fullHostname())
	state.Put("buildJob", buildJob)
	state.Put("ctx", ctx)

	logTimeout := p.logTimeout
	if buildJob.Payload().Timeouts.LogSilence != 0 {
		logTimeout = time.Duration(buildJob.Payload().Timeouts.LogSilence) * time.Second
	}

	steps := []multistep.Step{
		&stepSubscribeCancellation{
			canceller: p.canceller,
		},
		&stepGenerateScript{
			generator: p.generator,
		},
		&stepSendReceived{},
		&stepStartInstance{
			provider:     p.provider,
			startTimeout: p.startupTimeout,
		},
		&stepUploadScript{
			uploadTimeout: p.scriptUploadTimeout,
		},
		&stepUpdateState{},
		&stepOpenLogWriter{
			logTimeout:   logTimeout,
			maxLogLength: 4500000,
		},
		&stepRunScript{
			logTimeout:               logTimeout,
			hardTimeout:              p.hardTimeout,
			skipShutdownOnLogTimeout: p.SkipShutdownOnLogTimeout,
		},
	}

	runner := &multistep.BasicRunner{Steps: steps}

	context.LoggerFromContext(ctx).Info("starting job")
	runner.Run(state)
	context.LoggerFromContext(ctx).Info("finished job")
	p.ProcessedCount++
}