github.com/rothwerx/packer@v0.9.0/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  	VRDPPortMin uint
    25  	VRDPPortMax uint
    26  }
    27  
    28  func (s *StepConfigureVRDP) Run(state multistep.StateBag) multistep.StepAction {
    29  	driver := state.Get("driver").(Driver)
    30  	ui := state.Get("ui").(packer.Ui)
    31  	vmName := state.Get("vmName").(string)
    32  
    33  	log.Printf("Looking for available port between %d and %d", s.VRDPPortMin, s.VRDPPortMax)
    34  	var vrdpPort uint
    35  	portRange := int(s.VRDPPortMax - s.VRDPPortMin)
    36  
    37  	for {
    38  		if portRange > 0 {
    39  			vrdpPort = uint(rand.Intn(portRange)) + s.VRDPPortMin
    40  		} else {
    41  			vrdpPort = s.VRDPPortMin
    42  		}
    43  
    44  		log.Printf("Trying port: %d", vrdpPort)
    45  		l, err := net.Listen("tcp", fmt.Sprintf(":%d", vrdpPort))
    46  		if err == nil {
    47  			defer l.Close()
    48  			break
    49  		}
    50  	}
    51  
    52  	command := []string{
    53  		"modifyvm", vmName,
    54  		"--vrdeaddress", "127.0.0.1",
    55  		"--vrdeauthtype", "null",
    56  		"--vrde", "on",
    57  		"--vrdeport",
    58  		fmt.Sprintf("%d", vrdpPort),
    59  	}
    60  	if err := driver.VBoxManage(command...); err != nil {
    61  		err := fmt.Errorf("Error enabling VRDP: %s", err)
    62  		state.Put("error", err)
    63  		ui.Error(err.Error())
    64  		return multistep.ActionHalt
    65  	}
    66  
    67  	state.Put("vrdpIp", "127.0.0.1")
    68  	state.Put("vrdpPort", vrdpPort)
    69  
    70  	return multistep.ActionContinue
    71  }
    72  
    73  func (s *StepConfigureVRDP) Cleanup(state multistep.StateBag) {}