Search in sources :

Example 16 with NicTO

use of com.cloud.legacymodel.to.NicTO in project cosmic by MissionCriticalCloud.

the class NetworkOrchestrator method toNicTO.

protected NicTO toNicTO(final NicVO nic, final NicProfile profile, final NetworkVO config) {
    final NicTO to = new NicTO();
    to.setBroadcastType(config.getBroadcastDomainType());
    to.setType(config.getTrafficType());
    to.setIp(nic.getIPv4Address());
    to.setNetmask(nic.getIPv4Netmask());
    to.setMac(nic.getMacAddress());
    to.setDns1(profile.getIPv4Dns1());
    to.setDns2(profile.getIPv4Dns2());
    if (nic.getIPv4Gateway() != null) {
        to.setGateway(nic.getIPv4Gateway());
    } else {
        to.setGateway(config.getGateway());
    }
    to.setDefaultNic(nic.isDefaultNic());
    to.setBroadcastUri(nic.getBroadcastUri());
    to.setIsolationuri(nic.getIsolationUri());
    if (profile != null) {
        to.setDns1(profile.getIPv4Dns1());
        to.setDns2(profile.getIPv4Dns2());
    }
    final Integer networkRate = _networkModel.getNetworkRate(config.getId(), null);
    to.setNetworkRateMbps(networkRate);
    to.setUuid(config.getUuid());
    return to;
}
Also used : NicTO(com.cloud.legacymodel.to.NicTO)

Example 17 with NicTO

use of com.cloud.legacymodel.to.NicTO in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateRemoveNicFromVm.

private boolean orchestrateRemoveNicFromVm(final VirtualMachine vm, final Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
    final CallContext cctx = CallContext.current();
    final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
    final NetworkVO network = _networkDao.findById(nic.getNetworkId());
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
    final Zone zone = _zoneRepository.findById(network.getDataCenterId()).orElse(null);
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(zone, null, null, host);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
    final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
    final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
    // 1) Unplug the nic
    if (vm.getState() == State.Running) {
        final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
        s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network);
        final boolean result = unplugNic(network, nicTO, vmTO, context, dest);
        if (result) {
            s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
            final long isDefault = nic.isDefaultNic() ? 1 : 0;
        } else {
            s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
            return false;
        }
    } else if (vm.getState() != State.Stopped) {
        s_logger.warn("Unable to remove vm " + vm + " from network  " + network);
        throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
    }
    // 2) Release the nic
    _networkMgr.releaseNic(vmProfile, nic);
    s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
    // 3) Remove the nic
    _networkMgr.removeNic(vmProfile, nic);
    _nicsDao.expunge(nic.getId());
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) Host(com.cloud.legacymodel.dc.Host) CallContext(com.cloud.context.CallContext) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DataCenter(com.cloud.legacymodel.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) NicTO(com.cloud.legacymodel.to.NicTO)

Example 18 with NicTO

use of com.cloud.legacymodel.to.NicTO in project cosmic by MissionCriticalCloud.

the class CitrixResourceBase method prepareNetworkElementCommand.

