Search in sources :

Example 61 with VirtualMachineTO

use of com.cloud.agent.api.to.VirtualMachineTO in project cloudstack by apache.

the class CitrixScaleVmCommandWrapper method execute.

@Override
public Answer execute(final ScaleVmCommand command, final CitrixResourceBase citrixResourceBase) {
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final String vmName = vmSpec.getName();
    try {
        final Connection conn = citrixResourceBase.getConnection();
        final Set<VM> vms = VM.getByNameLabel(conn, vmName);
        final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
        // If DMC is not enable then don't execute this command.
        if (!citrixResourceBase.isDmcEnabled(conn, host)) {
            throw new CloudRuntimeException("Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:" + citrixResourceBase.getHost().getUuid() + " ,check your license and hypervisor version.");
        }
        if (vms == null || vms.size() == 0) {
            s_logger.info("No running VM " + vmName + " exists on XenServer" + citrixResourceBase.getHost().getUuid());
            return new ScaleVmAnswer(command, false, "VM does not exist");
        }
        // stop vm which is running on this host or is in halted state
        final Iterator<VM> iter = vms.iterator();
        while (iter.hasNext()) {
            final VM vm = iter.next();
            final VM.Record vmr = vm.getRecord(conn);
            if (vmr.powerState == VmPowerState.HALTED || vmr.powerState == VmPowerState.RUNNING && !citrixResourceBase.isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
                iter.remove();
            }
        }
        for (final VM vm : vms) {
            vm.getRecord(conn);
            try {
                citrixResourceBase.scaleVM(conn, vm, vmSpec, host);
            } catch (final Exception e) {
                final String msg = "Catch exception " + e.getClass().getName() + " when scaling VM:" + vmName + " due to " + e.toString();
                s_logger.debug(msg);
                return new ScaleVmAnswer(command, false, msg);
            }
        }
        final String msg = "scaling VM " + vmName + " is successful on host " + host;
        s_logger.debug(msg);
        return new ScaleVmAnswer(command, true, msg);
    } catch (final XenAPIException e) {
        final String msg = "Upgrade Vm " + vmName + " fail due to " + e.toString();
        s_logger.warn(msg, e);
        return new ScaleVmAnswer(command, false, msg);
    } catch (final XmlRpcException e) {
        final String msg = "Upgrade Vm " + vmName + " fail due to " + e.getMessage();
        s_logger.warn(msg, e);
        return new ScaleVmAnswer(command, false, msg);
    } catch (final Exception e) {
        final String msg = "Unable to upgrade " + vmName + " due to " + e.getMessage();
        s_logger.warn(msg, e);
        return new ScaleVmAnswer(command, false, msg);
    }
}
Also used : Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Host(com.xensource.xenapi.Host) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) ScaleVmAnswer(com.cloud.agent.api.ScaleVmAnswer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VM(com.xensource.xenapi.VM) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 62 with VirtualMachineTO

use of com.cloud.agent.api.to.VirtualMachineTO in project cloudstack by apache.

the class CitrixStartCommandWrapper method execute.

@Override
public Answer execute(final StartCommand command, final CitrixResourceBase citrixResourceBase) {
    final Connection conn = citrixResourceBase.getConnection();
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final String vmName = vmSpec.getName();
    VmPowerState state = VmPowerState.HALTED;
    VM vm = null;
    // if a VDI is created, record its UUID to send back to the CS MS
    final Map<String, String> iqnToPath = new HashMap<String, String>();
    try {
        final Set<VM> vms = VM.getByNameLabel(conn, vmName);
        if (vms != null) {
            for (final VM v : vms) {
                final VM.Record vRec = v.getRecord(conn);
                if (vRec.powerState == VmPowerState.HALTED) {
                    v.destroy(conn);
                } else if (vRec.powerState == VmPowerState.RUNNING) {
                    final String host = vRec.residentOn.getUuid(conn);
                    final String msg = "VM " + vmName + " is runing on host " + host;
                    s_logger.debug(msg);
                    return new StartAnswer(command, msg, host);
                } else {
                    final String msg = "There is already a VM having the same name " + vmName + " vm record " + vRec.toString();
                    s_logger.warn(msg);
                    return new StartAnswer(command, msg);
                }
            }
        }
        s_logger.debug("1. The VM " + vmName + " is in Starting state.");
        final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
        vm = citrixResourceBase.createVmFromTemplate(conn, vmSpec, host);
        final GPUDeviceTO gpuDevice = vmSpec.getGpuDevice();
        if (gpuDevice != null) {
            s_logger.debug("Creating VGPU for of VGPU type: " + gpuDevice.getVgpuType() + " in GPU group " + gpuDevice.getGpuGroup() + " for VM " + vmName);
            citrixResourceBase.createVGPU(conn, command, vm, gpuDevice);
        }
        if (vmSpec.getType() != VirtualMachine.Type.User) {
            citrixResourceBase.createPatchVbd(conn, vmName, vm);
        }
        // put cdrom at the first place in the list
        List<DiskTO> disks = new ArrayList<DiskTO>(vmSpec.getDisks().length);
        int index = 0;
        for (final DiskTO disk : vmSpec.getDisks()) {
            if (Volume.Type.ISO.equals(disk.getType())) {
                disks.add(0, disk);
            } else {
                disks.add(index, disk);
            }
            index++;
        }
        for (DiskTO disk : disks) {
            final VDI newVdi = citrixResourceBase.prepareManagedDisk(conn, disk, vmSpec.getId(), vmSpec.getName());
            if (newVdi != null) {
                final String path = newVdi.getUuid(conn);
                iqnToPath.put(disk.getDetails().get(DiskTO.IQN), path);
            }
            citrixResourceBase.createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), newVdi);
        }
        for (final NicTO nic : vmSpec.getNics()) {
            citrixResourceBase.createVif(conn, vmName, vm, vmSpec, nic);
        }
        citrixResourceBase.startVM(conn, host, vm, vmName);
        if (citrixResourceBase.isOvs()) {
            // TODO(Salvatore-orlando): This code should go
            for (final NicTO nic : vmSpec.getNics()) {
                if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vswitch) {
                    final HashMap<String, String> args = citrixResourceBase.parseDefaultOvsRuleComamnd(BroadcastDomainType.getValue(nic.getBroadcastUri()));
                    final OvsSetTagAndFlowCommand flowCmd = new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"), Long.parseLong(args.get("vmId")));
                    final CitrixRequestWrapper citrixRequestWrapper = CitrixRequestWrapper.getInstance();
                    final OvsSetTagAndFlowAnswer r = (OvsSetTagAndFlowAnswer) citrixRequestWrapper.execute(flowCmd, citrixResourceBase);
                    if (!r.getResult()) {
                        s_logger.warn("Failed to set flow for VM " + r.getVmId());
                    } else {
                        s_logger.info("Success to set flow for VM " + r.getVmId());
                    }
                }
            }
        }
        if (citrixResourceBase.canBridgeFirewall()) {
            String result = null;
            if (vmSpec.getType() != VirtualMachine.Type.User) {
                final NicTO[] nics = vmSpec.getNics();
                boolean secGrpEnabled = false;
                for (final NicTO nic : nics) {
                    if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                        secGrpEnabled = true;
                        break;
                    }
                }
                if (secGrpEnabled) {
                    result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules_systemvm", "vmName", vmName);
                    if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
                        s_logger.warn("Failed to program default network rules for " + vmName);
                    } else {
                        s_logger.info("Programmed default network rules for " + vmName);
                    }
                }
            } else {
                // For user vm, program the rules for each nic if the
                // isolation uri scheme is ec2
                final NicTO[] nics = vmSpec.getNics();
                for (final NicTO nic : nics) {
                    if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                        final List<String> nicSecIps = nic.getNicSecIps();
                        String secIpsStr;
                        final StringBuilder sb = new StringBuilder();
                        if (nicSecIps != null) {
                            for (final String ip : nicSecIps) {
                                sb.append(ip).append(":");
                            }
                            secIpsStr = sb.toString();
                        } else {
                            secIpsStr = "0:";
                        }
                        result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", Long.toString(vmSpec.getId()), "secIps", secIpsStr);
                        if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
                            s_logger.warn("Failed to program default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
                        } else {
                            s_logger.info("Programmed default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
                        }
                    }
                }
            }
        }
        state = VmPowerState.RUNNING;
        final StartAnswer startAnswer = new StartAnswer(command);
        startAnswer.setIqnToPath(iqnToPath);
        return startAnswer;
    } catch (final Exception e) {
        s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
        final String msg = citrixResourceBase.handleVmStartFailure(conn, vmName, vm, "", e);
        final StartAnswer startAnswer = new StartAnswer(command, msg);
        startAnswer.setIqnToPath(iqnToPath);
        return startAnswer;
    } finally {
        if (state != VmPowerState.HALTED) {
            s_logger.debug("2. The VM " + vmName + " is in " + state + " state.");
        } else {
            s_logger.debug("The VM is in stopped state, detected problem during startup : " + vmName);
        }
    }
}
Also used : StartAnswer(com.cloud.agent.api.StartAnswer) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) VDI(com.xensource.xenapi.VDI) NicTO(com.cloud.agent.api.to.NicTO) Connection(com.xensource.xenapi.Connection) Host(com.xensource.xenapi.Host) OvsSetTagAndFlowAnswer(com.cloud.agent.api.OvsSetTagAndFlowAnswer) GPUDeviceTO(com.cloud.agent.api.to.GPUDeviceTO) OvsSetTagAndFlowCommand(com.cloud.agent.api.OvsSetTagAndFlowCommand) VM(com.xensource.xenapi.VM) VmPowerState(com.xensource.xenapi.Types.VmPowerState) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 63 with VirtualMachineTO

