Search in sources :

Example 11 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method createVirtualMachine.

@DB
private UserVm createVirtualMachine(final Zone zone, final ServiceOffering serviceOffering, final VirtualMachineTemplate tmplt, String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final List<NetworkVO> networkList, final String group, final HTTPMethod httpmethod, final String userData, final String sshKeyPair, final HypervisorType hypervisor, final Account caller, final Map<Long, IpAddresses> requestedIps, final IpAddresses defaultIps, final Boolean isDisplayVm, final String keyboard, final List<Long> affinityGroupIdList, final Map<String, String> customParameters, final String customId, final DiskControllerType diskControllerType, final Long bootMenuTimeout, MaintenancePolicy maintenancePolicy, OptimiseFor optimiseFor, String manufacturerString, String bootOrder) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    _accountMgr.checkAccess(caller, null, true, owner);
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
    }
    final VMTemplateVO template = _templateDao.findById(tmplt.getId());
    if (template != null) {
        _templateDao.loadDetails(template);
    }
    if (optimiseFor == null) {
        if (template.getOptimiseFor() != null) {
            optimiseFor = template.getOptimiseFor();
        } else {
            optimiseFor = OptimiseFor.Generic;
        }
    }
    if (manufacturerString == null) {
        manufacturerString = template.getManufacturerString();
    }
    if (maintenancePolicy == null) {
        maintenancePolicy = template.getMaintenancePolicy();
    }
    Boolean macLarning = template.getMacLearning();
    String cpuFlags = template.getCpuFlags();
    final long accountId = owner.getId();
    assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be " + "specified together";
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
    }
    // check if zone is dedicated
    final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
    if (dedicatedZone != null) {
        final DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
        if (domain == null) {
            throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
        }
        // check that caller can operate with domain
        _configMgr.checkZoneAccess(caller, zone);
        // check that vm owner can create vm in the domain
        _configMgr.checkZoneAccess(owner, zone);
    }
    ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
    // check if account/domain is with in resource limits to create a new vm
    final boolean isIso = ImageFormat.ISO == template.getFormat();
    long size = 0;
    // custom root disk size, resizes base template to larger size
    if (customParameters.containsKey("rootdisksize")) {
        final Long rootDiskSize = NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1);
        if (rootDiskSize <= 0) {
            throw new InvalidParameterValueException("Root disk size should be a positive number.");
        }
        size = rootDiskSize * GB_TO_BYTES;
    }
    if (diskOfferingId != null) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        if (diskOffering != null && diskOffering.isCustomized()) {
            if (diskSize == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            final Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
            final Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
            if (diskSize < customDiskOfferingMinSize || diskSize > customDiskOfferingMaxSize) {
                throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
            size += diskSize * GB_TO_BYTES;
        }
        size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
    }
    resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, isIso || diskOfferingId == null ? 1 : 2);
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
    // check that the affinity groups exist
    if (affinityGroupIdList != null) {
        for (final Long affinityGroupId : affinityGroupIdList) {
            final AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
            if (ag == null) {
                throw new InvalidParameterValueException("Unable to find affinity group " + ag);
            } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
                throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
            } else {
                // verify permissions
                if (ag.getAclType() == ACLType.Domain) {
                    _accountMgr.checkAccess(caller, null, false, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                } else {
                    _accountMgr.checkAccess(caller, null, true, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (ag.getDomainId() != owner.getDomainId()) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                }
            }
        }
    }
    final HypervisorType hypervisorType;
    if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
        if (hypervisor == null || hypervisor == HypervisorType.None) {
            throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
        }
        hypervisorType = hypervisor;
    } else {
        if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
            throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
        }
        hypervisorType = template.getHypervisorType();
    }
    // check if we have available pools for vm deployment
    final long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
    if (availablePools < 1) {
        throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
    }
    if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
        throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
    }
    final List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
    if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
        throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
    }
    if (isIso && !template.isBootable()) {
        throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
    }
    // Check templates permissions
    _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
    // check if the user data is correct
    validateUserData(userData, httpmethod);
    // Find an SSH public key corresponding to the key pair name, if one is
    // given
    String sshPublicKey = null;
    if (sshKeyPair != null && !sshKeyPair.equals("")) {
        final SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
        if (pair == null) {
            throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
        }
        sshPublicKey = pair.getPublicKey();
    }
    final List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<>();
    final LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<>();
    short defaultNetworkNumber = 0;
    boolean vpcNetwork = false;
    for (final NetworkVO network : networkList) {
        if (network.getDataCenterId() != zone.getId()) {
            if (!network.isStrechedL2Network()) {
                throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
            }
            final NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
            final Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
            if (physicalNetworkId == null) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
            final String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
            if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
        }
        // relax the check if the caller is admin account
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            if (!(network.getGuestType() == GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
                throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
            }
        }
        IpAddresses requestedIpPair = null;
        if (requestedIps != null && !requestedIps.isEmpty()) {
            requestedIpPair = requestedIps.get(network.getId());
        }
        if (requestedIpPair == null) {
            requestedIpPair = new IpAddresses(null, null);
        } else {
            _networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair);
        }
        NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());
        if (defaultNetworkNumber == 0) {
            defaultNetworkNumber++;
            // if user requested specific ip for default network, add it
            if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
                _networkModel.checkRequestedIpAddresses(network.getId(), defaultIps);
                profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
            } else if (defaultIps.getMacAddress() != null) {
                profile = new NicProfile(null, null, defaultIps.getMacAddress());
            }
            profile.setDefaultNic(true);
            if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
                if (userData != null && !userData.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (sshPublicKey != null && !sshPublicKey.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (template.getEnablePassword()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
            }
        }
        networks.add(new Pair<>(network, profile));
        networkNicMap.put(network.getUuid(), profile);
    }
    // gateway for the vm
    if (defaultNetworkNumber == 0) {
        throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
    } else if (defaultNetworkNumber > 1) {
        throw new InvalidParameterValueException("Only 1 default network per vm is supported");
    }
    final long id = _vmDao.getNextInSequence(Long.class, "id");
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    final String instanceName;
    final String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (hostName == null) {
        // Generate name using uuid and instance.name global config
        hostName = generateHostName(uuidName);
    }
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
    // Check if VM with instanceName already exists.
    final VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
    if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
        throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
    }
    checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
    long userId = CallContext.current().getCallingUserId();
    if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
        final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
        if (!userVOs.isEmpty()) {
            userId = userVOs.get(0).getId();
        }
    }
    final UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, diskControllerType, manufacturerString, optimiseFor, macLarning, cpuFlags, maintenancePolicy, bootMenuTimeout, bootOrder);
    // Assign instance to the group
    try {
        if (group != null) {
            final boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
            if (!addToGroup) {
                throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
            }
        }
    } catch (final Exception ex) {
        throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
    }
    if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
        _affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
    }
    CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
    return vm;
}
Also used : VMTemplateZoneVO(com.cloud.storage.VMTemplateZoneVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) Pair(com.cloud.legacymodel.utils.Pair) AffinityGroupVO(com.cloud.affinity.AffinityGroupVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) AccountService(com.cloud.user.AccountService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(com.cloud.legacymodel.network.Network.Service) OrchestrationService(com.cloud.engine.service.api.OrchestrationService) ExecutorService(java.util.concurrent.ExecutorService) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) VolumeOrchestrationService(com.cloud.engine.orchestration.service.VolumeOrchestrationService) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) CloudException(com.cloud.legacymodel.exceptions.CloudException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ManagementServerException(com.cloud.legacymodel.exceptions.ManagementServerException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) IpAddresses(com.cloud.legacymodel.network.Network.IpAddresses) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 12 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class CloudOrchestrator method createVirtualMachine.

@Override
public void createVirtualMachine(final String id, final String owner, final String templateId, final String hostName, final String displayName, final String hypervisor, final int cpu, final long memory, final Long diskSize, final List<String> computeTags, final List<String> rootDiskTags, final Map<String, NicProfile> networkNicMap, final DeploymentPlan plan, final Long rootDiskSize, final DiskControllerType diskControllerType) throws InsufficientCapacityException {
    final LinkedHashMap<NetworkVO, List<? extends NicProfile>> networkIpMap = new LinkedHashMap<>();
    for (final String uuid : networkNicMap.keySet()) {
        final NetworkVO network = _networkDao.findByUuid(uuid);
        if (network != null) {
            networkIpMap.put(network, new ArrayList<>(Arrays.asList(networkNicMap.get(uuid))));
        }
    }
    final VirtualMachineEntityImpl vmEntity = ComponentContext.inject(VirtualMachineEntityImpl.class);
    vmEntity.init(id, owner, hostName, displayName, computeTags, rootDiskTags, new ArrayList<>(networkNicMap.keySet()));
    final HypervisorType hypervisorType = HypervisorType.valueOf(hypervisor);
    // load vm instance and offerings and call virtualMachineManagerImpl
    final VMInstanceVO vm = _vmDao.findByUuid(id);
    // If the template represents an ISO, a disk offering must be passed in, and will be used to create the root disk
    // Else, a disk offering is optional, and if present will be used to create the data disk
    final DiskOfferingInfo rootDiskOfferingInfo = new DiskOfferingInfo();
    final List<DiskOfferingInfo> dataDiskOfferings = new ArrayList<>();
    final ServiceOfferingVO computeOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
    rootDiskOfferingInfo.setDiskOffering(computeOffering);
    rootDiskOfferingInfo.setSize(rootDiskSize);
    if (computeOffering.isCustomizedIops() != null && computeOffering.isCustomizedIops()) {
        final Map<String, String> userVmDetails = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
        if (userVmDetails != null) {
            final String minIops = userVmDetails.get("minIops");
            final String maxIops = userVmDetails.get("maxIops");
            rootDiskOfferingInfo.setMinIops(minIops != null && minIops.trim().length() > 0 ? Long.parseLong(minIops) : null);
            rootDiskOfferingInfo.setMaxIops(maxIops != null && maxIops.trim().length() > 0 ? Long.parseLong(maxIops) : null);
        }
    }
    if (vm.getDiskOfferingId() != null) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(vm.getDiskOfferingId());
        if (diskOffering == null) {
            throw new InvalidParameterValueException("Unable to find disk offering " + vm.getDiskOfferingId());
        }
        Long size = null;
        if (diskOffering.getDiskSize() == 0) {
            size = diskSize;
            if (size == null) {
                throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter.");
            }
            _volumeMgr.validateVolumeSizeRange(size * 1024 * 1024 * 1024);
        }
        final DiskOfferingInfo dataDiskOfferingInfo = new DiskOfferingInfo();
        dataDiskOfferingInfo.setDiskOffering(diskOffering);
        dataDiskOfferingInfo.setSize(size);
        dataDiskOfferingInfo.setDiskControllerType(diskControllerType);
        if (diskOffering.isCustomizedIops() != null && diskOffering.isCustomizedIops()) {
            final Map<String, String> userVmDetails = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
            if (userVmDetails != null) {
                final String minIops = userVmDetails.get("minIopsDo");
                final String maxIops = userVmDetails.get("maxIopsDo");
                dataDiskOfferingInfo.setMinIops(minIops != null && minIops.trim().length() > 0 ? Long.parseLong(minIops) : null);
                dataDiskOfferingInfo.setMaxIops(maxIops != null && maxIops.trim().length() > 0 ? Long.parseLong(maxIops) : null);
            }
        }
        dataDiskOfferings.add(dataDiskOfferingInfo);
    }
    _itMgr.allocate(vm.getInstanceName(), _templateDao.findById(new Long(templateId)), computeOffering, rootDiskOfferingInfo, dataDiskOfferings, networkIpMap, plan, hypervisorType, diskControllerType);
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) NicProfile(com.cloud.vm.NicProfile) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VirtualMachineEntityImpl(com.cloud.engine.cloud.entity.api.VirtualMachineEntityImpl) LinkedHashMap(java.util.LinkedHashMap) HypervisorType(com.cloud.model.enumeration.HypervisorType) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) ArrayList(java.util.ArrayList) List(java.util.List) DiskOfferingInfo(com.cloud.offering.DiskOfferingInfo)

