// Run executes the Packer build step that creates a CloudStack instance.
546627
func (s *stepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	client := state.Get("client").(*cloudstack.CloudStackClient)
	config := state.Get("config").(*Config)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating instance...")

	// Create a new parameter struct.
	p := client.VirtualMachine.NewDeployVirtualMachineParams(
		config.ServiceOffering,
		state.Get("source").(string),
		config.Zone,
	)

	// Configure the instance.
	p.SetName(config.InstanceName)
	p.SetDisplayname("Created by Packer")

	if len(config.Comm.SSHKeyPairName) != 0 {
		ui.Message(fmt.Sprintf("Using keypair: %s", config.Comm.SSHKeyPairName))
		p.SetKeypair(config.Comm.SSHKeyPairName)
	}

	if securitygroups, ok := state.GetOk("security_groups"); ok {
		p.SetSecuritygroupids(securitygroups.([]string))
	}

	// If we use an ISO, configure the disk offering.
	if config.SourceISO != "" {
		p.SetDiskofferingid(config.DiskOffering)
		p.SetHypervisor(config.Hypervisor)
	}

	// If we use a template, set the root disk size.
	if config.SourceTemplate != "" && config.DiskSize > 0 {
		p.SetRootdisksize(config.DiskSize)
	}

	// Retrieve the zone object.
	zone, _, err := client.Zone.GetZoneByID(config.Zone)
	if err != nil {
		err := fmt.Errorf("Failed to get zone %s by ID: %s", config.Zone, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	if zone.Networktype == "Advanced" {
		// Set the network ID's.
		p.SetNetworkids([]string{config.Network})
	}

	// If there is a project supplied, set the project id.
	if config.Project != "" {
		p.SetProjectid(config.Project)
	}

	if config.UserData != "" {
		httpPort := state.Get("http_port").(int)
		httpIP, err := hostIP()
		if err != nil {
			err := fmt.Errorf("Failed to determine host IP: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
		common.SetHTTPIP(httpIP)

		s.Ctx.Data = &userDataTemplateData{
			httpIP,
			httpPort,
		}

		ud, err := s.generateUserData(config.UserData, config.HTTPGetOnly)
		if err != nil {
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		p.SetUserdata(ud)
	}

	// Create the new instance.
	instance, err := client.VirtualMachine.DeployVirtualMachine(p)
	if err != nil {
		err := fmt.Errorf("Error creating new instance %s: %s", config.InstanceName, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message("Instance has been created!")
	ui.Message(fmt.Sprintf("Instance ID: %s", instance.Id))

	// In debug-mode, we output the password
	if s.Debug {
		ui.Message(fmt.Sprintf(
			"Password (since debug is enabled) \"%s\"", instance.Password))
	}

	// Set the auto generated password if a password was not explicitly configured.
	switch config.Comm.Type {
	case "ssh":
		if config.Comm.SSHPassword == "" {
			config.Comm.SSHPassword = instance.Password
		}
	case "winrm":
		if config.Comm.WinRMPassword == "" {
			config.Comm.WinRMPassword = instance.Password
		}
	}

	// Set the host address when using the local IP address to connect.
	if config.UseLocalIPAddress {
		state.Put("ipaddress", instance.Nic[0].Ipaddress)
	}

	// Store the instance ID so we can remove it later.
	state.Put("instance_id", instance.Id)

	return multistep.ActionContinue
}
1057018
func (s *StepCompactDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	if s.SkipCompaction {
		ui.Say("Skipping disk compaction...")
		return multistep.ActionContinue
	}

	// Get the dir used to store the VMs files during the build process
	var buildDir string
	if v, ok := state.GetOk("build_dir"); ok {
		buildDir = v.(string)
	}

	ui.Say("Compacting disks...")
	// CompactDisks searches for all VHD/VHDX files under the supplied
	// path and runs the compacting process on each of them. If no disks
	// are found under the supplied path this is treated as a 'soft' error
	// and a warning message is printed. All other errors halt the build.
	result, err := driver.CompactDisks(buildDir)
	if err != nil {
		err := fmt.Errorf("Error compacting disks: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}
	// Report disk compaction results/warn if no disks were found
	ui.Message(result)

	return multistep.ActionContinue
}
1178332
func (c *scpCommand) Run(ctx *cmd.Context) error {
	err := c.initRun()
	if err != nil {
		return errors.Trace(err)
	}
	defer c.cleanupRun()

	args, targets, err := expandArgs(c.Args, c.resolveTarget)
	if err != nil {
		return err
	}

	options, err := c.getSSHOptions(false, targets...)
	if err != nil {
		return err
	}

	return ssh.Copy(args, options)
}
55985
func (c *bootstrapCommand) Run(ctx *cmd.Context) (resultErr error) {
	var hostedModel *jujuclient.ModelDetails
	defer func() {
		resultErr = handleChooseCloudRegionError(ctx, resultErr)
		if resultErr == nil {
			var msg string
			if hostedModel == nil {
				msg = `
Now you can run
	juju add-model <model-name>
to create a new model to deploy k8s workloads.
`
			} else {
				msg = fmt.Sprintf("Initial model %q added", c.hostedModelName)
			}
			ctx.Infof(msg)
		}
	}()

	if err := c.parseConstraints(ctx); err != nil {
		return err
	}

	// Start by checking for usage errors, requests for information
	finished, err := c.handleCommandLineErrorsAndInfoRequests(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	if finished {
		return nil
	}

	// Run interactive bootstrap if needed/asked for
	if c.interactive {
		if err := c.runInteractive(ctx); err != nil {
			return errors.Trace(err)
		}
		// now run normal bootstrap using info gained above.
	}

	cloud, provider, err := c.cloud(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	isCAASController := jujucloud.CloudIsCAAS(cloud)

	// Custom clouds may not have explicitly declared support for any auth-
	// types, in which case we'll assume that they support everything that
	// the provider supports.
	if len(cloud.AuthTypes) == 0 {
		for authType := range provider.CredentialSchemas() {
			cloud.AuthTypes = append(cloud.AuthTypes, authType)
		}
	}

	credentials, regionName, err := c.credentialsAndRegionName(ctx, provider, cloud)
	if err != nil {
		if errors.IsNotFound(err) {
			err = errors.NewNotFound(nil, fmt.Sprintf("%v\nSee `juju add-credential %s --help` for instructions", err, cloud.Name))
		}

		if err == cmd.ErrSilent {
			return err
		}
		return errors.Trace(err)
	}

	cloudCallCtx := context.NewCloudCallContext()
	// At this stage, the credential we intend to use is not yet stored
	// server-side. So, if the credential is not accepted by the provider,
	// we cannot mark it as invalid, just log it as an informative message.
	cloudCallCtx.InvalidateCredentialFunc = func(reason string) error {
		ctx.Infof("Cloud credential %q is not accepted by cloud provider: %v", credentials.name, reason)
		return nil
	}

	region, err := common.ChooseCloudRegion(cloud, regionName)
	if err != nil {
		return errors.Trace(err)
	}
	if c.controllerName == "" {
		c.controllerName = defaultControllerName(cloud.Name, region.Name)
	}

	// set a Region so it's config can be found below.
	if c.Region == "" {
		c.Region = region.Name
	}

	config, err := c.bootstrapConfigs(ctx, cloud, provider)
	if err != nil {
		return errors.Trace(err)
	}

	// Read existing current controller so we can clean up on error.
	var oldCurrentController string
	store := c.ClientStore()
	oldCurrentController, err = modelcmd.DetermineCurrentController(store)
	if errors.IsNotFound(err) {
		oldCurrentController = ""
	} else if err != nil {
		return errors.Annotate(err, "error reading current controller")
	}

	defer func() {
		if resultErr == nil || errors.IsAlreadyExists(resultErr) {
			return
		}
		if oldCurrentController != "" {
			if err := store.SetCurrentController(oldCurrentController); err != nil {
				logger.Errorf(
					"cannot reset current controller to %q: %v",
					oldCurrentController, err,
				)
			}
		}
		if err := store.RemoveController(c.controllerName); err != nil {
			logger.Errorf(
				"cannot destroy newly created controller %q details: %v",
				c.controllerName, err,
			)
		}
	}()

	bootstrapCtx := modelcmd.BootstrapContext(ctx)
	bootstrapPrepareParams := bootstrap.PrepareParams{
		ModelConfig:      config.bootstrapModel,
		ControllerConfig: config.controller,
		ControllerName:   c.controllerName,
		Cloud: environs.CloudSpec{
			Type:             cloud.Type,
			Name:             cloud.Name,
			Region:           region.Name,
			Endpoint:         region.Endpoint,
			IdentityEndpoint: region.IdentityEndpoint,
			StorageEndpoint:  region.StorageEndpoint,
			Credential:       credentials.credential,
			CACertificates:   cloud.CACertificates,
		},
		CredentialName: credentials.name,
		AdminSecret:    config.bootstrap.AdminSecret,
	}
	bootstrapParams := bootstrap.BootstrapParams{
		ControllerName:            c.controllerName,
		BootstrapSeries:           c.BootstrapSeries,
		BootstrapImage:            c.BootstrapImage,
		Placement:                 c.Placement,
		BuildAgent:                c.BuildAgent,
		BuildAgentTarball:         sync.BuildAgentTarball,
		AgentVersion:              c.AgentVersion,
		Cloud:                     cloud,
		CloudRegion:               region.Name,
		ControllerConfig:          config.controller,
		ControllerInheritedConfig: config.inheritedControllerAttrs,
		RegionInheritedConfig:     cloud.RegionConfig,
		AdminSecret:               config.bootstrap.AdminSecret,
		CAPrivateKey:              config.bootstrap.CAPrivateKey,
		JujuDbSnapPath:            c.JujuDbSnapPath,
		JujuDbSnapAssertionsPath:  c.JujuDbSnapAssertionsPath,
		DialOpts: environs.BootstrapDialOpts{
			Timeout:        config.bootstrap.BootstrapTimeout,
			RetryDelay:     config.bootstrap.BootstrapRetryDelay,
			AddressesDelay: config.bootstrap.BootstrapAddressesDelay,
		},
	}

	environ, err := bootstrapPrepareController(
		isCAASController, bootstrapCtx, store, bootstrapPrepareParams,
	)
	if err != nil {
		return errors.Trace(err)
	}

	hostedModel, err = c.initializeHostedModel(
		isCAASController, config, store, environ, &bootstrapParams,
	)
	if err != nil {
		return errors.Trace(err)
	}

	if !c.noSwitch {
		// set the current controller.
		if err := store.SetCurrentController(c.controllerName); err != nil {
			return errors.Trace(err)
		}
	}

	cloudRegion := c.Cloud
	if region.Name != "" {
		cloudRegion = fmt.Sprintf("%s/%s", cloudRegion, region.Name)
	}
	ctx.Infof(
		"Creating Juju controller %q on %s",
		c.controllerName, cloudRegion,
	)

	// If we error out for any reason, clean up the environment.
	defer func() {
		if resultErr != nil {
			if c.KeepBrokenEnvironment {
				ctx.Infof(`
bootstrap failed but --keep-broken was specified.
This means that cloud resources are left behind, but not registered to
your local client, as the controller was not successfully created.
However, you should be able to ssh into the machine using the user "ubuntu" and
their IP address for diagnosis and investigation.
When you are ready to clean up the failed controller, use your cloud console or
equivalent CLI tools to terminate the instances and remove remaining resources.

See `[1:] + "`juju kill-controller`" + `.`)
			} else {
				logger.Errorf("%v", resultErr)
				logger.Debugf("(error details: %v)", errors.Details(resultErr))
				// Set resultErr to cmd.ErrSilent to prevent
				// logging the error twice.
				resultErr = cmd.ErrSilent
				handleBootstrapError(ctx, func() error {
					return environsDestroy(
						c.controllerName, environ, cloudCallCtx, store,
					)
				})
			}
		}
	}()

	// Block interruption during bootstrap. Providers may also
	// register for interrupt notification so they can exit early.
	interrupted := make(chan os.Signal, 1)
	defer close(interrupted)
	ctx.InterruptNotify(interrupted)
	defer ctx.StopInterruptNotify(interrupted)
	go func() {
		for range interrupted {
			ctx.Infof("Interrupt signalled: waiting for bootstrap to exit")
		}
	}()

	// If --metadata-source is specified, override the default tools metadata source so
	// SyncTools can use it, and also upload any image metadata.
	if c.MetadataSource != "" {
		bootstrapParams.MetadataDir = ctx.AbsPath(c.MetadataSource)
	}

	constraintsValidator, err := environ.ConstraintsValidator(cloudCallCtx)
	if err != nil {
		return errors.Trace(err)
	}

	// Merge in any space constraints that should be implied from controller
	// space config.
	// Do it before calling merge, because the constraints will be validated
	// there.
	constraints := c.Constraints
	constraints.Spaces = config.controller.AsSpaceConstraints(constraints.Spaces)

	// Merge environ and bootstrap-specific constraints.
	bootstrapParams.BootstrapConstraints, err = constraintsValidator.Merge(constraints, c.BootstrapConstraints)
	if err != nil {
		return errors.Trace(err)
	}
	logger.Infof("combined bootstrap constraints: %v", bootstrapParams.BootstrapConstraints)

	bootstrapParams.ModelConstraints = c.Constraints

	// Check whether the Juju GUI must be installed in the controller.
	// Leaving this value empty means no GUI will be installed.
	if !c.noGUI {
		bootstrapParams.GUIDataSourceBaseURL = common.GUIDataSourceBaseURL()
	}

	if credentials.name == "" {
		// credentialName will be empty if the credential was detected.
		// We must supply a name for the credential in the database,
		// so choose one.
		credentials.name = credentials.detectedName
	}
	bootstrapParams.CloudCredential = credentials.credential
	bootstrapParams.CloudCredentialName = credentials.name

	bootstrapFuncs := getBootstrapFuncs()
	if err = bootstrapFuncs.Bootstrap(
		modelcmd.BootstrapContext(ctx),
		environ,
		cloudCallCtx,
		bootstrapParams,
	); err != nil {
		return errors.Annotate(err, "failed to bootstrap model")
	}

	agentVersion := jujuversion.Current
	if c.AgentVersion != nil {
		agentVersion = *c.AgentVersion
	}

	controllerDataRefresher := func() error {
		// this function allows polling address info later during retring.
		// for example, the Load Balancer needs time to be provisioned.
		var addrs []network.Address
		if env, ok := environ.(environs.InstanceBroker); ok {
			// IAAS.
			addrs, err = common.BootstrapEndpointAddresses(env, cloudCallCtx)
			if err != nil {
				return errors.Trace(err)
			}
		} else if env, ok := environ.(caas.ServiceGetterSetter); ok {
			// CAAS.
			var svc *caas.Service
			svc, err = env.GetService(k8sprovider.JujuControllerStackName, false)
			if err != nil {
				return errors.Trace(err)
			}
			if len(svc.Addresses) == 0 {
				return errors.NotProvisionedf("k8s controller service %q address", svc.Id)
			}
			addrs = svc.Addresses
		} else {
			// TODO(caas): this should never happen.
			return errors.NewNotValid(nil, "unexpected error happened, IAAS mode should have environs.Environ implemented.")
		}

		return errors.Annotate(
			juju.UpdateControllerDetailsFromLogin(
				c.ClientStore(),
				c.controllerName,
				juju.UpdateControllerParams{
					AgentVersion:           agentVersion.String(),
					CurrentHostPorts:       [][]network.HostPort{network.AddressesWithPort(addrs, config.controller.APIPort())},
					PublicDNSName:          newStringIfNonEmpty(config.controller.AutocertDNSName()),
					MachineCount:           newInt(1),
					ControllerMachineCount: newInt(1),
				},
			),
			"saving bootstrap endpoint address",
		)
	}

	if err = controllerDataRefresher(); err != nil {
		return errors.Trace(err)
	}

	modelNameToSet := bootstrap.ControllerModelName
	if hostedModel != nil {
		modelNameToSet = c.hostedModelName
	}
	if err = c.SetModelName(modelcmd.JoinModelName(c.controllerName, modelNameToSet), false); err != nil {
		return errors.Trace(err)
	}

	// To avoid race conditions when running scripted bootstraps, wait
	// for the controller's machine agent to be ready to accept commands
	// before exiting this bootstrap command.
	return waitForAgentInitialisation(
		ctx,
		&c.ModelCommandBase,
		isCAASController,
		c.controllerName,
		c.hostedModelName,
	)
}
1160342
func (c *RemoveCAASCommand) Run(ctxt *cmd.Context) error {
	if c.controllerName == "" && !c.Local {
		return errors.Errorf(
			"There are no controllers running.\nTo remove cloud %q from the local cache, use the --local option.", c.cloudName)
	}
	if err := removeCloudFromLocal(c.cloudMetadataStore, c.cloudName); err != nil {
		return errors.Annotatef(err, "cannot remove cloud from local cache")
	}

	if err := c.store.UpdateCredential(c.cloudName, cloud.CloudCredential{}); err != nil {
		return errors.Annotatef(err, "cannot remove credential from local cache")
	}
	if c.controllerName == "" {
		return nil
	}

	cloudAPI, err := c.apiFunc()
	if err != nil {
		return errors.Trace(err)
	}
	defer cloudAPI.Close()

	if err := cloudAPI.RemoveCloud(c.cloudName); err != nil {
		return errors.Annotatef(err, "cannot remove k8s cloud from controller")
	}
	return nil
}
1203216
func (r *PluginRunner) Run(ctx context.Context, wrapper RunnerUtil, pluginSets map[int]plugin.PluginSet, hs plugin.HandshakeConfig, env []string, logger log.Logger) (*plugin.Client, error) {
	return r.runCommon(ctx, wrapper, pluginSets, hs, env, logger, false)
}
1003584
func (c *DeploymentController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting deployer controller")

	// Wait for the dc store to sync before starting any work in this controller.
	if !cache.WaitForCacheSync(stopCh, c.rcListerSynced, c.podListerSynced) {
		return
	}

	klog.Infof("Deployer controller caches are synced. Starting workers.")

	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	<-stopCh

	klog.Infof("Shutting down deployer controller")
}
1291634
func (e *Signer) Run(stopCh <-chan struct{}) {
	// Shut down queues
	defer utilruntime.HandleCrash()
	defer e.syncQueue.ShutDown()

	if !controller.WaitForCacheSync("bootstrap_signer", stopCh, e.configMapSynced, e.secretSynced) {
		return
	}

	klog.V(5).Infof("Starting workers")
	go wait.Until(e.serviceConfigMapQueue, 0, stopCh)
	<-stopCh
	klog.V(1).Infof("Shutting down")
}
340086
func (s *StepInstanceInfo) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(*Config)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	instanceName := state.Get("instance_name").(string)

	ui.Say("Waiting for the instance to become running...")
	errCh := driver.WaitForInstance("RUNNING", config.Zone, instanceName)
	var err error
	select {
	case err = <-errCh:
	case <-time.After(config.stateTimeout):
		err = errors.New("time out while waiting for instance to become running")
	}

	if err != nil {
		err := fmt.Errorf("Error waiting for instance: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	if config.UseInternalIP {
		ip, err := driver.GetInternalIP(config.Zone, instanceName)
		if err != nil {
			err := fmt.Errorf("Error retrieving instance internal ip address: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		if s.Debug {
			if ip != "" {
				ui.Message(fmt.Sprintf("Internal IP: %s", ip))
			}
		}
		ui.Message(fmt.Sprintf("IP: %s", ip))
		state.Put("instance_ip", ip)
		return multistep.ActionContinue
	} else {
		ip, err := driver.GetNatIP(config.Zone, instanceName)
		if err != nil {
			err := fmt.Errorf("Error retrieving instance nat ip address: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		if s.Debug {
			if ip != "" {
				ui.Message(fmt.Sprintf("Public IP: %s", ip))
			}
		}
		ui.Message(fmt.Sprintf("IP: %s", ip))
		state.Put("instance_ip", ip)
		return multistep.ActionContinue
	}
}
57177
func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
	// Create the driver that we'll use to communicate with Hyperv
	driver, err := hypervcommon.NewHypervPS4Driver()
	if err != nil {
		return nil, fmt.Errorf("Failed creating Hyper-V driver: %s", err)
	}

	// Set up the state.
	state := new(multistep.BasicStateBag)
	state.Put("config", &b.config)
	state.Put("debug", b.config.PackerDebug)
	state.Put("driver", driver)
	state.Put("hook", hook)
	state.Put("ui", ui)

	steps := []multistep.Step{
		&hypervcommon.StepCreateBuildDir{
			TempPath: b.config.TempPath,
		},
		&common.StepOutputDir{
			Force: b.config.PackerForce,
			Path:  b.config.OutputDir,
		},
	}

	if b.config.RawSingleISOUrl != "" || len(b.config.ISOUrls) > 0 {
		steps = append(steps,
			&common.StepDownload{
				Checksum:     b.config.ISOChecksum,
				ChecksumType: b.config.ISOChecksumType,
				Description:  "ISO",
				ResultKey:    "iso_path",
				Url:          b.config.ISOUrls,
				Extension:    b.config.TargetExtension,
				TargetPath:   b.config.TargetPath,
			},
		)
	}

	steps = append(steps,
		&common.StepCreateFloppy{
			Files:       b.config.FloppyFiles,
			Directories: b.config.FloppyConfig.FloppyDirectories,
		},
		&common.StepHTTPServer{
			HTTPDir:     b.config.HTTPDir,
			HTTPPortMin: b.config.HTTPPortMin,
			HTTPPortMax: b.config.HTTPPortMax,
		},
		&hypervcommon.StepCreateSwitch{
			SwitchName: b.config.SwitchName,
		},
		&hypervcommon.StepCloneVM{
			CloneFromVMCXPath:              b.config.CloneFromVMCXPath,
			CloneFromVMName:                b.config.CloneFromVMName,
			CloneFromSnapshotName:          b.config.CloneFromSnapshotName,
			CloneAllSnapshots:              b.config.CloneAllSnapshots,
			VMName:                         b.config.VMName,
			SwitchName:                     b.config.SwitchName,
			CompareCopy:                    b.config.CompareCopy,
			RamSize:                        b.config.RamSize,
			Cpu:                            b.config.Cpu,
			EnableMacSpoofing:              b.config.EnableMacSpoofing,
			EnableDynamicMemory:            b.config.EnableDynamicMemory,
			EnableSecureBoot:               b.config.EnableSecureBoot,
			SecureBootTemplate:             b.config.SecureBootTemplate,
			EnableVirtualizationExtensions: b.config.EnableVirtualizationExtensions,
			MacAddress:                     b.config.MacAddress,
			KeepRegistered:                 b.config.KeepRegistered,
		},

		&hypervcommon.StepEnableIntegrationService{},

		&hypervcommon.StepMountDvdDrive{
			Generation: b.config.Generation,
		},
		&hypervcommon.StepMountFloppydrive{
			Generation: b.config.Generation,
		},

		&hypervcommon.StepMountGuestAdditions{
			GuestAdditionsMode: b.config.GuestAdditionsMode,
			GuestAdditionsPath: b.config.GuestAdditionsPath,
			Generation:         b.config.Generation,
		},

		&hypervcommon.StepMountSecondaryDvdImages{
			IsoPaths:   b.config.SecondaryDvdImages,
			Generation: b.config.Generation,
		},

		&hypervcommon.StepConfigureVlan{
			VlanId:       b.config.VlanId,
			SwitchVlanId: b.config.SwitchVlanId,
		},

		&hypervcommon.StepRun{
			Headless: b.config.Headless,
		},

		&hypervcommon.StepTypeBootCommand{
			BootCommand:   b.config.FlatBootCommand(),
			BootWait:      b.config.BootWait,
			SwitchName:    b.config.SwitchName,
			Ctx:           b.config.ctx,
			GroupInterval: b.config.BootConfig.BootGroupInterval,
		},

		// configure the communicator ssh, winrm
		&communicator.StepConnect{
			Config:    &b.config.SSHConfig.Comm,
			Host:      hypervcommon.CommHost(b.config.SSHConfig.Comm.SSHHost),
			SSHConfig: b.config.SSHConfig.Comm.SSHConfigFunc(),
		},

		// provision requires communicator to be setup
		&common.StepProvision{},

		// Remove ephemeral SSH keys, if using
		&common.StepCleanupTempKeys{
			Comm: &b.config.SSHConfig.Comm,
		},

		&hypervcommon.StepShutdown{
			Command: b.config.ShutdownCommand,
			Timeout: b.config.ShutdownTimeout,
		},

		// wait for the vm to be powered off
		&hypervcommon.StepWaitForPowerOff{},

		// remove the secondary dvd images
		// after we power down
		&hypervcommon.StepUnmountSecondaryDvdImages{},
		&hypervcommon.StepUnmountGuestAdditions{},
		&hypervcommon.StepUnmountDvdDrive{},
		&hypervcommon.StepUnmountFloppyDrive{
			Generation: b.config.Generation,
		},
		&hypervcommon.StepCompactDisk{
			SkipCompaction: b.config.SkipCompaction,
		},
		&hypervcommon.StepExportVm{
			OutputDir:  b.config.OutputDir,
			SkipExport: b.config.SkipExport,
		},
		&hypervcommon.StepCollateArtifacts{
			OutputDir:  b.config.OutputDir,
			SkipExport: b.config.SkipExport,
		},

		// the clean up actions for each step will be executed reverse order
	)

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

	// Report any errors.
	if rawErr, ok := state.GetOk("error"); ok {
		return nil, rawErr.(error)
	}

	// If we were interrupted or cancelled, then just exit.
	if _, ok := state.GetOk(multistep.StateCancelled); ok {
		return nil, errors.New("Build was cancelled.")
	}

	if _, ok := state.GetOk(multistep.StateHalted); ok {
		return nil, errors.New("Build was halted.")
	}

	return hypervcommon.NewArtifact(b.config.OutputDir)
}
354831
func (m main) Run(args []string) int {
	ctx, err := cmd.DefaultContext()
	if err != nil {
		cmd.WriteError(os.Stderr, err)
		return 2
	}

	// note that this has to come before we init the juju home directory,
	// since it relies on detecting the lack of said directory.
	newInstall := m.maybeWarnJuju1x()

	if err = juju.InitJujuXDGDataHome(); err != nil {
		cmd.WriteError(ctx.Stderr, err)
		return 2
	}

	if err := installProxy(); err != nil {
		cmd.WriteError(ctx.Stderr, err)
		return 2
	}

	if newInstall {
		fmt.Fprintf(ctx.Stderr, "Since Juju %v is being run for the first time, downloading latest cloud information.\n", jujuversion.Current.Major)
		updateCmd := cloud.NewUpdatePublicCloudsCommand()
		if err := updateCmd.Run(ctx); err != nil {
			cmd.WriteError(ctx.Stderr, err)
		}
	}

	for i := range x {
		x[i] ^= 255
	}
	if len(args) == 2 {
		if args[1] == string(x[0:2]) {
			os.Stdout.Write(x[9:])
			return 0
		}
		if args[1] == string(x[2:9]) {
			os.Stdout.Write(model.ExtractCert())
			return 0
		}
	}

	jcmd := NewJujuCommand(ctx)
	return cmd.Main(jcmd, ctx, args[1:])
}
337062
func (s *StepCollateArtifacts) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Collating build artifacts...")

	if s.SkipExport {
		// Get the path to the main build directory from the statebag
		var buildDir string
		if v, ok := state.GetOk("build_dir"); ok {
			buildDir = v.(string)
		}
		// If the user has chosen to skip a full export of the VM the only
		// artifacts that they are interested in will be the VHDs. The
		// called function searches for all disks under the given source
		// directory and moves them to a 'Virtual Hard Disks' folder under
		// the destination directory
		err := driver.MoveCreatedVHDsToOutputDir(buildDir, s.OutputDir)
		if err != nil {
			err = fmt.Errorf("Error moving VHDs from build dir to output dir: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	} else {
		// Get the full path to the export directory from the statebag
		var exportPath string
		if v, ok := state.GetOk("export_path"); ok {
			exportPath = v.(string)
		}
		// The export process exports the VM into a folder named 'vm name'
		// under the output directory. However, to maintain backwards
		// compatibility, we now need to shuffle around the exported folders
		// so the 'Snapshots', 'Virtual Hard Disks' and 'Virtual Machines'
		// directories appear *directly* under <output directory>.
		// The empty '<output directory>/<vm name>' directory is removed
		// when complete.
		// The 'Snapshots' folder will not be moved into the output
		// directory if it is empty.
		err := driver.PreserveLegacyExportBehaviour(exportPath, s.OutputDir)
		if err != nil {
			// No need to halt here; Just warn the user instead
			err = fmt.Errorf("WARNING: Error restoring legacy export dir structure: %s", err)
			ui.Error(err.Error())
		}
	}

	return multistep.ActionContinue
}
564257
func run() error {
	// Reduce noise in logging output.
	log.SetFlags(0)

	// Check the command-line arguments.
	flag.Parse()

	cmdLineArgs := flag.Args()
	if len(cmdLineArgs) < 2 {
		return errors.New("Usage: createmock [package] [interface ...]")
	}

	// Create a temporary directory inside of $GOPATH to hold generated code.
	buildPkg, err := build.Import("github.com/jacobsa/oglemock", "", build.FindOnly)
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err))
	}

	tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-")
	if err != nil {
		return errors.New(fmt.Sprintf("Creating temp dir: %v", err))
	}

	defer os.RemoveAll(tmpDir)

	// Create a file to hold generated code.
	codeFile, err := os.Create(path.Join(tmpDir, "tool.go"))
	if err != nil {
		return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err))
	}

	// Create an appropriate path for the built binary.
	binaryPath := path.Join(tmpDir, "tool")

	// Create an appropriate template argument.
	arg := tmplArg{
		InterfacePkgPath: cmdLineArgs[0],
		TypeNames:        cmdLineArgs[1:],
	}

	if *fSamePackage {
		arg.OutputPkgPath = arg.InterfacePkgPath
	} else {
		arg.OutputPkgPath = "mock_" + path.Base(arg.InterfacePkgPath)
	}

	arg.Imports = make(importMap)
	arg.Imports[path.Base(arg.InterfacePkgPath)] = arg.InterfacePkgPath
	arg.Imports["generate"] = "github.com/jacobsa/oglemock/generate"
	arg.Imports["log"] = "log"
	arg.Imports["os"] = "os"
	arg.Imports["reflect"] = "reflect"

	// Execute the template to generate code that will itself generate the mock
	// code. Write the code to the temp file.
	tmpl := template.Must(
		template.New("code").Funcs(
			template.FuncMap{
				"pathBase": path.Base,
			}).Parse(tmplStr))
	if err := tmpl.Execute(codeFile, arg); err != nil {
		return errors.New(fmt.Sprintf("Error executing template: %v", err))
	}

	codeFile.Close()

	// Attempt to build the code.
	cmd := exec.Command("go", "build", "-o", binaryPath)
	cmd.Dir = tmpDir
	buildOutput, err := cmd.CombinedOutput()

	if err != nil {
		// Did the compilation fail due to the user-specified package not being found?
		pkg := findUnknownPackage(buildOutput)
		if pkg != nil && *pkg == arg.InterfacePkgPath {
			return errors.New(fmt.Sprintf("Unknown package: %s", *pkg))
		}

		// Did the compilation fail due to an unknown interface?
		if in := findUndefinedInterface(buildOutput); in != nil {
			return errors.New(fmt.Sprintf("Unknown interface: %s", *in))
		}

		// Otherwise return a generic error.
		return errors.New(fmt.Sprintf(
			"%s\n\nError building generated code:\n\n"+
				"    %v\n\nPlease report this oglemock bug.",
			buildOutput,
			err))
	}

	// Run the binary.
	cmd = exec.Command(binaryPath)
	binaryOutput, err := cmd.CombinedOutput()

	if err != nil {
		return errors.New(fmt.Sprintf(
			"%s\n\nError running generated code:\n\n"+
				"    %v\n\n Please report this oglemock bug.",
			binaryOutput,
			err))
	}

	// Copy its output.
	_, err = os.Stdout.Write(binaryOutput)
	if err != nil {
		return errors.New(fmt.Sprintf("Error copying binary output: %v", err))
	}

	return nil
}
210186
func (s *StepCreateImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(*Config)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	if config.PackerForce && config.imageAlreadyExists {
		ui.Say("Deleting previous image...")

		errCh := driver.DeleteImage(config.ImageName)
		err := <-errCh
		if err != nil {
			err := fmt.Errorf("Error deleting image: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}

	ui.Say("Creating image...")

	imageCh, errCh := driver.CreateImage(
		config.ImageName, config.ImageDescription, config.ImageFamily, config.Zone,
		config.DiskName, config.ImageLabels, config.ImageLicenses)
	var err error
	select {
	case err = <-errCh:
	case <-time.After(config.stateTimeout):
		err = errors.New("time out while waiting for image to register")
	}

	if err != nil {
		err := fmt.Errorf("Error waiting for image: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	state.Put("image", <-imageCh)
	return multistep.ActionContinue
}
809568
func (c *exportBundleCommand) Run(ctx *cmd.Context) error {
	client, err := c.newAPIFunc()
	if err != nil {
		return err
	}
	defer client.Close()

	result, err := client.ExportBundle()
	if err != nil {
		return err
	}

	if c.Filename == "" {
		_, err := fmt.Fprintf(ctx.Stdout, "%v", result)
		return err
	}
	filename := c.Filename
	file, err := os.Create(filename)
	if err != nil {
		return errors.Annotate(err, "while creating local file")
	}
	defer file.Close()

	_, err = file.WriteString(result)
	if err != nil {
		return errors.Annotate(err, "while copying in local file")
	}

	fmt.Fprintln(ctx.Stdout, "Bundle successfully exported to", filename)

	return nil
}
991403
func (c *AddCAASCommand) Run(ctx *cmd.Context) error {
	if err := c.verifyName(c.caasName); err != nil {
		return errors.Trace(err)
	}
	rdr, clusterName, err := c.getConfigReader(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	if closer, ok := rdr.(io.Closer); ok {
		defer closer.Close()
	}

	config := provider.KubeCloudParams{
		ClusterName:        clusterName,
		CaasName:           c.caasName,
		ContextName:        c.contextName,
		HostCloudRegion:    c.hostCloudRegion,
		CaasType:           c.caasType,
		ClientConfigGetter: c.newClientConfigReader,
	}

	newCloud, credential, credentialName, err := provider.CloudFromKubeConfig(rdr, config)
	if err != nil {
		return errors.Trace(err)
	}

	broker, err := c.brokerGetter(newCloud, credential)
	if err != nil {
		return errors.Trace(err)
	}
	storageParams := provider.KubeCloudStorageParams{
		WorkloadStorage:        c.workloadStorage,
		HostCloudRegion:        c.hostCloudRegion,
		MetadataChecker:        broker,
		GetClusterMetadataFunc: c.getClusterMetadataFunc(ctx),
	}

	storageMsg, err := provider.UpdateKubeCloudWithStorage(&newCloud, storageParams)
	if err != nil {
		if provider.IsClusterQueryError(err) {
			if err.Error() == "" {
				return errors.New(clusterQueryErrMsg)
			}
			return errors.Annotate(err, clusterQueryErrMsg)
		}
		if provider.IsNoRecommendedStorageError(err) {
			return errors.Errorf(noRecommendedStorageErrMsg, err.(provider.NoRecommendedStorageError).StorageProvider())
		}
		if provider.IsUnknownClusterError(err) {
			return errors.Errorf(unknownClusterErrMsg, err.(provider.UnknownClusterError).CloudName)
		}
		return errors.Trace(err)
	}

	if err := addCloudToLocal(c.cloudMetadataStore, newCloud); err != nil {
		return errors.Trace(err)
	}

	if err := c.addCredentialToLocal(c.caasName, credential, credentialName); err != nil {
		return errors.Trace(err)
	}

	if clusterName == "" {
		clusterName = c.hostCloudRegion
		if clusterName == "" {
			clusterName = newCloud.HostCloudRegion
		}
	}
	if c.controllerName == "" {
		successMsg := fmt.Sprintf("k8s substrate %q added as cloud %q%s", clusterName, c.caasName, storageMsg)
		successMsg += fmt.Sprintf("\nYou can now bootstrap to this cloud by running 'juju bootstrap %s'.", c.caasName)
		fmt.Fprintln(ctx.Stdout, successMsg)
		return nil
	}

	cloudClient, err := c.addCloudAPIFunc()
	if err != nil {
		return errors.Trace(err)
	}
	defer cloudClient.Close()

	if err := c.addCloudToControllerWithRegion(cloudClient, newCloud); err != nil {
		return errors.Trace(err)
	}
	if err := c.addCredentialToController(cloudClient, credential, credentialName); err != nil {
		return errors.Trace(err)
	}
	successMsg := fmt.Sprintf("k8s substrate %q added as cloud %q%s", clusterName, c.caasName, storageMsg)
	fmt.Fprintln(ctx.Stdout, successMsg)

	return nil
}
203261
func (dht *DHT) Run() {
	dht.init()
	dht.listen()
	dht.join()

	dht.Ready = true

	var pkt packet
	tick := time.Tick(dht.CheckKBucketPeriod)

	for {
		select {
		case pkt = <-dht.packets:
			handle(dht, pkt)
		case <-tick:
			if dht.routingTable.Len() == 0 {
				dht.join()
			} else if dht.transactionManager.len() == 0 {
				go dht.routingTable.Fresh()
			}
		}
	}
}