protected ExecutionResult prepareNetworkElementCommand(final SetNetworkACLCommand cmd) {
    final Connection conn = getConnection();
    final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
    try {
        final VM router = getVM(conn, routerName);
        final NicTO nic = cmd.getNic();
        if (nic != null) {
            final VIF vif = getVifByMac(conn, router, nic.getMac());
            if (vif == null) {
                final String msg = "Prepare SetNetworkACL failed due to VIF is null for : " + nic.getMac() + " with routername: " + routerName;
                s_logger.error(msg);
                return new ExecutionResult(false, msg);
            }
        } else {
            final String msg = "Prepare SetNetworkACL failed due to nic is null for : " + routerName;
            s_logger.error(msg);
            return new ExecutionResult(false, msg);
        }
    } catch (final Exception e) {
        final String msg = "Prepare SetNetworkACL failed due to " + e.toString();
        s_logger.error(msg, e);
        return new ExecutionResult(false, msg);
    }
    return new ExecutionResult(true, null);
}
Also used : VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM) Connection(com.xensource.xenapi.Connection) URLConnection(java.net.URLConnection) ExecutionResult(com.cloud.legacymodel.ExecutionResult) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) SAXException(org.xml.sax.SAXException) ConfigurationException(javax.naming.ConfigurationException) MalformedURLException(java.net.MalformedURLException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NicTO(com.cloud.legacymodel.to.NicTO)

Example 19 with NicTO

use of com.cloud.legacymodel.to.NicTO in project cosmic by MissionCriticalCloud.

the class HypervisorGuruBase method toVirtualMachineTO.

protected VirtualMachineTO toVirtualMachineTO(final VirtualMachineProfile vmProfile) {
    final ServiceOffering offering = _serviceOfferingDao.findById(vmProfile.getId(), vmProfile.getServiceOfferingId());
    final VirtualMachine vm = vmProfile.getVirtualMachine();
    final Long minMemory = (long) (offering.getRamSize() / vmProfile.getMemoryOvercommitRatio());
    final VirtualMachineTO to = new VirtualMachineTO(vm.getId(), vm.getInstanceName(), vm.getType(), offering.getCpu(), minMemory * 1024l * 1024l, offering.getRamSize() * 1024l * 1024l, null, null, vm.isHaEnabled(), vm.limitCpuUse(), vm.getVncPassword());
    to.setBootArgs(vmProfile.getBootArgs());
    final List<NicProfile> nicProfiles = vmProfile.getNics();
    final NicTO[] nics = new NicTO[nicProfiles.size()];
    int i = 0;
    List<Long> vpcList = new ArrayList<>();
    for (final NicProfile nicProfile : nicProfiles) {
        nics[i++] = toNicTO(nicProfile);
        if (TrafficType.Guest.equals(nicProfile.getTrafficType())) {
            final NetworkVO network = _networkDao.findById(nicProfile.getNetworkId());
            final Long vpcId = network.getVpcId();
            if (vpcId != null) {
                vpcList.add(network.getVpcId());
            }
        }
    }
    to.setNics(nics);
    to.setDisks(vmProfile.getDisks().toArray(new DiskTO[vmProfile.getDisks().size()]));
    if (vmProfile.getTemplate().getBits() == 32) {
        to.setArch("i686");
    } else {
        to.setArch("x86_64");
    }
    final Map<String, String> detailsInVm = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
    if (detailsInVm != null) {
        to.setDetails(detailsInVm);
    }
    // Set GPU details
    ServiceOfferingDetailsVO offeringDetail;
    if ((offeringDetail = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.vgpuType.toString())) != null) {
        final ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.pciDevice.toString());
        to.setGpuDevice(_resourceMgr.getGPUDevice(vm.getHostId(), groupName.getValue(), offeringDetail.getValue()));
    }
    // Workaround to make sure the TO has the UUID we need for Niciri integration
    final VMInstanceVO vmInstance = _virtualMachineDao.findById(to.getId());
    // check if XStools tools are present in the VM and dynamic scaling feature is enabled (per zone/global)
    final Boolean isDynamicallyScalable = vmInstance.isDynamicallyScalable() && UserVmManager.EnableDynamicallyScaleVm.valueIn(vm.getDataCenterId());
    to.setEnableDynamicallyScaleVm(isDynamicallyScalable);
    to.setUuid(vmInstance.getUuid());
    to.setManufacturer(vmInstance.getManufacturerString());
    to.setOptimiseFor(vmInstance.getOptimiseFor());
    to.setMaintenancePolicy(vmInstance.getMaintenancePolicy());
    to.setBootMenuTimeout(vmInstance.getBootMenuTimeout());
    to.setLastStartVersion(vmInstance.getLastStartVersion());
    to.setLastStartDateTime(vmInstance.getLastStartDateTime());
    to.setVmData(vmProfile.getVmData());
    to.setConfigDriveLabel(vmProfile.getConfigDriveLabel());
    to.setConfigDriveIsoRootFolder(vmProfile.getConfigDriveIsoRootFolder());
    to.setConfigDriveIsoFile(vmProfile.getConfigDriveIsoFile());
    LinkedHashSet<BootOrder> order = new LinkedHashSet<>();
    if (vmInstance.getBootOrder() != null) {
        for (final String dev : vmInstance.getBootOrder().split(",")) {
            order.add(BootOrder.stringToEnum(dev));
        }
    } else {
        // If bootorder column in DB is empty do default behaviour
        order.add(BootOrder.CDROM);
        order.add(BootOrder.HARDDISK);
    }
    to.setBootOrder(new ArrayList<>(order));
    final MetadataTO metadataTO = new MetadataTO();
    final DomainVO domain = _domainDao.findById(vm.getDomainId());
    metadataTO.setDomainUuid(domain.getUuid());
    metadataTO.setCosmicDomainName(domain.getName());
    metadataTO.setCosmicDomainPath(domain.getPath());
    metadataTO.setInstanceName(vm.getInstanceName());
    metadataTO.setVmId(vm.getId());
    metadataTO.setHostname(vm.getHostName());
    final Map<String, String> resourceDetails = ApiDBUtils.getResourceDetails(vm.getId(), ResourceTag.ResourceObjectType.UserVm);
    final Map<String, String> resourceTags = new HashMap<String, String>();
    final List<String> vpcNameList = new LinkedList<>();
    if (VirtualMachineType.User.equals(vm.getType())) {
        final List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(ResourceTag.ResourceObjectType.UserVm, vm.getId());
        for (final ResourceTag tag : tags) {
            resourceTags.put("instance_" + tag.getKey(), tag.getValue());
        }
    }
    for (final Long vpcId : vpcList) {
        final VpcVO vpc = _vpcDao.findById(vpcId);
        if (vpc != null) {
            vpcNameList.add(vpc.getName());
        }
        final List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(ResourceTag.ResourceObjectType.Vpc, vpcId);
        for (final ResourceTag tag : tags) {
            if (tag != null) {
                resourceTags.put("vpc_" + tag.getKey(), tag.getValue());
            }
        }
    }
    metadataTO.setResourceDetails(resourceDetails);
    metadataTO.setResourceTags(resourceTags);
    metadataTO.setVpcNameList(vpcNameList);
    to.setMetadata(metadataTO);
    return to;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) BootOrder(com.cloud.model.enumeration.BootOrder) MetadataTO(com.cloud.legacymodel.to.MetadataTO) ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) NicTO(com.cloud.legacymodel.to.NicTO) NetworkVO(com.cloud.network.dao.NetworkVO) ServiceOffering(com.cloud.offering.ServiceOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO) NicProfile(com.cloud.vm.NicProfile) LinkedList(java.util.LinkedList) DomainVO(com.cloud.domain.DomainVO) VpcVO(com.cloud.network.vpc.VpcVO) ResourceTag(com.cloud.server.ResourceTag) VirtualMachine(com.cloud.legacymodel.vm.VirtualMachine) DiskTO(com.cloud.legacymodel.to.DiskTO)

