當前位置: 首頁>>代碼示例>>Golang>>正文


Golang multistep.StateBag類代碼示例

本文整理匯總了Golang中github.com/mitchellh/multistep.StateBag的典型用法代碼示例。如果您正苦於以下問題:Golang StateBag類的具體用法?Golang StateBag怎麽用?Golang StateBag使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了StateBag類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: CleanupFunc

func (s *StepMountExtra) CleanupFunc(state multistep.StateBag) error {
	if s.mounts == nil {
		return nil
	}

	wrappedCommand := state.Get("wrappedCommand").(CommandWrapper)
	for len(s.mounts) > 0 {
		var path string
		lastIndex := len(s.mounts) - 1
		path, s.mounts = s.mounts[lastIndex], s.mounts[:lastIndex]
		unmountCommand, err := wrappedCommand(fmt.Sprintf("umount %s", path))
		if err != nil {
			return fmt.Errorf("Error creating unmount command: %s", err)
		}

		stderr := new(bytes.Buffer)
		cmd := ShellCommand(unmountCommand)
		cmd.Stderr = stderr
		if err := cmd.Run(); err != nil {
			return fmt.Errorf(
				"Error unmounting device: %s\nStderr: %s", err, stderr.String())
		}
	}

	s.mounts = nil
	return nil
}
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:27,代碼來源:step_mount_extra.go

示例2: Cleanup

func (s *StepSecurityGroup) Cleanup(state multistep.StateBag) {
	if s.createdGroupId == "" {
		return
	}

	ec2conn := state.Get("ec2").(*ec2.EC2)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Deleting temporary security group...")

	var err error
	for i := 0; i < 5; i++ {
		_, err = ec2conn.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{GroupId: &s.createdGroupId})
		if err == nil {
			break
		}

		log.Printf("Error deleting security group: %s", err)
		time.Sleep(5 * time.Second)
	}

	if err != nil {
		ui.Error(fmt.Sprintf(
			"Error cleaning up security group. Please delete the group manually: %s", s.createdGroupId))
	}
}
開發者ID:c12simple,項目名稱:packer,代碼行數:26,代碼來源:step_security_group.go

示例3: Run

func (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction {
	dir := state.Get("dir").(OutputDir)
	ui := state.Get("ui").(packer.Ui)

	exists, err := dir.DirExists()
	if err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	if exists {
		if s.Force {
			ui.Say("Deleting previous output directory...")
			dir.RemoveAll()
		} else {
			state.Put("error", fmt.Errorf(
				"Output directory '%s' already exists.", dir.String()))
			return multistep.ActionHalt
		}
	}

	if err := dir.MkdirAll(); err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	s.success = true
	return multistep.ActionContinue
}
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:29,代碼來源:step_output_dir.go

示例4: Cleanup

// Cleanup destroys the GCE instance created during the image creation process.
func (s *StepCreateInstance) Cleanup(state multistep.StateBag) {
	if s.instanceName == "" {
		return
	}

	config := state.Get("config").(*Config)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Deleting instance...")
	errCh, err := driver.DeleteInstance(config.Zone, s.instanceName)
	if err == nil {
		select {
		case err = <-errCh:
		case <-time.After(config.stateTimeout):
			err = errors.New("time out while waiting for instance to delete")
		}
	}

	if err != nil {
		ui.Error(fmt.Sprintf(
			"Error deleting instance. Please delete it manually.\n\n"+
				"Name: %s\n"+
				"Error: %s", s.instanceName, err))
	}

	s.instanceName = ""
	return
}
開發者ID:jaags,項目名稱:packer,代碼行數:30,代碼來源:step_create_instance.go

示例5: Cleanup

func (s *StepMountDvdDrive) Cleanup(state multistep.StateBag) {
	if s.path == "" {
		return
	}

	errorMsg := "Error unmounting dvd drive: %s"

	vmName := state.Get("vmName").(string)
	driver := state.Get("driver").(hypervcommon.Driver)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Unmounting dvd drive...")

	var err error = nil

	var blockBuffer bytes.Buffer
	blockBuffer.WriteString("Invoke-Command -scriptblock {Set-VMDvdDrive -VMName '")
	blockBuffer.WriteString(vmName)
	blockBuffer.WriteString("' -Path $null}")

	err = driver.HypervManage(blockBuffer.String())

	if err != nil {
		ui.Error(fmt.Sprintf(errorMsg, err))
	}
}
開發者ID:jamesleech,項目名稱:packer,代碼行數:26,代碼來源:step_mount_dvddrive.go

示例6: Run

func (s *StepProvision) Run(state multistep.StateBag) multistep.StepAction {
	comm := s.Comm
	if comm == nil {
		comm = state.Get("communicator").(packer.Communicator)
	}

	hook := state.Get("hook").(packer.Hook)
	ui := state.Get("ui").(packer.Ui)

	// Run the provisioner in a goroutine so we can continually check
	// for cancellations...
	log.Println("Running the provision hook")
	errCh := make(chan error, 1)
	go func() {
		errCh <- hook.Run(packer.HookProvision, ui, comm, nil)
	}()

	for {
		select {
		case err := <-errCh:
			if err != nil {
				state.Put("error", err)
				return multistep.ActionHalt
			}

			return multistep.ActionContinue
		case <-time.After(1 * time.Second):
			if _, ok := state.GetOk(multistep.StateCancelled); ok {
				log.Println("Cancelling provisioning due to interrupt...")
				hook.Cancel()
				return multistep.ActionHalt
			}
		}
	}
}
開發者ID:JNPRAutomate,項目名稱:packer,代碼行數:35,代碼來源:step_provision.go

示例7: cancelCallback

func cancelCallback(state multistep.StateBag) bool {
	cancel := false
	if _, ok := state.GetOk(multistep.StateCancelled); ok {
		cancel = true
	}
	return cancel
}
開發者ID:englishm,項目名稱:packer,代碼行數:7,代碼來源:step_run.go

示例8: Run

func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)
	c := state.Get("config").(*Config)

	ui.Say("Creating ProfitBricks snapshot...")

	profitbricks.SetAuth(c.PBUsername, c.PBPassword)

	dcId := state.Get("datacenter_id").(string)
	volumeId := state.Get("volume_id").(string)

	snapshot := profitbricks.CreateSnapshot(dcId, volumeId, c.SnapshotName)

	state.Put("snapshotname", c.SnapshotName)

	if snapshot.StatusCode > 299 {
		var restError RestError
		json.Unmarshal([]byte(snapshot.Response), &restError)
		if len(restError.Messages) > 0 {
			ui.Error(restError.Messages[0].Message)
		} else {
			ui.Error(snapshot.Response)
		}

		return multistep.ActionHalt
	}

	s.waitTillProvisioned(snapshot.Headers.Get("Location"), *c)

	return multistep.ActionContinue
}
開發者ID:arizvisa,項目名稱:packer,代碼行數:31,代碼來源:step_take_snapshot.go

