github.com/amanya/packer@v0.12.1-0.20161117214323-902ac5ab2eb6/builder/virtualbox/common/step_configure_vrdp.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"math/rand"
     7  	"net"
     8  
     9  	"github.com/mitchellh/multistep"
    10  	"github.com/mitchellh/packer/packer"
    11  )
    12  
    13  // This step configures the VM to enable the VRDP server
    14  // on the guest machine.
    15  //
    16  // Uses:
    17  //   driver Driver
    18  //   ui packer.Ui
    19  //   vmName string
    20  //
    21  // Produces:
    22  // vrdp_port unit - The port that VRDP is configured to listen on.
    23  type StepConfigureVRDP struct {
    24  	VRDPBindAddress string
    25  	VRDPPortMin     uint
    26  	VRDPPortMax     uint
    27  }
    28  
    29  func (s *StepConfigureVRDP) Run(state multistep.StateBag) multistep.StepAction {
    30  	driver := state.Get("driver").(Driver)
    31  	ui := state.Get("ui").(packer.Ui)
    32  	vmName := state.Get("vmName").(string)
    33  
    34  	log.Printf("Looking for available port between %d and %d on %s", s.VRDPPortMin, s.VRDPPortMax, s.VRDPBindAddress)
    35  	var vrdpPort uint
    36  	portRange := int(s.VRDPPortMax - s.VRDPPortMin)
    37  
    38  	for {
    39  		if portRange > 0 {
    40  			vrdpPort = uint(rand.Intn(portRange)) + s.VRDPPortMin
    41  		} else {
    42  			vrdpPort = s.VRDPPortMin
    43  		}
    44  
    45  		log.Printf("Trying port: %d", vrdpPort)
    46  		l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.VRDPBindAddress, vrdpPort))
    47  		if err == nil {
    48  			defer l.Close()
    49  			break
    50  		}
    51  	}
    52  
    53  	command := []string{
    54  		"modifyvm", vmName,
    55  		"--vrdeaddress", fmt.Sprintf("%s", s.VRDPBindAddress),
    56  		"--vrdeauthtype", "null",
    57  		"--vrde", "on",
    58  		"--vrdeport",
    59  		fmt.Sprintf("%d", vrdpPort),
    60  	}
    61  	if err := driver.VBoxManage(command...); err != nil {
    62  		err := fmt.Errorf("Error enabling VRDP: %s", err)
    63  		state.Put("error", err)
    64  		ui.Error(err.Error())
    65  		return multistep.ActionHalt
    66  	}
    67  
    68  	state.Put("vrdpIp", s.VRDPBindAddress)
    69  	state.Put("vrdpPort", vrdpPort)
    70  
    71  	return multistep.ActionContinue
    72  }
    73  
    74  func (s *StepConfigureVRDP) Cleanup(state multistep.StateBag) {}