github.com/rothwerx/packer@v0.9.0/builder/qemu/step_configure_vnc.go (about)

     1  package qemu
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"log"
     8  	"math/rand"
     9  	"net"
    10  )
    11  
    12  // This step configures the VM to enable the VNC server.
    13  //
    14  // Uses:
    15  //   config *config
    16  //   ui     packer.Ui
    17  //
    18  // Produces:
    19  //   vnc_port uint - The port that VNC is configured to listen on.
    20  type stepConfigureVNC struct{}
    21  
    22  func (stepConfigureVNC) Run(state multistep.StateBag) multistep.StepAction {
    23  	config := state.Get("config").(*Config)
    24  	ui := state.Get("ui").(packer.Ui)
    25  
    26  	// Find an open VNC port. Note that this can still fail later on
    27  	// because we have to release the port at some point. But this does its
    28  	// best.
    29  	msg := fmt.Sprintf("Looking for available port between %d and %d", config.VNCPortMin, config.VNCPortMax)
    30  	ui.Say(msg)
    31  	log.Printf(msg)
    32  	var vncPort uint
    33  	portRange := int(config.VNCPortMax - config.VNCPortMin)
    34  	for {
    35  		if portRange > 0 {
    36  			vncPort = uint(rand.Intn(portRange)) + config.VNCPortMin
    37  		} else {
    38  			vncPort = config.VNCPortMin
    39  		}
    40  
    41  		log.Printf("Trying port: %d", vncPort)
    42  		l, err := net.Listen("tcp", fmt.Sprintf(":%d", vncPort))
    43  		if err == nil {
    44  			defer l.Close()
    45  			break
    46  		}
    47  	}
    48  
    49  	ui.Say(fmt.Sprintf("Found available VNC port: %d", vncPort))
    50  	state.Put("vnc_port", vncPort)
    51  
    52  	return multistep.ActionContinue
    53  }
    54  
    55  func (stepConfigureVNC) Cleanup(multistep.StateBag) {}