Example 13 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class NetworkOrchestrator method processConnect.

@Override
public void processConnect(final Host host, final StartupCommand[] startupCommands, final boolean forRebalance) throws ConnectionException {
    for (final StartupCommand startupCommand : startupCommands) {
        if (!(startupCommand instanceof StartupRoutingCommand)) {
            return;
        }
        final long hostId = host.getId();
        final StartupRoutingCommand startup = (StartupRoutingCommand) startupCommand;
        final String dataCenter = startup.getDataCenter();
        long dcId = -1;
        Zone dc = _zoneRepository.findByName(dataCenter);
        if (dc == null) {
            try {
                dcId = Long.parseLong(dataCenter);
                dc = _zoneRepository.findById(dcId).orElse(null);
            } catch (final NumberFormatException e) {
            }
        }
        if (dc == null) {
            throw new IllegalArgumentException("Host " + startup.getPrivateIpAddress() + " sent incorrect data center: " + dataCenter);
        }
        dcId = dc.getId();
        final HypervisorType hypervisorType = startup.getHypervisorType();
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Host's hypervisorType is: " + hypervisorType);
        }
        final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<>();
        // list all physicalnetworks in the zone & for each get the network names
        final List<PhysicalNetworkVO> physicalNtwkList = _physicalNetworkDao.listByZone(dcId);
        for (final PhysicalNetworkVO pNtwk : physicalNtwkList) {
            final String publicName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Public, hypervisorType);
            final String privateName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Management, hypervisorType);
            final String guestName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Guest, hypervisorType);
            final String storageName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Storage, hypervisorType);
            // String controlName = _pNTrafficTypeDao._networkModel.getNetworkTag(pNtwk.getId(), TrafficType.Control, hypervisorType);
            final PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo();
            info.setPhysicalNetworkId(pNtwk.getId());
            info.setGuestNetworkName(guestName);
            info.setPrivateNetworkName(privateName);
            info.setPublicNetworkName(publicName);
            info.setStorageNetworkName(storageName);
            final PhysicalNetworkTrafficTypeVO mgmtTraffic = _pNTrafficTypeDao.findBy(pNtwk.getId(), TrafficType.Management);
            if (mgmtTraffic != null) {
                final String vlan = mgmtTraffic.getVlan();
                info.setMgmtVlan(vlan);
            }
            networkInfoList.add(info);
        }
        // send the names to the agent
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Sending CheckNetworkCommand to check the Network is setup correctly on Agent");
        }
        final CheckNetworkCommand nwCmd = new CheckNetworkCommand(networkInfoList);
        final CheckNetworkAnswer answer = (CheckNetworkAnswer) _agentMgr.easySend(hostId, nwCmd);
        if (answer == null) {
            s_logger.warn("Unable to get an answer to the CheckNetworkCommand from agent:" + host.getId());
            throw new ConnectionException(true, "Unable to get an answer to the CheckNetworkCommand from agent: " + host.getId());
        }
        if (!answer.getResult()) {
            s_logger.warn("Unable to setup agent " + hostId + " due to " + answer.getDetails());
            final String msg = "Incorrect Network setup on agent, Reinitialize agent after network names are setup, details : " + answer.getDetails();
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, host.getPodId(), msg, msg);
            throw new ConnectionException(true, msg);
        } else {
            if (answer.needReconnect()) {
                throw new ConnectionException(false, "Reinitialize agent after network setup.");
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Network setup is correct on Agent");
            }
            return;
        }
    }
}
Also used : Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) CheckNetworkAnswer(com.cloud.legacymodel.communication.answer.CheckNetworkAnswer) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) StartupCommand(com.cloud.legacymodel.communication.command.startup.StartupCommand) HypervisorType(com.cloud.model.enumeration.HypervisorType) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) CheckNetworkCommand(com.cloud.legacymodel.communication.command.CheckNetworkCommand) StartupRoutingCommand(com.cloud.legacymodel.communication.command.startup.StartupRoutingCommand) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) PhysicalNetworkSetupInfo(com.cloud.legacymodel.network.PhysicalNetworkSetupInfo)