Example 20 with NicTO

use of com.cloud.legacymodel.to.NicTO in project cosmic by MissionCriticalCloud.

the class XenServer610MigrateWithStorageSendCommandWrapper method execute.

@Override
public Answer execute(final MigrateWithStorageSendCommand command, final XenServer610Resource xenServer610Resource) {
    final Connection connection = xenServer610Resource.getConnection();
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final List<Pair<VolumeTO, Object>> volumeToSr = command.getVolumeToSr();
    final List<Pair<NicTO, Object>> nicToNetwork = command.getNicToNetwork();
    final Map<String, String> token = command.getToken();
    final String vmName = vmSpec.getName();
    Task task = null;
    try {
        // In a cluster management server setup, the migrate with storage receive and send
        // commands and answers may have to be forwarded to another management server. This
        // happens when the host/resource on which the command has to be executed is owned
        // by the second management server. The serialization/deserialization of the command
        // and answers fails as the xapi SR and Network class type isn't understand by the
        // agent attache. Seriliaze the SR and Network objects here to a string and pass in
        // the answer object. It'll be deserialzed and object created in migrate with
        // storage send command execution.
        final Gson gson = new Gson();
        final Map<String, String> other = new HashMap<>();
        other.put("live", "true");
        // Create the vdi map which tells what volumes of the vm need to go
        // on which sr on the destination.
        final Map<VDI, SR> vdiMap = new HashMap<>();
        for (final Pair<VolumeTO, Object> entry : volumeToSr) {
            if (entry.second() instanceof SR) {
                final SR sr = (SR) entry.second();
                final VDI vdi = xenServer610Resource.getVDIbyUuid(connection, entry.first().getPath());
                vdiMap.put(vdi, sr);
            } else {
                throw new CloudRuntimeException("The object " + entry.second() + " passed is not of type SR.");
            }
        }
        final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
        VM vmToMigrate = null;
        if (vms != null) {
            vmToMigrate = vms.iterator().next();
        }
        // Create the vif map.
        final Map<VIF, Network> vifMap = new HashMap<>();
        for (final Pair<NicTO, Object> entry : nicToNetwork) {
            if (entry.second() instanceof Network) {
                final Network network = (Network) entry.second();
                final VIF vif = xenServer610Resource.getVifByMac(connection, vmToMigrate, entry.first().getMac());
                vifMap.put(vif, network);
            } else {
                throw new CloudRuntimeException("The object " + entry.second() + " passed is not of type Network.");
            }
        }
        // Check migration with storage is possible.
        task = vmToMigrate.assertCanMigrateAsync(connection, token, true, vdiMap, vifMap, other);
        try {
            // poll every 1 seconds.
            final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
            xenServer610Resource.waitForTask(connection, task, 1000, timeout);
            xenServer610Resource.checkForSuccess(connection, task);
        } catch (final Types.HandleInvalid e) {
            s_logger.error("Error while checking if vm " + vmName + " can be migrated.", e);
            throw new CloudRuntimeException("Error while checking if vm " + vmName + " can be migrated.", e);
        }
        // Migrate now.
        task = vmToMigrate.migrateSendAsync(connection, token, true, vdiMap, vifMap, other);
        try {
            // poll every 1 seconds.
            final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
            xenServer610Resource.waitForTask(connection, task, 1000, timeout);
            xenServer610Resource.checkForSuccess(connection, task);
        } catch (final Types.HandleInvalid e) {
            s_logger.error("Error while migrating vm " + vmName, e);
            throw new CloudRuntimeException("Error while migrating vm " + vmName, e);
        }
        final Set<VolumeTO> volumeToSet = null;
        return new MigrateWithStorageSendAnswer(command, volumeToSet);
    } catch (final CloudRuntimeException e) {
        s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
        return new MigrateWithStorageSendAnswer(command, e);
    } catch (final Exception e) {
        s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
        return new MigrateWithStorageSendAnswer(command, e);
    } finally {
        if (task != null) {
            try {
                task.destroy(connection);
            } catch (final Exception e) {
                s_logger.debug("Unable to destroy task " + task.toString() + " on host " + xenServer610Resource.getHost().getUuid() + " due to " + e.toString());
            }
        }
    }
}
Also used : Types(com.xensource.xenapi.Types) Task(com.xensource.xenapi.Task) MigrateWithStorageSendAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageSendAnswer) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) VolumeTO(com.cloud.legacymodel.to.VolumeTO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.xensource.xenapi.Network) VDI(com.xensource.xenapi.VDI) Pair(com.cloud.legacymodel.utils.Pair) SR(com.xensource.xenapi.SR) NicTO(com.cloud.legacymodel.to.NicTO) Connection(com.xensource.xenapi.Connection) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM)

