// Run executes the Packer build step that gathers GCE instance info.
// This adds "instance_ip" to the multistep state.
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
	}
}
367023
func (o PruneBuildsOptions) Run() error {
	buildConfigList, err := o.BuildClient.BuildConfigs(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	buildConfigs := []*buildv1.BuildConfig{}
	for i := range buildConfigList.Items {
		buildConfigs = append(buildConfigs, &buildConfigList.Items[i])
	}

	buildList, err := o.BuildClient.Builds(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	builds := []*buildv1.Build{}
	for i := range buildList.Items {
		builds = append(builds, &buildList.Items[i])
	}

	options := PrunerOptions{
		KeepYoungerThan: o.KeepYoungerThan,
		Orphans:         o.Orphans,
		KeepComplete:    o.KeepComplete,
		KeepFailed:      o.KeepFailed,
		BuildConfigs:    buildConfigs,
		Builds:          builds,
	}
	pruner := NewPruner(options)

	w := tabwriter.NewWriter(o.Out, 10, 4, 3, ' ', 0)
	defer w.Flush()

	buildDeleter := &describingBuildDeleter{w: w}

	if o.Confirm {
		buildDeleter.delegate = NewBuildDeleter(o.BuildClient)
	} else {
		fmt.Fprintln(os.Stderr, "Dry run enabled - no modifications will be made. Add --confirm to remove builds")
	}

	return pruner.Prune(buildDeleter)
}
843810
func (e *Kex2Provisionee) Run(m libkb.MetaContext) error {
	m.G().LocalSigchainGuard().Set(m.Ctx(), "Kex2Provisionee")
	defer m.G().LocalSigchainGuard().Clear(m.Ctx(), "Kex2Provisionee")

	// check device struct:
	if len(e.device.Type) == 0 {
		return errors.New("provisionee device requires Type to be set")
	}
	if e.device.ID.IsNil() {
		return errors.New("provisionee device requires ID to be set")
	}

	if m.LoginContext() == nil {
		return errors.New("Kex2Provisionee needs LoginContext set in engine.Context")
	}

	if len(e.secret) == 0 {
		panic("empty secret")
	}

	m, e.kex2Cancel = m.WithContextCancel()
	defer e.kex2Cancel()

	// The MetaContext m is needed in some of the kex2 functions. Make sure to do that
	// after we've added a cancelation above.
	e.mctx = m

	karg := kex2.KexBaseArg{
		Ctx:           m.Ctx(),
		LogCtx:        newKex2LogContext(m.G()),
		Mr:            libkb.NewKexRouter(m),
		DeviceID:      e.device.ID,
		Secret:        e.secret,
		SecretChannel: e.secretCh,
		Timeout:       60 * time.Minute,
	}
	parg := kex2.ProvisioneeArg{
		KexBaseArg:  karg,
		Provisionee: e,
	}
	return kex2.RunProvisionee(parg)
}
718976
func (b *Builder) Run() error {
	wg := &errgroup.Group{}
	root, err := filepath.EvalSymlinks(b.RootPath)
	if err != nil {
		return err
	}
	err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if info == nil {
			return filepath.SkipDir
		}

		base := strings.ToLower(filepath.Base(path))
		if strings.HasPrefix(base, "_") {
			return filepath.SkipDir
		}
		for _, f := range b.IgnoredFolders {
			if strings.ToLower(f) == base {
				if info.IsDir() {
					return filepath.SkipDir
				} else {
					return nil
				}
			}
		}
		if !info.IsDir() {
			wg.Go(func() error {
				return b.process(path)
			})
		}
		return nil
	})
	if err != nil {
		return err
	}
	if err := wg.Wait(); err != nil {
		return err
	}
	return b.dump()
}
1116030
func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	comm := state.Get("communicator").(packer.Communicator)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	if s.Command != "" {
		ui.Say("Gracefully halting virtual machine...")
		log.Printf("Executing shutdown command: %s", s.Command)

		var stdout, stderr bytes.Buffer
		cmd := &packer.RemoteCmd{
			Command: s.Command,
			Stdout:  &stdout,
			Stderr:  &stderr,
		}
		if err := comm.Start(ctx, cmd); err != nil {
			err := fmt.Errorf("Failed to send shutdown command: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}

		// Wait for the machine to actually shut down
		log.Printf("Waiting max %s for shutdown to complete", s.Timeout)
		shutdownTimer := time.After(s.Timeout)
		for {
			running, _ := driver.IsRunning(vmName)
			if !running {
				break
			}

			select {
			case <-shutdownTimer:
				log.Printf("Shutdown stdout: %s", stdout.String())
				log.Printf("Shutdown stderr: %s", stderr.String())
				err := errors.New("Timeout while waiting for machine to shut down.")
				state.Put("error", err)
				ui.Error(err.Error())
				return multistep.ActionHalt
			default:
				time.Sleep(500 * time.Millisecond)
			}
		}
	} else {
		ui.Say("Halting the virtual machine...")
		if err := driver.Stop(vmName); err != nil {
			err = fmt.Errorf("Error stopping VM: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}

	log.Println("VM shut down.")
	return multistep.ActionContinue
}
1164311
func (s *Server) Run(ready chan struct{}) (err error) {
	var listener net.Listener
	o := rpc2.SimpleLogOutput{}
	lf := rpc2.NewSimpleLogFactory(o, nil)
	o.Info(fmt.Sprintf("Listening on port %d...", s.port))
	if listener, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", s.port)); err != nil {
		return
	}
	close(ready)
	for {
		var c net.Conn
		if c, err = listener.Accept(); err != nil {
			return
		}
		xp := rpc2.NewTransport(c, lf, nil)
		srv := rpc2.NewServer(xp, nil)
		srv.Register(ArithProtocol(&ArithServer{c}))
		srv.Run(true)
	}
	return nil
}
1314057
func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
	b.ui = ui

	// Create a CloudStack API client.
	client := cloudstack.NewAsyncClient(
		b.config.APIURL,
		b.config.APIKey,
		b.config.SecretKey,
		!b.config.SSLNoVerify,
	)

	// Set the time to wait before timing out
	client.AsyncTimeout(int64(b.config.AsyncTimeout.Seconds()))

	// Some CloudStack service providers only allow HTTP GET calls.
	client.HTTPGETOnly = b.config.HTTPGetOnly

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

	// Build the steps.
	steps := []multistep.Step{
		&stepPrepareConfig{},
		&common.StepHTTPServer{
			HTTPDir:     b.config.HTTPDir,
			HTTPPortMin: b.config.HTTPPortMin,
			HTTPPortMax: b.config.HTTPPortMax,
		},
		&stepKeypair{
			Debug:        b.config.PackerDebug,
			Comm:         &b.config.Comm,
			DebugKeyPath: fmt.Sprintf("cs_%s.pem", b.config.PackerBuildName),
		},
		&stepCreateSecurityGroup{},
		&stepCreateInstance{
			Ctx:   b.config.ctx,
			Debug: b.config.PackerDebug,
		},
		&stepSetupNetworking{},
		&communicator.StepConnect{
			Config:    &b.config.Comm,
			Host:      commHost,
			SSHConfig: b.config.Comm.SSHConfigFunc(),
			SSHPort:   commPort,
			WinRMPort: commPort,
		},
		&common.StepProvision{},
		&common.StepCleanupTempKeys{
			Comm: &b.config.Comm,
		},
		&stepShutdownInstance{},
		&stepCreateTemplate{},
	}

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

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

	// If there was no template created, just return
	if _, ok := state.GetOk("template"); !ok {
		return nil, nil
	}

	// Build the artifact and return it
	artifact := &Artifact{
		client:   client,
		config:   b.config,
		template: state.Get("template").(*cloudstack.CreateTemplateResponse),
	}

	return artifact, nil
}
381398
func (p *pingPongService) Run(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
	log := p.log.New("peer.id", peer.ID())

	errC := make(chan error)
	go func() {
		for range time.Tick(10 * time.Second) {
			log.Info("sending ping")
			if err := p2p.Send(rw, pingMsgCode, "PING"); err != nil {
				errC <- err
				return
			}
		}
	}()
	go func() {
		for {
			msg, err := rw.ReadMsg()
			if err != nil {
				errC <- err
				return
			}
			payload, err := ioutil.ReadAll(msg.Payload)
			if err != nil {
				errC <- err
				return
			}
			log.Info("received message", "msg.code", msg.Code, "msg.payload", string(payload))
			atomic.AddInt64(&p.received, 1)
			if msg.Code == pingMsgCode {
				log.Info("sending pong")
				go p2p.Send(rw, pongMsgCode, "PONG")
			}
		}
	}()
	return <-errC
}
572087
func (b *Builder) Run(step *Step, exec Executor, noRunsRemaining bool) error {
	fn, ok := evaluateTable[step.Command]
	if !ok {
		return exec.UnrecognizedInstruction(step)
	}
	if err := fn(b, step.Args, step.Attrs, step.Flags, step.Original); err != nil {
		return err
	}

	copies := b.PendingCopies
	b.PendingCopies = nil
	runs := b.PendingRuns
	b.PendingRuns = nil

	// Once a VOLUME is defined, future ADD/COPY instructions are
	// all that may mutate that path. Instruct the executor to preserve
	// the path. The executor must handle invalidating preserved info.
	for _, path := range b.PendingVolumes {
		if b.Volumes.Add(path) && !noRunsRemaining {
			if err := exec.Preserve(path); err != nil {
				return err
			}
		}
	}

	if err := exec.Copy(b.Excludes, copies...); err != nil {
		return err
	}

	if len(b.RunConfig.WorkingDir) > 0 {
		if err := exec.EnsureContainerPath(b.RunConfig.WorkingDir); err != nil {
			return err
		}
	}

	for _, run := range runs {
		config := b.Config()
		config.Env = step.Env
		if err := exec.Run(run, *config); err != nil {
			return err
		}
	}

	return nil
}
1184939
func (ic *IngressIPController) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer ic.queue.ShutDown()

	klog.V(5).Infof("Waiting for the initial sync to be completed")
	if !cache.WaitForCacheSync(stopCh, ic.hasSynced) {
		return
	}

	if !ic.processInitialSync() {
		return
	}

	klog.V(5).Infof("Initial sync completed, starting worker")
	for ic.work() {
		var done bool
		select {
		case _, ok := <-stopCh:
			done = !ok
		default:
		}
		if done {
			break
		}
	}

	klog.V(1).Infof("Shutting down ingress ip controller")
}
1017462
func (step modelFoldersUpgradeStep) Run(ctx context.ProviderCallContext) error {
	return step.env.withSession(ctx, func(env *sessionEnviron) error {
		// We must create the folder even if there are no VMs in the model.
		modelFolderPath := path.Join(
			controllerFolderName(step.controllerUUID),
			env.modelFolderName(),
		)
		if _, err := env.client.EnsureVMFolder(env.ctx, modelFolderPath); err != nil {
			HandleCredentialError(err, ctx)
			return errors.Annotate(err, "creating model folder")
		}

		// List all instances at the top level with the model UUID,
		// and move them into the folder.
		vms, err := env.client.VirtualMachines(env.ctx, env.namespace.Prefix()+"*")
		if err != nil || len(vms) == 0 {
			HandleCredentialError(err, ctx)
			return err
		}
		refs := make([]types.ManagedObjectReference, len(vms))
		for i, vm := range vms {
			logger.Debugf("moving VM %q into %q", vm.Name, modelFolderPath)
			refs[i] = vm.Reference()
		}
		if err := env.client.MoveVMsInto(env.ctx, modelFolderPath, refs...); err != nil {
			HandleCredentialError(err, ctx)
			return errors.Annotate(err, "moving VMs into model folder")
		}
		return nil
	})
}
342049
func (s *StepCreateBuildDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating build directory...")

	var err error
	if s.TempPath == "" {
		s.buildDir, err = tmp.Dir("hyperv")
	} else {
		s.buildDir, err = ioutil.TempDir(s.TempPath, "hyperv")
	}

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

	log.Printf("Created build directory: %s", s.buildDir)

	// Record the build directory location for later steps
	state.Put("build_dir", s.buildDir)

	return multistep.ActionContinue
}
821877
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 Parallels
	driver, err := parallelscommon.NewDriver()
	if err != nil {
		return nil, fmt.Errorf("Failed creating Parallels 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)
	state.Put("http_port", 0)

	// Build the steps.
	steps := []multistep.Step{
		&parallelscommon.StepPrepareParallelsTools{
			ParallelsToolsMode:   b.config.ParallelsToolsMode,
			ParallelsToolsFlavor: b.config.ParallelsToolsFlavor,
		},
		&parallelscommon.StepOutputDir{
			Force: b.config.PackerForce,
			Path:  b.config.OutputDir,
		},
		&common.StepCreateFloppy{
			Files:       b.config.FloppyConfig.FloppyFiles,
			Directories: b.config.FloppyConfig.FloppyDirectories,
		},
		&StepImport{
			Name:       b.config.VMName,
			SourcePath: b.config.SourcePath,
		},
		&parallelscommon.StepAttachParallelsTools{
			ParallelsToolsMode: b.config.ParallelsToolsMode,
		},
		new(parallelscommon.StepAttachFloppy),
		&parallelscommon.StepPrlctl{
			Commands: b.config.Prlctl,
			Ctx:      b.config.ctx,
		},
		&parallelscommon.StepRun{},
		&parallelscommon.StepTypeBootCommand{
			BootCommand:    b.config.FlatBootCommand(),
			BootWait:       b.config.BootWait,
			HostInterfaces: []string{},
			VMName:         b.config.VMName,
			Ctx:            b.config.ctx,
			GroupInterval:  b.config.BootConfig.BootGroupInterval,
		},
		&communicator.StepConnect{
			Config:    &b.config.SSHConfig.Comm,
			Host:      parallelscommon.CommHost,
			SSHConfig: b.config.SSHConfig.Comm.SSHConfigFunc(),
		},
		&parallelscommon.StepUploadVersion{
			Path: b.config.PrlctlVersionFile,
		},
		&parallelscommon.StepUploadParallelsTools{
			ParallelsToolsFlavor:    b.config.ParallelsToolsFlavor,
			ParallelsToolsGuestPath: b.config.ParallelsToolsGuestPath,
			ParallelsToolsMode:      b.config.ParallelsToolsMode,
			Ctx:                     b.config.ctx,
		},
		new(common.StepProvision),
		&parallelscommon.StepShutdown{
			Command: b.config.ShutdownCommand,
			Timeout: b.config.ShutdownTimeout,
		},
		&common.StepCleanupTempKeys{
			Comm: &b.config.SSHConfig.Comm,
		},
		&parallelscommon.StepPrlctl{
			Commands: b.config.PrlctlPost,
			Ctx:      b.config.ctx,
		},
		&parallelscommon.StepCompactDisk{
			Skip: b.config.SkipCompaction,
		},
	}

	// Run the steps.
	b.runner = common.NewRunnerWithPauseFn(steps, b.config.PackerConfig, ui, state)
	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 parallelscommon.NewArtifact(b.config.OutputDir)
}
299321
func (s *StepTeardownInstance) 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)

	name := config.InstanceName
	if name == "" {
		return multistep.ActionHalt
	}

	ui.Say("Deleting instance...")
	instanceLog, _ := driver.GetSerialPortOutput(config.Zone, name)
	state.Put("instance_log", instanceLog)
	errCh, err := driver.DeleteInstance(config.Zone, name)
	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", name, err))
		return multistep.ActionHalt
	}
	ui.Message("Instance has been deleted!")
	state.Put("instance_name", "")

	return multistep.ActionContinue
}
200107
func (client *AMIClient) Run() {
	go func() {
		for {
			data, err := client.conn.ReadMIMEHeader()
			if err != nil {
				switch err {
				case syscall.ECONNABORTED:
					fallthrough
				case syscall.ECONNRESET:
					fallthrough
				case syscall.ECONNREFUSED:
					fallthrough
				case io.EOF:
					client.NetError <- err
					<-client.waitNewConnection
				default:
					client.Error <- err
				}
				continue
			}

			if ev, err := newEvent(&data); err != nil {
				if err != errNotEvent {
					client.Error <- err
				}
			} else {
				client.Events <- ev
			}

			//only handle valid responses
			//@todo handle longs response
			// see  https://marcelog.github.io/articles/php_asterisk_manager_interface_protocol_tutorial_introduction.html
			if response, err := newResponse(&data); err == nil {
				client.notifyResponse(response)
			}

		}
	}()
}
497876
func (e *PGPKeyfinder) Run(m libkb.MetaContext) error {
	e.loadUsers(m)
	e.loadKeys(m)
	return e.runerr
}
819547
func (m *Main) Run() (err error) {
	go func() {
		fmt.Println(http.ListenAndServe("localhost:6060", nil))
	}()

	schema := gopilosa.NewSchema()
	m.index = schema.Index(m.Index)
	pdk.NewRankedField(m.index, "weather_condition", 0)
	pdk.NewRankedField(m.index, "precipitation_type", 0)
	pdk.NewRankedField(m.index, "precipitation_inches", 0)
	pdk.NewRankedField(m.index, "temp_f", 0)
	pdk.NewRankedField(m.index, "pressure_i", 0)
	pdk.NewRankedField(m.index, "humidity", 0)

	m.importer, err = pdk.SetupPilosa([]string{m.PilosaHost}, m.Index, schema, uint(m.BufferSize))
	if err != nil {
		return errors.Wrap(err, "setting up pilosa")
	}

	pilosaURI, err := gopilosa.NewURIFromAddress(m.PilosaHost)
	if err != nil {
		return fmt.Errorf("interpreting pilosaHost '%v': %v", m.PilosaHost, err)
	}
	setupClient, err := gopilosa.NewClient(pilosaURI)
	if err != nil {
		return fmt.Errorf("setting up client: %v", err)
	}
	m.client = setupClient

	readFieldNames := []string{"cab_type", "passenger_count", "total_amount_dollars", "pickup_time", "pickup_day", "pickup_mday", "pickup_month", "pickup_year", "drop_time", "drop_day", "drop_mday", "drop_month", "drop_year", "dist_miles", "duration_minutes", "speed_mph", "pickup_grid_id", "drop_grid_id"}

	for _, fieldName := range readFieldNames {
		m.index.Field(fieldName)
	}
	err = setupClient.SyncSchema(schema)
	if err != nil {
		return errors.Wrap(err, "synchronizing schema")
	}

	err = m.WeatherCache.ReadAll()
	if err != nil {
		return errors.Wrap(err, "reading weather cache")
	}

	err = m.appendWeatherData()
	if err != nil {
		return errors.Wrap(err, "appending weather data")
	}

	return errors.Wrap(m.importer.Close(), "closing indexer")
}