use of com.cloud.agent.api.to.VirtualMachineTO in project cloudstack by apache.

the class BareMetalResourceBase method execute.

protected StartAnswer execute(StartCommand cmd) {
    VirtualMachineTO vm = cmd.getVirtualMachine();
    OutputInterpreter.AllLinesParser interpreter = new OutputInterpreter.AllLinesParser();
    if (!doScript(_getStatusCommand, interpreter)) {
        return new StartAnswer(cmd, "Cannot get current power status of " + getName());
    }
    if (isPowerOn(interpreter.getLines())) {
        if (!doScript(_rebootCommand)) {
            return new StartAnswer(cmd, "IPMI reboot failed");
        }
    } else {
        if (!doScript(_powerOnCommand)) {
            return new StartAnswer(cmd, "IPMI power on failed");
        }
    }
    if (_isEchoScAgent) {
        SecurityGroupHttpClient hc = new SecurityGroupHttpClient();
        boolean echoRet = hc.echo(vm.getNics()[0].getIp(), TimeUnit.MINUTES.toMillis(30), TimeUnit.MINUTES.toMillis(1));
        if (!echoRet) {
            return new StartAnswer(cmd, String.format("Call security group agent on vm[%s] timeout", vm.getNics()[0].getIp()));
        }
    }
    if (provisionDoneNotificationOn) {
        QueryBuilder<VMInstanceVO> q = QueryBuilder.create(VMInstanceVO.class);
        q.and(q.entity().getInstanceName(), SearchCriteria.Op.EQ, vm.getName());
        VMInstanceVO vmvo = q.find();
        if (vmvo.getLastHostId() == null) {
            // this is new created vm
            long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(isProvisionDoneNotificationTimeout);
            while (timeout > System.currentTimeMillis()) {
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    s_logger.warn(e.getMessage(), e);
                }
                q = QueryBuilder.create(VMInstanceVO.class);
                q.and(q.entity().getInstanceName(), SearchCriteria.Op.EQ, vm.getName());
                vmvo = q.find();
                if (vmvo == null) {
                    return new StartAnswer(cmd, String.format("cannot find vm[name:%s] while waiting for baremtal provision done notification", vm.getName()));
                }
                if (VirtualMachine.State.Running == vmvo.getState()) {
                    return new StartAnswer(cmd);
                }
                s_logger.debug(String.format("still wait for baremetal provision done notification for vm[name:%s], current vm state is %s", vmvo.getInstanceName(), vmvo.getState()));
            }
            return new StartAnswer(cmd, String.format("timeout after %s seconds, no baremetal provision done notification received. vm[name:%s] failed to start", isProvisionDoneNotificationTimeout, vm.getName()));
        }
    }
    s_logger.debug("Start bare metal vm " + vm.getName() + "successfully");
    _vmName = vm.getName();
    return new StartAnswer(cmd);
}
Also used : StartAnswer(com.cloud.agent.api.StartAnswer) VMInstanceVO(com.cloud.vm.VMInstanceVO) OutputInterpreter(com.cloud.utils.script.OutputInterpreter) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO)