示例9: sshConfig

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(*Config)
	var privateKey string

	var auth []gossh.AuthMethod

	if config.Comm.SSHPassword != "" {
		auth = []gossh.AuthMethod{
			gossh.Password(config.Comm.SSHPassword),
			gossh.KeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
		}
	}

	if config.Comm.SSHPrivateKey != "" {
		if priv, ok := state.GetOk("privateKey"); ok {
			privateKey = priv.(string)
		}
		signer, err := gossh.ParsePrivateKey([]byte(privateKey))
		if err != nil {
			return nil, fmt.Errorf("Error setting up SSH config: %s", err)
		}
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}
	return &gossh.ClientConfig{
		User: config.Comm.SSHUsername,
		Auth: auth,
	}, nil
}
開發者ID:arizvisa,項目名稱:packer,代碼行數:33,代碼來源:ssh.go

示例10: Run

func (s *stepStopInstance) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(*ec2.EC2)
	instance := state.Get("instance").(*ec2.Instance)
	ui := state.Get("ui").(packer.Ui)

	// Stop the instance so we can create an AMI from it
	ui.Say("Stopping the source instance...")
	_, err := ec2conn.StopInstances(instance.InstanceId)
	if err != nil {
		err := fmt.Errorf("Error stopping instance: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Wait for the instance to actual stop
	ui.Say("Waiting for the instance to stop...")
	stateChange := awscommon.StateChangeConf{
		Conn:      ec2conn,
		Pending:   []string{"running", "stopping"},
		Target:    "stopped",
		Refresh:   awscommon.InstanceStateRefreshFunc(ec2conn, instance),
		StepState: state,
	}
	_, err = awscommon.WaitForState(&stateChange)
	if err != nil {
		err := fmt.Errorf("Error waiting for instance to stop: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	return multistep.ActionContinue
}
開發者ID:englishm,項目名稱:packer,代碼行數:34,代碼來源:step_stop_instance.go

示例11: Run

func (s *StepGetIPAddress) Run(state multistep.StateBag) multistep.StepAction {
	s.say("Getting the VM's IP address ...")

	var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
	var ipAddressName = state.Get(constants.ArmPublicIPAddressName).(string)
	var nicName = state.Get(constants.ArmNicName).(string)

	s.say(fmt.Sprintf(" -> ResourceGroupName   : '%s'", resourceGroupName))
	s.say(fmt.Sprintf(" -> PublicIPAddressName : '%s'", ipAddressName))
	s.say(fmt.Sprintf(" -> NicName             : '%s'", nicName))
	s.say(fmt.Sprintf(" -> Network Connection  : '%s'", EndpointCommunicationText[s.endpoint]))

	address, err := s.get(resourceGroupName, ipAddressName, nicName)
	if err != nil {
		state.Put(constants.Error, err)
		s.error(err)

		return multistep.ActionHalt
	}

	state.Put(constants.SSHHost, address)
	s.say(fmt.Sprintf(" -> IP Address          : '%s'", address))

	return multistep.ActionContinue
}
開發者ID:curiositycasualty,項目名稱:packer,代碼行數:25,代碼來源:step_get_ip_address.go

示例12: Cleanup

func (s *StepKeyPair) Cleanup(state multistep.StateBag) {
	// If we used an SSH private key file, do not go about deleting
	// keypairs
	if s.PrivateKeyFile != "" {
		return
	}
	// If no key name is set, then we never created it, so just return
	if s.keyName == "" {
		return
	}

	config := state.Get("config").(Config)
	ui := state.Get("ui").(packer.Ui)

	// We need the v2 compute client
	computeClient, err := config.computeV2Client()
	if err != nil {
		ui.Error(fmt.Sprintf(
			"Error cleaning up keypair. Please delete the key manually: %s", s.keyName))
		return
	}

	ui.Say("Deleting temporary keypair...")
	err = keypairs.Delete(computeClient, s.keyName).ExtractErr()
	if err != nil {
		ui.Error(fmt.Sprintf(
			"Error cleaning up keypair. Please delete the key manually: %s", s.keyName))
	}
}
開發者ID:rodm,項目名稱:packer,代碼行數:29,代碼來源:step_key_pair.go

示例13: Run

// Run adds a virtual CD-ROM device to the VM and attaches Parallels Tools ISO image.
// If ISO image is not specified, then this step will be skipped.
func (s *StepAttachParallelsTools) Run(state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	// If we're not attaching the guest additions then just return
	if s.ParallelsToolsMode != ParallelsToolsModeAttach {
		log.Println("Not attaching parallels tools since we're uploading.")
		return multistep.ActionContinue
	}

	// Get the Paralells Tools path on the host machine
	parallelsToolsPath := state.Get("parallels_tools_path").(string)

	// Attach the guest additions to the computer
	ui.Say("Attaching Parallels Tools ISO to the new CD/DVD drive...")

	cdrom, err := driver.DeviceAddCDROM(vmName, parallelsToolsPath)

	if err != nil {
		err = fmt.Errorf("Error attaching Parallels Tools ISO: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Track the device name so that we can can delete later
	s.cdromDevice = cdrom

	return multistep.ActionContinue
}
開發者ID:dave2,項目名稱:packer,代碼行數:33,代碼來源:step_attach_parallels_tools.go

示例14: Run

func (s *StepCopyFiles) Run(state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(*Config)
	mountPath := state.Get("mount_path").(string)
	ui := state.Get("ui").(packer.Ui)

	s.files = make([]string, 0, len(config.CopyFiles))
	if len(config.CopyFiles) > 0 {
		ui.Say("Copying files from host to chroot...")
		for _, path := range config.CopyFiles {
			ui.Message(path)
			chrootPath := filepath.Join(mountPath, path)
			log.Printf("Copying '%s' to '%s'", path, chrootPath)

			if err := s.copySingle(chrootPath, path); err != nil {
				err := fmt.Errorf("Error copying file: %s", err)
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			}

			s.files = append(s.files, chrootPath)
		}
	}

	state.Put("copy_files_cleanup", s)
	return multistep.ActionContinue
}
開發者ID:kirikaza,項目名稱:packer,代碼行數:27,代碼來源:step_copy_files.go

示例15: Run

func (s *StepDownload) Run(state multistep.StateBag) multistep.StepAction {
	cache := state.Get("cache").(packer.Cache)
	ui := state.Get("ui").(packer.Ui)

	var checksum []byte
	if s.Checksum != "" {
		var err error
		checksum, err = hex.DecodeString(s.Checksum)
		if err != nil {
			state.Put("error", fmt.Errorf("Error parsing checksum: %s", err))
			return multistep.ActionHalt
		}
	}

	ui.Say(fmt.Sprintf("Downloading or copying %s", s.Description))

	var finalPath string
	for _, url := range s.Url {
		ui.Message(fmt.Sprintf("Downloading or copying: %s", url))

		targetPath := s.TargetPath
		if targetPath == "" {
			log.Printf("Acquiring lock to download: %s", url)
			targetPath = cache.Lock(url)
			defer cache.Unlock(url)
		}

		config := &DownloadConfig{
			Url:        url,
			TargetPath: targetPath,
			CopyFile:   false,
			Hash:       HashForType(s.ChecksumType),
			Checksum:   checksum,
		}

		path, err, retry := s.download(config, state)
		if err != nil {
			ui.Message(fmt.Sprintf("Error downloading: %s", err))
		}

		if !retry {
			return multistep.ActionHalt
		}

		if err == nil {
			finalPath = path
			break
		}
	}

	if finalPath == "" {
		err := fmt.Errorf("%s download failed.", s.Description)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put(s.ResultKey, finalPath)
	return multistep.ActionContinue
}
開發者ID:EdevMosaic,項目名稱:packer,代碼行數:60,代碼來源:step_download.go


注:本文中的github.com/mitchellh/multistep.StateBag類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。