Example 14 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class SecondaryStorageManagerImpl method createSecStorageVmInstance.

protected Map<String, Object> createSecStorageVmInstance(final long dataCenterId, final SecondaryStorageVmRole role) {
    final DataStore secStore = this._dataStoreMgr.getImageStore(dataCenterId);
    if (secStore == null) {
        final String msg = "No secondary storage available in zone " + dataCenterId + ", cannot create secondary storage vm";
        logger.warn(msg);
        throw new CloudRuntimeException(msg);
    }
    final long id = this._secStorageVmDao.getNextInSequence(Long.class, "id");
    final String name = VirtualMachineName.getSystemVmName(id, this._instance, "s").intern();
    final Account systemAcct = this._accountMgr.getSystemAccount();
    final DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
    final Zone zone = this.zoneRepository.findById(plan.getDataCenterId()).orElse(null);
    final NetworkVO defaultNetwork = getDefaultNetworkForCreation(zone);
    final List<? extends NetworkOffering> offerings;
    if (this._sNwMgr.isStorageIpRangeAvailable(dataCenterId)) {
        offerings = this._networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork, NetworkOffering.SystemStorageNetwork);
    } else {
        offerings = this._networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
    }
    final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>(offerings.size() + 1);
    final NicProfile defaultNic = new NicProfile();
    defaultNic.setDefaultNic(true);
    try {
        networks.put(this._networkMgr.setupNetwork(systemAcct, this._networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0), new ArrayList<>(Arrays.asList(defaultNic)));
        for (final NetworkOffering offering : offerings) {
            networks.put(this._networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<>());
        }
    } catch (final ConcurrentOperationException e) {
        logger.info("Unable to setup due to concurrent operation.", e);
        return new HashMap<>();
    }
    final HypervisorType availableHypervisor = this._resourceMgr.getAvailableHypervisor(dataCenterId);
    final String templateName = retrieveTemplateName(dataCenterId);
    final VMTemplateVO template = this._templateDao.findRoutingTemplate(availableHypervisor, templateName, dataCenterId);
    if (template == null) {
        throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
    }
    ServiceOfferingVO serviceOffering = this._serviceOffering;
    if (serviceOffering == null) {
        serviceOffering = this._offeringDao.findDefaultSystemOffering(ServiceOffering.ssvmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
    }
    SecondaryStorageVmVO secStorageVm = new SecondaryStorageVmVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId(), this._accountMgr.getSystemUser().getId(), role, serviceOffering.getOfferHA(), template.getOptimiseFor(), template.getManufacturerString(), template.getCpuFlags(), template.getMacLearning(), false, template.getMaintenancePolicy());
    secStorageVm.setDynamicallyScalable(template.isDynamicallyScalable());
    secStorageVm = this._secStorageVmDao.persist(secStorageVm);
    try {
        this._itMgr.allocate(name, template, serviceOffering, networks, plan, null);
        secStorageVm = this._secStorageVmDao.findById(secStorageVm.getId());
    } catch (final InsufficientCapacityException e) {
        logger.warn("InsufficientCapacity", e);
        throw new CloudRuntimeException("Insufficient capacity exception", e);
    }
    final Map<String, Object> context = new HashMap<>();
    context.put("secStorageVmId", secStorageVm.getId());
    return context;
}
Also used : Account(com.cloud.legacymodel.user.Account) SecondaryStorageVmVO(com.cloud.vm.SecondaryStorageVmVO) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) Network(com.cloud.legacymodel.network.Network) ArrayList(java.util.ArrayList) List(java.util.List) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) NetworkVO(com.cloud.network.dao.NetworkVO) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) NetworkOffering(com.cloud.offering.NetworkOffering) Zone(com.cloud.db.model.Zone) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) HypervisorType(com.cloud.model.enumeration.HypervisorType)

