github.com/timsutton/packer@v1.3.2/builder/hyperv/common/step_wait_for_install_to_complete.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/hashicorp/packer/helper/multistep"
     9  	"github.com/hashicorp/packer/packer"
    10  )
    11  
    12  const (
    13  	SleepSeconds = 10
    14  )
    15  
    16  type StepWaitForPowerOff struct {
    17  }
    18  
    19  func (s *StepWaitForPowerOff) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    20  	driver := state.Get("driver").(Driver)
    21  	ui := state.Get("ui").(packer.Ui)
    22  	vmName := state.Get("vmName").(string)
    23  	ui.Say("Waiting for vm to be powered down...")
    24  
    25  	for {
    26  		isOff, err := driver.IsOff(vmName)
    27  
    28  		if err != nil {
    29  			err := fmt.Errorf("Error checking if vm is off: %s", err)
    30  			state.Put("error", err)
    31  			ui.Error(err.Error())
    32  			return multistep.ActionHalt
    33  		}
    34  
    35  		if isOff {
    36  			break
    37  		} else {
    38  			time.Sleep(time.Second * SleepSeconds)
    39  		}
    40  	}
    41  
    42  	return multistep.ActionContinue
    43  }
    44  
    45  func (s *StepWaitForPowerOff) Cleanup(state multistep.StateBag) {
    46  }
    47  
    48  type StepWaitForInstallToComplete struct {
    49  	ExpectedRebootCount uint
    50  	ActionName          string
    51  }
    52  
    53  func (s *StepWaitForInstallToComplete) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    54  	driver := state.Get("driver").(Driver)
    55  	ui := state.Get("ui").(packer.Ui)
    56  	vmName := state.Get("vmName").(string)
    57  
    58  	if len(s.ActionName) > 0 {
    59  		ui.Say(fmt.Sprintf("%v ! Waiting for VM to reboot %v times...", s.ActionName, s.ExpectedRebootCount))
    60  	}
    61  
    62  	var rebootCount uint
    63  	var lastUptime uint64
    64  
    65  	for rebootCount < s.ExpectedRebootCount {
    66  		uptime, err := driver.Uptime(vmName)
    67  
    68  		if err != nil {
    69  			err := fmt.Errorf("Error checking uptime: %s", err)
    70  			state.Put("error", err)
    71  			ui.Error(err.Error())
    72  			return multistep.ActionHalt
    73  		}
    74  
    75  		if uptime < lastUptime {
    76  			rebootCount++
    77  			ui.Say(fmt.Sprintf("%v  -> Detected reboot %v after %v seconds...", s.ActionName, rebootCount, lastUptime))
    78  		}
    79  
    80  		lastUptime = uptime
    81  
    82  		if rebootCount < s.ExpectedRebootCount {
    83  			time.Sleep(time.Second * SleepSeconds)
    84  		}
    85  	}
    86  
    87  	return multistep.ActionContinue
    88  }
    89  
    90  func (s *StepWaitForInstallToComplete) Cleanup(state multistep.StateBag) {
    91  
    92  }