Search in sources :

Example 71 with InvalidParameterValueException

use of com.cloud.utils.exception.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class UpgradeVMCmd method execute.

// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public void execute() throws ResourceAllocationException {
    CallContext.current().setEventDetails("Vm Id: " + getId());
    final ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
    }
    final UserVm result = _userVmService.upgradeVirtualMachine(this);
    if (result != null) {
        final UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Restricted, "virtualmachine", result).get(0);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upgrade vm");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(com.cloud.api.ServerApiException) ServiceOffering(com.cloud.offering.ServiceOffering) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) UserVmResponse(com.cloud.api.response.UserVmResponse)

Example 72 with InvalidParameterValueException

use of com.cloud.utils.exception.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicTest method testCreateFailure.

@Test
public void testCreateFailure() throws ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException {
    final NetworkService networkService = Mockito.mock(NetworkService.class);
    final AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);
    Mockito.when(networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString())).thenReturn(null);
    ipTonicCmd._networkService = networkService;
    try {
        ipTonicCmd.execute();
    } catch (final InsufficientAddressCapacityException e) {
        throw new InvalidParameterValueException("Allocating guest ip for nic failed");
    }
}
Also used : AddIpToVmNicCmd(com.cloud.api.command.user.vm.AddIpToVmNicCmd) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) NetworkService(com.cloud.network.NetworkService) Test(org.junit.Test)

Example 73 with InvalidParameterValueException

use of com.cloud.utils.exception.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicTest method testRemoveIpFromVmNicFailure.

@Test
public void testRemoveIpFromVmNicFailure() throws InsufficientAddressCapacityException {
    final NetworkService networkService = Mockito.mock(NetworkService.class);
    final RemoveIpFromVmNicCmd removeIpFromNic = Mockito.mock(RemoveIpFromVmNicCmd.class);
    Mockito.when(networkService.releaseSecondaryIpFromNic(Matchers.anyInt())).thenReturn(false);
    removeIpFromNic._networkService = networkService;
    successResponseGenerator = Mockito.mock(SuccessResponse.class);
    try {
        removeIpFromNic.execute();
    } catch (final InvalidParameterValueException exception) {
        Assert.assertEquals("Failed to remove secondary  ip address for the nic", exception.getLocalizedMessage());
    }
}
Also used : SuccessResponse(com.cloud.api.response.SuccessResponse) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) NetworkService(com.cloud.network.NetworkService) RemoveIpFromVmNicCmd(com.cloud.api.command.user.vm.RemoveIpFromVmNicCmd) Test(org.junit.Test)

Example 74 with InvalidParameterValueException

use of com.cloud.utils.exception.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateMigrateWithStorage.

private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final HostVO srcHost = _hostDao.findById(srcHostId);
    final HostVO destHost = _hostDao.findById(destHostId);
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final Zone zone = _zoneRepository.findOne(destHost.getDataCenterId());
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(zone, pod, cluster, destHost);
    // Create a map of which volume should go in which storage pool.
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    final Map<Volume, StoragePool> volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
    // a vm and not migrating a vm with storage.
    if (volumeToPoolMap == null || volumeToPoolMap.isEmpty()) {
        throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost + " doesn't involve migrating the volumes.");
    }
    AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
    if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
    }
    _networkMgr.prepareNicForMigration(profile, destination);
    volumeMgr.prepareForMigration(profile, destination);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
    final VirtualMachineTO to = hvGuru.implement(profile);
    ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
    work.setStep(Step.Prepare);
    work.setResourceType(ItWorkVO.ResourceType.Host);
    work.setResourceId(destHostId);
    work = _workDao.persist(work);
    // Put the vm in migrating state.
    vm.setLastHostId(srcHostId);
    moveVmToMigratingState(vm, destHostId, work);
    boolean migrated = false;
    try {
        // config drive: Detach the config drive at source host
        // After migration successful attach the config drive in destination host
        // On migration failure VM will be stopped, So configIso will be deleted
        final Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            final UserVmVO userVm = _userVmDao.findById(vm.getId());
            final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            final Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
            if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
                final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
                final String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
                final boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
                vmData = _networkModel.generateVmData(userVm.getUserData(), serviceOffering, zoneName, vm.getInstanceName(), vm.getId(), (String) profile.getParameter(VirtualMachineProfile.Param.VmSshPubKey), (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows, network);
                final String vmName = vm.getInstanceName();
                final String configDriveIsoRootFolder = "/tmp";
                final String isoFile = configDriveIsoRootFolder + "/" + vmName + "/configDrive/" + vmName + ".iso";
                profile.setVmData(vmData);
                profile.setConfigDriveLabel(VmConfigDriveLabel.value());
                profile.setConfigDriveIsoRootFolder(configDriveIsoRootFolder);
                profile.setConfigDriveIsoFile(isoFile);
                // At source host detach the config drive iso.
                final AttachOrDettachConfigDriveCommand dettachCommand = new AttachOrDettachConfigDriveCommand(vm.getInstanceName(), vmData, VmConfigDriveLabel.value(), false);
                try {
                    _agentMgr.send(srcHost.getId(), dettachCommand);
                    s_logger.debug("Deleted config drive ISO for  vm " + vm.getInstanceName() + " In host " + srcHost);
                } catch (final OperationTimedoutException e) {
                    s_logger.debug("TIme out occured while exeuting command AttachOrDettachConfigDrive " + e.getMessage());
                }
            }
        }
        // Migrate the vm and its volume.
        volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPoolMap);
        // Put the vm back to running state.
        moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
        try {
            if (!checkVmOnHost(vm, destHostId)) {
                s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
                try {
                    _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
                } catch (final AgentUnavailableException e) {
                    s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                }
                cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
                throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
            }
        } catch (final OperationTimedoutException e) {
            s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
        }
        migrated = true;
    } finally {
        if (!migrated) {
            s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
            _alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + zone.getName() + " and pod " + zone.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                stateTransitTo(vm, Event.OperationFailed, srcHostId);
            } catch (final AgentUnavailableException e) {
                s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
            } catch (final NoTransitionException e) {
                s_logger.error("Error while transitioning vm from migrating to running state.", e);
            }
        }
        work.setStep(Step.Done);
        _workDao.update(work.getId(), work);
    }
}
Also used : AlertManager(com.cloud.alert.AlertManager) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) StoragePool(com.cloud.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) Commands(com.cloud.agent.manager.Commands) Zone(com.cloud.db.model.Zone) TimeZone(java.util.TimeZone) Cluster(com.cloud.org.Cluster) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.agent.api.AttachOrDettachConfigDriveCommand) Volume(com.cloud.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.utils.fsm.NoTransitionException)