Example 64 with VirtualMachineTO

use of com.cloud.agent.api.to.VirtualMachineTO in project cloudstack by apache.

the class VMwareGuru method implement.

@Override
public VirtualMachineTO implement(VirtualMachineProfile vm) {
    VirtualMachineTO to = toVirtualMachineTO(vm);
    to.setBootloader(BootloaderType.HVM);
    Map<String, String> details = to.getDetails();
    if (details == null)
        details = new HashMap<String, String>();
    Type vmType = vm.getType();
    boolean userVm = !(vmType.equals(VirtualMachine.Type.DomainRouter) || vmType.equals(VirtualMachine.Type.ConsoleProxy) || vmType.equals(VirtualMachine.Type.SecondaryStorageVm));
    String nicDeviceType = details.get(VmDetailConstants.NIC_ADAPTER);
    if (!userVm) {
        if (nicDeviceType == null) {
            details.put(VmDetailConstants.NIC_ADAPTER, _vmwareMgr.getSystemVMDefaultNicAdapterType());
        } else {
            try {
                VirtualEthernetCardType.valueOf(nicDeviceType);
            } catch (Exception e) {
                s_logger.warn("Invalid NIC device type " + nicDeviceType + " is specified in VM details, switch to default E1000");
                details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
            }
        }
    } else {
        // for user-VM, use E1000 as default
        if (nicDeviceType == null) {
            details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
        } else {
            try {
                VirtualEthernetCardType.valueOf(nicDeviceType);
            } catch (Exception e) {
                s_logger.warn("Invalid NIC device type " + nicDeviceType + " is specified in VM details, switch to default E1000");
                details.put(VmDetailConstants.NIC_ADAPTER, VirtualEthernetCardType.E1000.toString());
            }
        }
    }
    String diskDeviceType = details.get(VmDetailConstants.ROOT_DISK_CONTROLLER);
    if (userVm) {
        if (diskDeviceType == null) {
            details.put(VmDetailConstants.ROOT_DISK_CONTROLLER, _vmwareMgr.getRootDiskController());
        }
    }
    String diskController = details.get(VmDetailConstants.DATA_DISK_CONTROLLER);
    if (userVm) {
        if (diskController == null) {
            details.put(VmDetailConstants.DATA_DISK_CONTROLLER, DiskControllerType.lsilogic.toString());
        }
    }
    List<NicProfile> nicProfiles = vm.getNics();
    for (NicProfile nicProfile : nicProfiles) {
        if (nicProfile.getTrafficType() == TrafficType.Guest) {
            if (_networkMgr.isProviderSupportServiceInNetwork(nicProfile.getNetworkId(), Service.Firewall, Provider.CiscoVnmc)) {
                details.put("ConfigureVServiceInNexus", Boolean.TRUE.toString());
            }
            break;
        }
    }
    long clusterId = getClusterId(vm.getId());
    details.put(VmwareReserveCpu.key(), VmwareReserveCpu.valueIn(clusterId).toString());
    details.put(VmwareReserveMemory.key(), VmwareReserveMemory.valueIn(clusterId).toString());
    to.setDetails(details);
    if (vmType.equals(VirtualMachine.Type.DomainRouter)) {
        NicProfile publicNicProfile = null;
        for (NicProfile nicProfile : nicProfiles) {
            if (nicProfile.getTrafficType() == TrafficType.Public) {
                publicNicProfile = nicProfile;
                break;
            }
        }
        if (publicNicProfile != null) {
            NicTO[] nics = to.getNics();
            // reserve extra NICs
            NicTO[] expandedNics = new NicTO[nics.length + _vmwareMgr.getRouterExtraPublicNics()];
            int i = 0;
            int deviceId = -1;
            for (i = 0; i < nics.length; i++) {
                expandedNics[i] = nics[i];
                if (nics[i].getDeviceId() > deviceId)
                    deviceId = nics[i].getDeviceId();
            }
            deviceId++;
            long networkId = publicNicProfile.getNetworkId();
            NetworkVO network = _networkDao.findById(networkId);
            for (; i < nics.length + _vmwareMgr.getRouterExtraPublicNics(); i++) {
                NicTO nicTo = new NicTO();
                nicTo.setDeviceId(deviceId++);
                nicTo.setBroadcastType(publicNicProfile.getBroadcastType());
                nicTo.setType(publicNicProfile.getTrafficType());
                nicTo.setIp("0.0.0.0");
                nicTo.setNetmask("255.255.255.255");
                try {
                    String mac = _networkMgr.getNextAvailableMacAddressInNetwork(networkId);
                    nicTo.setMac(mac);
                } catch (InsufficientAddressCapacityException e) {
                    throw new CloudRuntimeException("unable to allocate mac address on network: " + networkId);
                }
                nicTo.setDns1(publicNicProfile.getIPv4Dns1());
                nicTo.setDns2(publicNicProfile.getIPv4Dns2());
                if (publicNicProfile.getIPv4Gateway() != null) {
                    nicTo.setGateway(publicNicProfile.getIPv4Gateway());
                } else {
                    nicTo.setGateway(network.getGateway());
                }
                nicTo.setDefaultNic(false);
                nicTo.setBroadcastUri(publicNicProfile.getBroadCastUri());
                nicTo.setIsolationuri(publicNicProfile.getIsolationUri());
                Integer networkRate = _networkMgr.getNetworkRate(network.getId(), null);
                nicTo.setNetworkRateMbps(networkRate);
                expandedNics[i] = nicTo;
            }
            to.setNics(expandedNics);
        }
        StringBuffer sbMacSequence = new StringBuffer();
        for (NicTO nicTo : sortNicsByDeviceId(to.getNics())) {
            sbMacSequence.append(nicTo.getMac()).append("|");
        }
        if (!sbMacSequence.toString().isEmpty()) {
            sbMacSequence.deleteCharAt(sbMacSequence.length() - 1);
            String bootArgs = to.getBootArgs();
            to.setBootArgs(bootArgs + " nic_macs=" + sbMacSequence.toString());
        }
    }
    // Should only be done on user machines
    if (userVm) {
        configureNestedVirtualization(details, to);
    }
    // Determine the VM's OS description
    GuestOSVO guestOS = _guestOsDao.findByIdIncludingRemoved(vm.getVirtualMachine().getGuestOSId());
    to.setOs(guestOS.getDisplayName());
    to.setHostName(vm.getHostName());
    HostVO host = _hostDao.findById(vm.getVirtualMachine().getHostId());
    GuestOSHypervisorVO guestOsMapping = null;
    if (host != null) {
        guestOsMapping = _guestOsHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), getHypervisorType().toString(), host.getHypervisorVersion());
    }
    if (guestOsMapping == null || host == null) {
        to.setPlatformEmulator(null);
    } else {
        to.setPlatformEmulator(guestOsMapping.getGuestOsName());
    }
    return to;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) HashMap(java.util.HashMap) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) GuestOSVO(com.cloud.storage.GuestOSVO) NicProfile(com.cloud.vm.NicProfile) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HostVO(com.cloud.host.HostVO) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) TrafficType(com.cloud.network.Networks.TrafficType) Type(com.cloud.vm.VirtualMachine.Type) DiskControllerType(com.cloud.hypervisor.vmware.mo.DiskControllerType) BootloaderType(com.cloud.template.VirtualMachineTemplate.BootloaderType) DataObjectType(com.cloud.agent.api.to.DataObjectType) BroadcastDomainType(com.cloud.network.Networks.BroadcastDomainType) VirtualEthernetCardType(com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NicTO(com.cloud.agent.api.to.NicTO)

Example 65 with VirtualMachineTO

use of com.cloud.agent.api.to.VirtualMachineTO in project cloudstack by apache.

the class LibvirtStartCommandWrapper method execute.

@Override
public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    vmSpec.setVncAddr(command.getHostIp());
    final String vmName = vmSpec.getName();
    LibvirtVMDef vm = null;
    DomainState state = DomainState.VIR_DOMAIN_SHUTOFF;
    final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
    Connect conn = null;
    try {
        vm = libvirtComputingResource.createVMFromSpec(vmSpec);
        conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType());
        Long remainingMem = getFreeMemory(conn, libvirtComputingResource);
        if (remainingMem == null) {
            return new StartAnswer(command, "failed to get free memory");
        } else if (remainingMem < vmSpec.getMinRam()) {
            return new StartAnswer(command, "Not enough memory on the host, remaining: " + remainingMem + ", asking: " + vmSpec.getMinRam());
        }
        final NicTO[] nics = vmSpec.getNics();
        for (final NicTO nic : nics) {
            if (vmSpec.getType() != VirtualMachine.Type.User) {
                nic.setPxeDisable(true);
            }
        }
        libvirtComputingResource.createVbd(conn, vmSpec, vmName, vm);
        if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)) {
            return new StartAnswer(command, "Failed to connect physical disks to host");
        }
        libvirtComputingResource.createVifs(vmSpec, vm);
        s_logger.debug("starting " + vmName + ": " + vm.toString());
        libvirtComputingResource.startVM(conn, vmName, vm.toString());
        for (final NicTO nic : nics) {
            if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                if (vmSpec.getType() != VirtualMachine.Type.User) {
                    libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, vmName);
                    break;
                } else {
                    final List<String> nicSecIps = nic.getNicSecIps();
                    String secIpsStr;
                    final StringBuilder sb = new StringBuilder();
                    if (nicSecIps != null) {
                        for (final String ip : nicSecIps) {
                            sb.append(ip).append(":");
                        }
                        secIpsStr = sb.toString();
                    } else {
                        secIpsStr = "0:";
                    }
                    libvirtComputingResource.defaultNetworkRules(conn, vmName, nic, vmSpec.getId(), secIpsStr);
                }
            }
        }
        // pass cmdline info to system vms
        if (vmSpec.getType() != VirtualMachine.Type.User) {
            //wait and try passCmdLine for 5 minutes at most for CLOUDSTACK-2823
            String controlIp = null;
            for (final NicTO nic : nics) {
                if (nic.getType() == TrafficType.Control) {
                    controlIp = nic.getIp();
                    break;
                }
            }
            for (int count = 0; count < 30; count++) {
                libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs());
                //check router is up?
                final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
                final boolean result = virtRouterResource.connect(controlIp, 1, 5000);
                if (result) {
                    break;
                }
            }
        }
        state = DomainState.VIR_DOMAIN_RUNNING;
        return new StartAnswer(command);
    } catch (final LibvirtException e) {
        s_logger.warn("LibvirtException ", e);
        if (conn != null) {
            libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
        }
        return new StartAnswer(command, e.getMessage());
    } catch (final InternalErrorException e) {
        s_logger.warn("InternalErrorException ", e);
        if (conn != null) {
            libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
        }
        return new StartAnswer(command, e.getMessage());
    } catch (final URISyntaxException e) {
        s_logger.warn("URISyntaxException ", e);
        if (conn != null) {
            libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
        }
        return new StartAnswer(command, e.getMessage());
    } finally {
        if (state != DomainState.VIR_DOMAIN_RUNNING) {
            storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
        }
    }
}
Also used : KVMStoragePoolManager(com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager) StartAnswer(com.cloud.agent.api.StartAnswer) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) VirtualRoutingResource(com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource) InternalErrorException(com.cloud.exception.InternalErrorException) URISyntaxException(java.net.URISyntaxException) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) LibvirtVMDef(com.cloud.hypervisor.kvm.resource.LibvirtVMDef) DomainState(org.libvirt.DomainInfo.DomainState) NicTO(com.cloud.agent.api.to.NicTO)

Aggregations

VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)84 NicTO (com.cloud.agent.api.to.NicTO)42 Test (org.junit.Test)33 Answer (com.cloud.agent.api.Answer)32 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)25 HashMap (java.util.HashMap)18 LibvirtException (org.libvirt.LibvirtException)18 StartAnswer (com.cloud.agent.api.StartAnswer)17 AttachAnswer (org.apache.cloudstack.storage.command.AttachAnswer)17 URISyntaxException (java.net.URISyntaxException)16 Connect (org.libvirt.Connect)16 InternalErrorException (com.cloud.exception.InternalErrorException)15 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)14 KVMStoragePoolManager (com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager)14 Connection (com.xensource.xenapi.Connection)14 ConfigurationException (javax.naming.ConfigurationException)14 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)13 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)13 StartCommand (com.cloud.agent.api.StartCommand)12 ArrayList (java.util.ArrayList)11