Search in sources :

Example 96 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class NiciraNvpElement method prepare.

@Override
public boolean prepare(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, IllegalVirtualMachineException {
    if (!canHandle(network, Network.Service.Connectivity)) {
        return false;
    }
    if (network.getBroadcastUri() == null) {
        s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
        return false;
    }
    final NicVO nicVO = nicDao.findById(nic.getId());
    final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
    if (devices.isEmpty()) {
        s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
        return false;
    }
    final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
    final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
    final NiciraNvpNicMappingVO existingNicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
    if (existingNicMap != null) {
        final FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchPortUuid());
        final FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) agentMgr.easySend(niciraNvpHost.getId(), findCmd);
        if (answer.getResult()) {
            s_logger.warn("Existing Logical Switchport found for nic " + nic.getName() + " with uuid " + existingNicMap.getLogicalSwitchPortUuid());
            final UpdateLogicalSwitchPortCommand cmd = new UpdateLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchPortUuid(), BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName());
            agentMgr.easySend(niciraNvpHost.getId(), cmd);
            return true;
        } else {
            s_logger.error("Stale entry found for nic " + nic.getName() + " with logical switchport uuid " + existingNicMap.getLogicalSwitchPortUuid());
            niciraNvpNicMappingDao.remove(existingNicMap.getId());
        }
    }
    VirtualMachine virtualMachine = vm.getVirtualMachine();
    boolean macLearning = false;
    if (virtualMachine != null) {
        macLearning = guestOSDao.listByGuestOSId(virtualMachine.getGuestOSId()).isMacLearning();
    }
    final CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand(BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName(), macLearning);
    final CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);
    if (answer == null || !answer.getResult()) {
        throw new NicPreparationException("CreateLogicalSwitchPortCommand failed");
    }
    final NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(BroadcastDomainType.getValue(network.getBroadcastUri()), answer.getLogicalSwitchPortUuid(), nicVO.getUuid());
    niciraNvpNicMappingDao.persist(nicMap);
    return true;
}
Also used : NiciraNvpNicMappingVO(com.cloud.network.NiciraNvpNicMappingVO) FindLogicalSwitchPortAnswer(com.cloud.agent.api.FindLogicalSwitchPortAnswer) FindLogicalSwitchPortCommand(com.cloud.agent.api.FindLogicalSwitchPortCommand) NiciraNvpDeviceVO(com.cloud.network.NiciraNvpDeviceVO) NicPreparationException(com.cloud.exception.NicPreparationException) CreateLogicalSwitchPortAnswer(com.cloud.agent.api.CreateLogicalSwitchPortAnswer) HostVO(com.cloud.host.HostVO) NicVO(com.cloud.vm.NicVO) CreateLogicalSwitchPortCommand(com.cloud.agent.api.CreateLogicalSwitchPortCommand) UpdateLogicalSwitchPortCommand(com.cloud.agent.api.UpdateLogicalSwitchPortCommand) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 97 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method allocSnapshotForVm.

@Override
public Snapshot allocSnapshotForVm(final Long vmId, Long volumeId, final String snapshotName) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vm:" + vmId + " doesn't exist");
    }
    _accountMgr.checkAccess(caller, null, true, vm);
    final VolumeInfo volume = volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
    }
    _accountMgr.checkAccess(caller, null, true, volume);
    final VirtualMachine attachVM = volume.getAttachedVM();
    if (attachVM == null || attachVM.getId() != vm.getId()) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't attach to vm :" + vm);
    }
    final DataCenter zone = _dcDao.findById(volume.getDataCenterId());
    if (zone == null) {
        throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
    }
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    if (volume.getTemplateId() != null) {
        final VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
        if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
            throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
        }
    }
    final StoragePool storagePool = (StoragePool) volume.getDataStore();
    if (storagePool == null) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
    }
    return snapshotMgr.allocSnapshot(volumeId, Snapshot.MANUAL_POLICY_ID, snapshotName, true);
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 98 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class ConsoleProxyServlet method handleAccessRequest.