Example 75 with InvalidParameterValueException

use of com.cloud.utils.exception.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class CloudOrchestrator method createVirtualMachineFromScratch.

@Override
public void createVirtualMachineFromScratch(final String id, final String owner, final String isoId, final String hostName, final String displayName, final String hypervisor, final String os, 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) throws InsufficientCapacityException {
    final VirtualMachineEntityImpl vmEntity = ComponentContext.inject(VirtualMachineEntityImpl.class);
    vmEntity.init(id, owner, hostName, displayName, computeTags, rootDiskTags, new ArrayList<>(networkNicMap.keySet()));
    // load vm instance and offerings and call virtualMachineManagerImpl
    final VMInstanceVO vm = _vmDao.findByUuid(id);
    final ServiceOfferingVO computeOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
    final DiskOfferingInfo rootDiskOfferingInfo = new DiskOfferingInfo();
    rootDiskOfferingInfo.setDiskOffering(computeOffering);
    final Long diskOfferingId = vm.getDiskOfferingId();
    if (diskOfferingId == null) {
        throw new InvalidParameterValueException("Installing from ISO requires a disk offering to be specified for the root disk.");
    }
    final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
    if (diskOffering == null) {
        throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId);
    }
    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);
    }
    rootDiskOfferingInfo.setDiskOffering(diskOffering);
    rootDiskOfferingInfo.setSize(size);
    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");
            rootDiskOfferingInfo.setMinIops(minIops != null && minIops.trim().length() > 0 ? Long.parseLong(minIops) : null);
            rootDiskOfferingInfo.setMaxIops(maxIops != null && maxIops.trim().length() > 0 ? Long.parseLong(maxIops) : null);
        }
    }
    final LinkedHashMap<Network, 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 HypervisorType hypervisorType = HypervisorType.valueOf(hypervisor);
    _itMgr.allocate(vm.getInstanceName(), _templateDao.findById(new Long(isoId)), computeOffering, rootDiskOfferingInfo, new ArrayList<>(), networkIpMap, plan, hypervisorType);
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) 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.hypervisor.Hypervisor.HypervisorType) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) Network(com.cloud.network.Network) ArrayList(java.util.ArrayList) List(java.util.List) DiskOfferingInfo(com.cloud.offering.DiskOfferingInfo)

Aggregations

InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)478 Account (com.cloud.user.Account)199 ActionEvent (com.cloud.event.ActionEvent)151 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)146 ArrayList (java.util.ArrayList)104 DB (com.cloud.utils.db.DB)97 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)72 List (java.util.List)61 TransactionStatus (com.cloud.utils.db.TransactionStatus)57 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)53 ServerApiException (com.cloud.api.ServerApiException)46 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)44 Network (com.cloud.network.Network)40 Pair (com.cloud.utils.Pair)36 HashMap (java.util.HashMap)36 ConfigurationException (javax.naming.ConfigurationException)36 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)33 NetworkVO (com.cloud.network.dao.NetworkVO)31 HostVO (com.cloud.host.HostVO)30 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)30