Ejemplo n.º 1
0
// cloneUpTo clones the template up to <<use>> times
func cloneUpTo(
	vmrun vmware.VmrunWrapper,
	config *util.LCMConfiguration,
	clones []*virtualMachine,
	use int) ([]string, error) {
	// Assert use greater zero
	if use <= 0 {
		return []string{}, nil
	}

	// First get available mac addresses
	availableAddresses := getAvailableMacAddresses(clones, config)

	// calculate how many clones need to be created
	diff := math.Max(0, float64(use-len(clones)))
	toCreate := int(math.Min(float64(len(availableAddresses)), diff))
	if toCreate <= 0 {
		return []string{}, nil
	}

	// Get snapshot for the clones
	snapshot, err := prepareTemplateSnapshot(vmrun, config)
	if err != nil {
		return nil, fmt.Errorf("Failed to prepare snapshot\n%s", err.Error())
	}
	var created []string

	// Now fire the clone command for each of the addresses
	for i := 0; i < toCreate; i++ {
		address := availableAddresses[i]
		vmID := util.MacAddressToVMId(address)
		vmName := fmt.Sprintf("%s-%s", config.Prefix, vmID)
		vmxPath := fmt.Sprintf(
			"%s%s.vmwarevm/%s.vmx",
			config.ClonesDirectory,
			vmName, vmName)

		// First create the linked clone
		err := vmrun.CloneLinked(
			config.TemplatePath,
			config.ClonesDirectory,
			vmName, snapshot)
		if err != nil {
			return nil, fmt.Errorf("Failed to clone vm %s\n%s", vmName, err.Error())
		}

		// Then configure that clone with the mac address
		err = util.UpdateVMX(vmxPath, vmxPath, address)
		if err != nil {
			return nil, fmt.Errorf("Failed to configure the linked clone %s\n%s",
				vmName, err.Error())
		}

		created = append(created, vmName)
	}
	return created, nil
}