Aggregations

NicTO (com.cloud.legacymodel.to.NicTO)51 VirtualMachineTO (com.cloud.legacymodel.to.VirtualMachineTO)28 Answer (com.cloud.legacymodel.communication.answer.Answer)26 Test (org.junit.Test)25 LibvirtException (org.libvirt.LibvirtException)23 AttachAnswer (com.cloud.legacymodel.communication.answer.AttachAnswer)21 LibvirtRequestWrapper (com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper)19 LibvirtUtilitiesHelper (com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper)19 CheckRouterAnswer (com.cloud.legacymodel.communication.answer.CheckRouterAnswer)19 Connect (org.libvirt.Connect)19 ArrayList (java.util.ArrayList)16 KvmStoragePoolManager (com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager)14 Connection (com.xensource.xenapi.Connection)14 InternalErrorException (com.cloud.legacymodel.exceptions.InternalErrorException)11 URISyntaxException (java.net.URISyntaxException)11 VifDriver (com.cloud.agent.resource.kvm.vif.VifDriver)10 LibvirtVmDef (com.cloud.agent.resource.kvm.xml.LibvirtVmDef)10 Host (com.cloud.legacymodel.dc.Host)10 UnPlugNicCommand (com.cloud.legacymodel.communication.command.UnPlugNicCommand)9 HashMap (java.util.HashMap)8