github.com/marksheahan/packer@v0.10.2-0.20160613200515-1acb2d6645a0/builder/qemu/step_run.go (about)

     1  package qemu
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"path/filepath"
     7  	"strconv"
     8  	"strings"
     9  
    10  	"github.com/mitchellh/multistep"
    11  	"github.com/mitchellh/packer/packer"
    12  	"github.com/mitchellh/packer/template/interpolate"
    13  )
    14  
    15  // stepRun runs the virtual machine
    16  type stepRun struct {
    17  	BootDrive string
    18  	Message   string
    19  }
    20  
    21  type qemuArgsTemplateData struct {
    22  	HTTPIP      string
    23  	HTTPPort    uint
    24  	HTTPDir     string
    25  	OutputDir   string
    26  	Name        string
    27  	SSHHostPort uint
    28  }
    29  
    30  func (s *stepRun) Run(state multistep.StateBag) multistep.StepAction {
    31  	driver := state.Get("driver").(Driver)
    32  	ui := state.Get("ui").(packer.Ui)
    33  
    34  	ui.Say(s.Message)
    35  
    36  	command, err := getCommandArgs(s.BootDrive, state)
    37  	if err != nil {
    38  		err := fmt.Errorf("Error processing QemuArggs: %s", err)
    39  		ui.Error(err.Error())
    40  		return multistep.ActionHalt
    41  	}
    42  
    43  	if err := driver.Qemu(command...); err != nil {
    44  		err := fmt.Errorf("Error launching VM: %s", err)
    45  		ui.Error(err.Error())
    46  		return multistep.ActionHalt
    47  	}
    48  
    49  	return multistep.ActionContinue
    50  }
    51  
    52  func (s *stepRun) Cleanup(state multistep.StateBag) {
    53  	driver := state.Get("driver").(Driver)
    54  	ui := state.Get("ui").(packer.Ui)
    55  
    56  	if err := driver.Stop(); err != nil {
    57  		ui.Error(fmt.Sprintf("Error shutting down VM: %s", err))
    58  	}
    59  }
    60  
    61  func getCommandArgs(bootDrive string, state multistep.StateBag) ([]string, error) {
    62  	config := state.Get("config").(*Config)
    63  	isoPath := state.Get("iso_path").(string)
    64  	vncIP := state.Get("vnc_ip").(string)
    65  	vncPort := state.Get("vnc_port").(uint)
    66  	sshHostPort := state.Get("sshHostPort").(uint)
    67  	ui := state.Get("ui").(packer.Ui)
    68  	driver := state.Get("driver").(Driver)
    69  
    70  	vnc := fmt.Sprintf("%s:%d", vncIP, vncPort-5900)
    71  	vmName := config.VMName
    72  	imgPath := filepath.Join(config.OutputDir, vmName)
    73  
    74  	defaultArgs := make(map[string]interface{})
    75  	var deviceArgs []string
    76  	var driveArgs []string
    77  
    78  	defaultArgs["-name"] = vmName
    79  	defaultArgs["-machine"] = fmt.Sprintf("type=%s", config.MachineType)
    80  	defaultArgs["-netdev"] = fmt.Sprintf("user,id=user.0,hostfwd=tcp::%v-:%d", sshHostPort, config.Comm.Port())
    81  
    82  	qemuVersion, err := driver.Version()
    83  	if err != nil {
    84  		return nil, err
    85  	}
    86  	parts := strings.Split(qemuVersion, ".")
    87  	qemuMajor, err := strconv.Atoi(parts[0])
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	if qemuMajor >= 2 {
    92  		if config.DiskInterface == "virtio-scsi" {
    93  			deviceArgs = append(deviceArgs, "virtio-scsi-pci,id=scsi0", "scsi-hd,bus=scsi0.0,drive=drive0")
    94  			driveArgs = append(driveArgs, fmt.Sprintf("if=none,file=%s,id=drive0,cache=%s,discard=%s", imgPath, config.DiskCache, config.DiskDiscard))
    95  		} else {
    96  			driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=%s,cache=%s,discard=%s", imgPath, config.DiskInterface, config.DiskCache, config.DiskDiscard))
    97  		}
    98  	} else {
    99  		driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=%s,cache=%s", imgPath, config.DiskInterface, config.DiskCache))
   100  	}
   101  	deviceArgs = append(deviceArgs, fmt.Sprintf("%s,netdev=user.0", config.NetDevice))
   102  
   103  	if config.Headless == true {
   104  		vncIpRaw, vncIpOk := state.GetOk("vnc_ip")
   105  		vncPortRaw, vncPortOk := state.GetOk("vnc_port")
   106  
   107  		if vncIpOk && vncPortOk {
   108  			vncIp := vncIpRaw.(string)
   109  			vncPort := vncPortRaw.(uint)
   110  
   111  			ui.Message(fmt.Sprintf(
   112  				"The VM will be run headless, without a GUI. If you want to\n"+
   113  					"view the screen of the VM, connect via VNC without a password to\n"+
   114  					"%s:%d", vncIp, vncPort))
   115  		} else {
   116  			ui.Message("The VM will be run headless, without a GUI, as configured.\n" +
   117  				"If the run isn't succeeding as you expect, please enable the GUI\n" +
   118  				"to inspect the progress of the build.")
   119  		}
   120  	} else {
   121  		if qemuMajor >= 2 {
   122  			defaultArgs["-display"] = "sdl"
   123  		} else {
   124  			ui.Message("WARNING: The version of qemu  on your host doesn't support display mode.\n" +
   125  				"The display parameter will be ignored.")
   126  		}
   127  	}
   128  
   129  	defaultArgs["-device"] = deviceArgs
   130  	defaultArgs["-drive"] = driveArgs
   131  
   132  	if !config.DiskImage {
   133  		defaultArgs["-cdrom"] = isoPath
   134  	}
   135  	defaultArgs["-boot"] = bootDrive
   136  	defaultArgs["-m"] = "512M"
   137  	defaultArgs["-vnc"] = vnc
   138  
   139  	// Append the accelerator to the machine type if it is specified
   140  	if config.Accelerator != "none" {
   141  		defaultArgs["-machine"] = fmt.Sprintf("%s,accel=%s", defaultArgs["-machine"], config.Accelerator)
   142  	} else {
   143  		ui.Message("WARNING: The VM will be started with no hardware acceleration.\n" +
   144  			"The installation may take considerably longer to finish.\n")
   145  	}
   146  
   147  	// Determine if we have a floppy disk to attach
   148  	if floppyPathRaw, ok := state.GetOk("floppy_path"); ok {
   149  		defaultArgs["-fda"] = floppyPathRaw.(string)
   150  	} else {
   151  		log.Println("Qemu Builder has no floppy files, not attaching a floppy.")
   152  	}
   153  
   154  	inArgs := make(map[string][]string)
   155  	if len(config.QemuArgs) > 0 {
   156  		ui.Say("Overriding defaults Qemu arguments with QemuArgs...")
   157  
   158  		httpPort := state.Get("http_port").(uint)
   159  		ctx := config.ctx
   160  		ctx.Data = qemuArgsTemplateData{
   161  			"10.0.2.2",
   162  			httpPort,
   163  			config.HTTPDir,
   164  			config.OutputDir,
   165  			config.VMName,
   166  			sshHostPort,
   167  		}
   168  		newQemuArgs, err := processArgs(config.QemuArgs, &ctx)
   169  		if err != nil {
   170  			return nil, err
   171  		}
   172  
   173  		// because qemu supports multiple appearances of the same
   174  		// switch, just different values, each key in the args hash
   175  		// will have an array of string values
   176  		for _, qemuArgs := range newQemuArgs {
   177  			key := qemuArgs[0]
   178  			val := strings.Join(qemuArgs[1:], "")
   179  			if _, ok := inArgs[key]; !ok {
   180  				inArgs[key] = make([]string, 0)
   181  			}
   182  			if len(val) > 0 {
   183  				inArgs[key] = append(inArgs[key], val)
   184  			}
   185  		}
   186  	}
   187  
   188  	// get any remaining missing default args from the default settings
   189  	for key := range defaultArgs {
   190  		if _, ok := inArgs[key]; !ok {
   191  			arg := make([]string, 1)
   192  			switch defaultArgs[key].(type) {
   193  			case string:
   194  				arg[0] = defaultArgs[key].(string)
   195  			case []string:
   196  				arg = defaultArgs[key].([]string)
   197  			}
   198  			inArgs[key] = arg
   199  		}
   200  	}
   201  
   202  	// Flatten to array of strings
   203  	outArgs := make([]string, 0)
   204  	for key, values := range inArgs {
   205  		if len(values) > 0 {
   206  			for idx := range values {
   207  				outArgs = append(outArgs, key, values[idx])
   208  			}
   209  		} else {
   210  			outArgs = append(outArgs, key)
   211  		}
   212  	}
   213  
   214  	return outArgs, nil
   215  }
   216  
   217  func processArgs(args [][]string, ctx *interpolate.Context) ([][]string, error) {
   218  	var err error
   219  
   220  	if args == nil {
   221  		return make([][]string, 0), err
   222  	}
   223  
   224  	newArgs := make([][]string, len(args))
   225  	for argsIdx, rowArgs := range args {
   226  		parms := make([]string, len(rowArgs))
   227  		newArgs[argsIdx] = parms
   228  		for i, parm := range rowArgs {
   229  			parms[i], err = interpolate.Render(parm, ctx)
   230  			if err != nil {
   231  				return nil, err
   232  			}
   233  		}
   234  	}
   235  
   236  	return newArgs, err
   237  }