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