private void handleAccessRequest(final HttpServletRequest req, final HttpServletResponse resp, final long vmId) {
    final VirtualMachine vm = _vmMgr.findById(vmId);
    if (vm == null) {
        s_logger.warn("VM " + vmId + " does not exist, sending blank response for console access request");
        sendResponse(resp, "");
        return;
    }
    if (vm.getHostId() == null) {
        s_logger.warn("VM " + vmId + " lost host info, sending blank response for console access request");
        sendResponse(resp, "");
        return;
    }
    final HostVO host = _ms.getHostBy(vm.getHostId());
    if (host == null) {
        s_logger.warn("VM " + vmId + "'s host does not exist, sending blank response for console access request");
        sendResponse(resp, "");
        return;
    }
    final String rootUrl = _ms.getConsoleAccessUrlRoot(vmId);
    if (rootUrl == null) {
        sendResponse(resp, "<html><body><p>Console access will be ready in a few minutes. Please try it again later.</p></body></html>");
        return;
    }
    String vmName = vm.getHostName();
    if (vm.getType() == VirtualMachine.Type.User) {
        final UserVm userVm = _entityMgr.findById(UserVm.class, vmId);
        final String displayName = userVm.getDisplayName();
        if (displayName != null && !displayName.isEmpty() && !displayName.equals(vmName)) {
            vmName += "(" + displayName + ")";
        }
    }
    final StringBuffer sb = new StringBuffer();
    sb.append("<html><title>").append(escapeHTML(vmName)).append("</title><frameset><frame src=\"").append(composeConsoleAccessUrl(rootUrl, vm, host));
    sb.append("\"></frame></frameset></html>");
    s_logger.debug("the console url is :: " + sb.toString());
    sendResponse(resp, sb.toString());
}
Also used : UserVm(com.cloud.uservm.UserVm) HostVO(com.cloud.host.HostVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 99 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class MigrateSystemVMCmd method execute.

@Override
public void execute() {
    if (getHostId() != null && getStorageId() != null) {
        throw new InvalidParameterValueException("Only one of hostId and storageId can be specified");
    }
    try {
        // FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer
        VirtualMachine migratedVm = null;
        if (getStorageId() != null) {
            // OfflineMigration performed when this parameter is specified
            StoragePool destStoragePool = _storageService.getStoragePool(getStorageId());
            if (destStoragePool == null) {
                throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM");
            }
            CallContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: " + getStorageId());
            migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool);
        } else {
            Host destinationHost = null;
            if (getHostId() != null) {
                destinationHost = _resourceService.getHost(getHostId());
                if (destinationHost == null) {
                    throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId());
                }
                if (destinationHost.getType() != Host.Type.Routing) {
                    throw new InvalidParameterValueException("The specified host(" + destinationHost.getName() + ") is not suitable to migrate the VM, please specify another one");
                }
            } else if (!isAutoSelect()) {
                throw new InvalidParameterValueException("Please specify a host or storage as destination, or pass 'autoselect=true' to automatically select a destination host which do not require storage migration");
            }
            CallContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: " + getHostId());
            if (destinationHost == null) {
                migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), null);
            } else {
                migratedVm = _userVmService.migrateVirtualMachineWithVolume(getVirtualMachineId(), destinationHost, new HashMap<String, String>());
            }
        }
        if (migratedVm != null) {
            // return the generic system VM instance response
            SystemVmResponse response = _responseGenerator.createSystemVmResponse(migratedVm);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate the system vm");
        }
    } catch (ResourceUnavailableException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException e) {
        s_logger.warn("Exception: ", e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    } catch (ManagementServerException e) {
        s_logger.warn("Exception: ", e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    } catch (VirtualMachineMigrationException e) {
        s_logger.warn("Exception: ", e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : SystemVmResponse(org.apache.cloudstack.api.response.SystemVmResponse) StoragePool(com.cloud.storage.StoragePool) ServerApiException(org.apache.cloudstack.api.ServerApiException) ManagementServerException(com.cloud.exception.ManagementServerException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) HashMap(java.util.HashMap) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Host(com.cloud.host.Host) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 100 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class MigrateVirtualMachineWithVolumeCmd method execute.

@Override
public void execute() {
    if (hostId == null && MapUtils.isEmpty(migrateVolumeTo)) {
        throw new InvalidParameterValueException(String.format("Either %s or %s  must be passed for migrating the VM", ApiConstants.HOST_ID, ApiConstants.MIGRATE_TO));
    }
    UserVm userVm = _userVmService.getUserVm(getVirtualMachineId());
    if (userVm == null) {
        throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId());
    }
    if (!VirtualMachine.State.Running.equals(userVm.getState()) && hostId != null) {
        throw new InvalidParameterValueException(String.format("VM ID: %s is not in Running state to migrate it to new host", userVm.getUuid()));
    }
    if (!VirtualMachine.State.Stopped.equals(userVm.getState()) && hostId == null) {
        throw new InvalidParameterValueException(String.format("VM ID: %s is not in Stopped state to migrate, use %s parameter to migrate it to a new host", userVm.getUuid(), ApiConstants.HOST_ID));
    }
    try {
        VirtualMachine migratedVm = null;
        if (hostId != null) {
            Host destinationHost = _resourceService.getHost(getHostId());
            // OfflineVmwareMigration: destination host would have to not be a required parameter for stopped VMs
            if (destinationHost == null) {
                throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id =" + getHostId());
            }
            migratedVm = _userVmService.migrateVirtualMachineWithVolume(getVirtualMachineId(), destinationHost, getVolumeToPool());
        } else if (MapUtils.isNotEmpty(migrateVolumeTo)) {
            migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), getVolumeToPool());
        }
        if (migratedVm != null) {
            UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", (UserVm) migratedVm).get(0);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate vm");
        }
    } catch (ResourceUnavailableException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException | ManagementServerException | VirtualMachineMigrationException e) {
        s_logger.warn("Exception: ", e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) ManagementServerException(com.cloud.exception.ManagementServerException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Host(com.cloud.host.Host) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachine(com.cloud.vm.VirtualMachine)

Aggregations

VirtualMachine (com.cloud.vm.VirtualMachine)141 HostVO (com.cloud.host.HostVO)38 ArrayList (java.util.ArrayList)35 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 HashMap (java.util.HashMap)25 List (java.util.List)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 VMInstanceVO (com.cloud.vm.VMInstanceVO)20 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)19 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 DataCenter (com.cloud.dc.DataCenter)17 Host (com.cloud.host.Host)17 ServiceOffering (com.cloud.offering.ServiceOffering)17 Test (org.junit.Test)17 ServerApiException (com.cloud.api.ServerApiException)16 SystemVmResponse (com.cloud.api.response.SystemVmResponse)14 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)14 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)13 Account (com.cloud.user.Account)13 UserVm (com.cloud.uservm.UserVm)13