Example 15 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class StorageManagerImpl method createPool.

@Override
public PrimaryDataStoreInfo createPool(final CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException {
    final String providerName = cmd.getStorageProviderName();
    DataStoreProvider storeProvider = this._dataStoreProviderMgr.getDataStoreProvider(providerName);
    if (storeProvider == null) {
        storeProvider = this._dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider();
        if (storeProvider == null) {
            throw new InvalidParameterValueException("can't find storage provider: " + providerName);
        }
    }
    Long clusterId = cmd.getClusterId();
    Long podId = cmd.getPodId();
    final Long zoneId = cmd.getZoneId();
    ScopeType scopeType = ScopeType.CLUSTER;
    final String scope = cmd.getScope();
    if (scope != null) {
        try {
            scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase());
        } catch (final Exception e) {
            throw new InvalidParameterValueException("invalid scope for pool " + scope);
        }
    }
    if (scopeType == ScopeType.CLUSTER && clusterId == null) {
        throw new InvalidParameterValueException("cluster id can't be null, if scope is cluster");
    } else if (scopeType == ScopeType.ZONE && zoneId == null) {
        throw new InvalidParameterValueException("zone id can't be null, if scope is zone");
    }
    HypervisorType hypervisorType = HypervisorType.KVM;
    if (scopeType == ScopeType.ZONE) {
        // ignore passed clusterId and podId
        clusterId = null;
        podId = null;
        final String hypervisor = cmd.getHypervisor();
        if (hypervisor != null) {
            try {
                hypervisorType = HypervisorType.getType(hypervisor);
            } catch (final Exception e) {
                throw new InvalidParameterValueException("invalid hypervisor type " + hypervisor);
            }
        } else {
            throw new InvalidParameterValueException("Missing parameter hypervisor. Hypervisor type is required to create zone wide primary storage.");
        }
        if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.Any) {
            throw new InvalidParameterValueException("zone wide storage pool is not supported for hypervisor type " + hypervisor);
        }
    }
    final Map<String, String> details = extractApiParamAsMap(cmd.getDetails());
    final DataCenterVO zone = this._dcDao.findById(cmd.getZoneId());
    if (zone == null) {
        throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
    }
    // Check if zone is disabled
    final Account account = CallContext.current().getCallingAccount();
    if (AllocationState.Disabled == zone.getAllocationState() && !this._accountMgr.isRootAdmin(account.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
    }
    final Map<String, Object> params = new HashMap<>();
    params.put("zoneId", zone.getId());
    params.put("clusterId", clusterId);
    params.put("podId", podId);
    params.put("url", cmd.getUrl());
    params.put("tags", cmd.getTags());
    params.put("name", cmd.getStoragePoolName());
    params.put("details", details);
    params.put("providerName", storeProvider.getName());
    params.put("managed", cmd.isManaged());
    params.put("capacityBytes", cmd.getCapacityBytes());
    params.put("capacityIops", cmd.getCapacityIops());
    final DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
    DataStore store = null;
    try {
        store = lifeCycle.initialize(params);
        if (scopeType == ScopeType.CLUSTER) {
            final ClusterScope clusterScope = new ClusterScope(clusterId, podId, zoneId);
            lifeCycle.attachCluster(store, clusterScope);
        } else if (scopeType == ScopeType.ZONE) {
            final ZoneScope zoneScope = new ZoneScope(zoneId);
            lifeCycle.attachZone(store, zoneScope, hypervisorType);
        }
    } catch (final Exception e) {
        s_logger.debug("Failed to add data store: " + e.getMessage(), e);
        try {
            // not deleting data store.
            if (store != null) {
                lifeCycle.deleteDataStore(store);
            }
        } catch (final Exception ex) {
            s_logger.debug("Failed to clean up storage pool: " + ex.getMessage());
        }
        throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e);
    }
    return (PrimaryDataStoreInfo) this._dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) PrimaryDataStoreInfo(com.cloud.legacymodel.storage.PrimaryDataStoreInfo) Account(com.cloud.legacymodel.user.Account) HashMap(java.util.HashMap) DataStoreProvider(com.cloud.engine.subsystem.api.storage.DataStoreProvider) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) ResourceInUseException(com.cloud.legacymodel.exceptions.ResourceInUseException) URISyntaxException(java.net.URISyntaxException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) StorageConflictException(com.cloud.legacymodel.exceptions.StorageConflictException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiscoveryException(com.cloud.legacymodel.exceptions.DiscoveryException) HypervisorType(com.cloud.model.enumeration.HypervisorType) ZoneScope(com.cloud.engine.subsystem.api.storage.ZoneScope) DataStoreLifeCycle(com.cloud.engine.subsystem.api.storage.DataStoreLifeCycle) PrimaryDataStoreLifeCycle(com.cloud.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle) ClusterScope(com.cloud.engine.subsystem.api.storage.ClusterScope) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException)

Aggregations

HypervisorType (com.cloud.model.enumeration.HypervisorType)40 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)18 ArrayList (java.util.ArrayList)17 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)16 Account (com.cloud.legacymodel.user.Account)12 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)7 ClusterVO (com.cloud.dc.ClusterVO)6 DataStore (com.cloud.engine.subsystem.api.storage.DataStore)6 DB (com.cloud.utils.db.DB)6 UserVmVO (com.cloud.vm.UserVmVO)6 HostVO (com.cloud.host.HostVO)5 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)5 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)5 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)5 NetworkVO (com.cloud.network.dao.NetworkVO)5 StoragePoolVO (com.cloud.storage.datastore.db.StoragePoolVO)5 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)5 EndPoint (com.cloud.engine.subsystem.api.storage.EndPoint)4 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)4