github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/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 vncPort = uint(rand.Intn(portRange)) + config.VNCPortMin 36 log.Printf("Trying port: %d", vncPort) 37 l, err := net.Listen("tcp", fmt.Sprintf(":%d", vncPort)) 38 if err == nil { 39 defer l.Close() 40 break 41 } 42 } 43 44 ui.Say(fmt.Sprintf("Found available VNC port: %d", vncPort)) 45 state.Put("vnc_port", vncPort) 46 47 return multistep.ActionContinue 48 } 49 50 func (stepConfigureVNC) Cleanup(multistep.StateBag) {}