Search in sources :

Example 96 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method removeNicFromVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_DELETE, eventDescription = "Removing Nic", async = true)
public UserVm removeNicFromVirtualMachine(final RemoveNicFromVMCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, CloudRuntimeException {
    final Long vmId = cmd.getVmId();
    final Long nicId = cmd.getNicId();
    final Account caller = CallContext.current().getCallingAccount();
    final UserVmVO vmInstance = _vmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("NIC cannot be removed from VM with VM Snapshots");
    }
    final NicVO nic = _nicDao.findById(nicId);
    if (nic == null) {
        throw new InvalidParameterValueException("Unable to find a nic with id " + nicId);
    }
    final NetworkVO network = _networkDao.findById(nic.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("Unable to find a network with id " + nic.getNetworkId());
    }
    // Perform permission check on VM
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    // Verify that zone is not Basic
    final Zone zone = zoneRepository.findById(vmInstance.getDataCenterId()).orElse(null);
    if (zone.getNetworkType() == NetworkType.Basic) {
        throw new InvalidParameterValueException("Zone " + vmInstance.getDataCenterId() + ", has a NetworkType of Basic. Can't remove a NIC from a VM on a Basic Network");
    }
    // check to see if nic is attached to VM
    if (nic.getInstanceId() != vmId) {
        throw new InvalidParameterValueException(nic + " is not a nic on " + vmInstance);
    }
    // Perform account permission check on network
    _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network);
    // don't delete default NIC on a user VM
    if (nic.isDefaultNic() && vmInstance.getType() == VirtualMachineType.User) {
        throw new InvalidParameterValueException("Unable to remove nic from " + vmInstance + " in " + network + ", nic is default.");
    }
    // if specified nic is associated with PF/LB/Static NAT
    if (_rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0) {
        throw new InvalidParameterValueException("Unable to remove nic from " + vmInstance + " in " + network + ", nic has associated Port forwarding or Load balancer or " + "Static NAT rules.");
    }
    final boolean nicremoved;
    try {
        nicremoved = _itMgr.removeNicFromVm(vmInstance, nic);
    } catch (final ResourceUnavailableException e) {
        throw new CloudRuntimeException("Unable to remove " + network + " from " + vmInstance + ": " + e);
    } catch (final ConcurrentOperationException e) {
        throw new CloudRuntimeException("Concurrent operations on removing " + network + " from " + vmInstance + ": " + e);
    }
    if (!nicremoved) {
        throw new CloudRuntimeException("Unable to remove " + network + " from " + vmInstance);
    }
    s_logger.debug("Successful removal of " + network + " from " + vmInstance);
    return _vmDao.findById(vmInstance.getId());
}
Also used : Account(com.cloud.legacymodel.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Zone(com.cloud.db.model.Zone) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ActionEvent(com.cloud.event.ActionEvent)

Example 97 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method rebootVirtualMachine.

private UserVm rebootVirtualMachine(final long userId, final long vmId) throws InsufficientCapacityException, ResourceUnavailableException {
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
        s_logger.warn("Vm id=" + vmId + " doesn't exist");
        return null;
    }
    if (vm.getState() == State.Running && vm.getHostId() != null) {
        collectVmDiskStatistics(vm);
        final Zone zone = zoneRepository.findById(vm.getDataCenterId()).orElse(null);
        try {
            if (zone.getNetworkType() == NetworkType.Advanced) {
                // List all networks of vm
                final List<Long> vmNetworks = _vmNetworkMapDao.getNetworks(vmId);
                final List<DomainRouterVO> routers = new ArrayList<>();
                // List the stopped routers
                for (final long vmNetworkId : vmNetworks) {
                    final List<DomainRouterVO> router = _routerDao.listStopped(vmNetworkId);
                    routers.addAll(router);
                }
                // and routers are started serially ,may revisit to make this process parallel
                for (final DomainRouterVO routerToStart : routers) {
                    s_logger.warn("Trying to start router " + routerToStart.getInstanceName() + " as part of vm: " + vm.getInstanceName() + " reboot");
                    _virtualNetAppliance.startRouter(routerToStart.getId(), true);
                }
            }
        } catch (final ConcurrentOperationException e) {
            throw new CloudRuntimeException("Concurrent operations on starting router. " + e);
        } catch (final Exception ex) {
            throw new CloudRuntimeException("Router start failed due to" + ex);
        } finally {
            s_logger.info("Rebooting vm " + vm.getInstanceName());
            _itMgr.reboot(vm.getUuid(), null);
        }
        return _vmDao.findById(vmId);
    } else {
        s_logger.error("Vm id=" + vmId + " is not in Running state, failed to reboot");
        return null;
    }
}
Also used : Zone(com.cloud.db.model.Zone) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ArrayList(java.util.ArrayList) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) 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)

Example 98 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method addNicToVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_CREATE, eventDescription = "Creating Nic", async = true)
public UserVm addNicToVirtualMachine(final AddNicToVMCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, CloudRuntimeException {
    final Long vmId = cmd.getVmId();
    final Long networkId = cmd.getNetworkId();
    final String ipAddress = cmd.getIpAddress();
    final String macAddress = cmd.getMacAddress();
    final Account caller = CallContext.current().getCallingAccount();
    final UserVmVO vmInstance = _vmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("NIC cannot be added to VM with VM Snapshots");
    }
    final NetworkVO network = _networkDao.findById(networkId);
    if (network == null) {
        throw new InvalidParameterValueException("unable to find a network with id " + networkId);
    }
    // Root admin may plug anything, Domain admin is allowed to plug into the public network
    if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        if (!(network.getGuestType() == GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == vmInstance.getAccountId()) && !(caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN && TrafficType.Public.equals(network.getTrafficType()))) {
            throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vmId: " + vmId);
        }
    }
    final List<NicVO> allNics = _nicDao.listByVmId(vmInstance.getId());
    for (final NicVO nic : allNics) {
        if (nic.getNetworkId() == network.getId()) {
            throw new CloudRuntimeException("A NIC already exists for VM:" + vmInstance.getInstanceName() + " in network: " + network.getUuid());
        }
    }
    if (_nicDao.findByNetworkIdAndMacAddress(networkId, macAddress) != null) {
        throw new CloudRuntimeException("A NIC with this MAC-Address already exists for network: " + network.getUuid());
    }
    NicProfile profile = new NicProfile(ipAddress, null, macAddress);
    if (ipAddress != null) {
        if (!(NetUtils.isValidIp4(ipAddress) || NetUtils.isValidIp6(ipAddress))) {
            throw new InvalidParameterValueException("Invalid format for IP address parameter: " + ipAddress);
        }
    }
    // Perform permission check on VM
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    // Verify that zone is not Basic
    final Zone zone = zoneRepository.findById(vmInstance.getDataCenterId()).orElse(null);
    if (zone.getNetworkType() == NetworkType.Basic) {
        throw new CloudRuntimeException("Zone " + vmInstance.getDataCenterId() + ", has a NetworkType of Basic. Can't add a new NIC to a VM on a Basic Network");
    }
    // Perform account permission check on network
    _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network);
    // ensure network belongs in zone
    if (network.getDataCenterId() != vmInstance.getDataCenterId()) {
        throw new CloudRuntimeException(vmInstance + " is in zone:" + vmInstance.getDataCenterId() + " but " + network + " is in zone:" + network.getDataCenterId());
    }
    // Get all vms hostNames in the network
    final List<String> hostNames = _vmInstanceDao.listDistinctHostNames(network.getId());
    // This will also check if there are multiple nics of same vm in the network
    if (hostNames.contains(vmInstance.getHostName())) {
        for (final String hostName : hostNames) {
            final VMInstanceVO vm = _vmInstanceDao.findVMByHostName(hostName);
            if (_networkModel.getNicInNetwork(vm.getId(), network.getId()) != null && vm.getHostName().equals(vmInstance.getHostName())) {
                throw new CloudRuntimeException(network + " already has a vm with host name: " + vmInstance.getHostName());
            }
        }
    }
    NicProfile guestNic = null;
    boolean cleanUp = true;
    try {
        guestNic = _itMgr.addVmToNetwork(vmInstance, network, profile);
        cleanUp = false;
    } catch (final ResourceUnavailableException e) {
        throw new CloudRuntimeException("Unable to add NIC to " + vmInstance + ": " + e);
    } catch (final InsufficientCapacityException e) {
        throw new CloudRuntimeException("Insufficient capacity when adding NIC to " + vmInstance + ": " + e);
    } catch (final ConcurrentOperationException e) {
        throw new CloudRuntimeException("Concurrent operations on adding NIC to " + vmInstance + ": " + e);
    } finally {
        if (cleanUp) {
            try {
                _itMgr.removeVmFromNetwork(vmInstance, network, null);
            } catch (final ResourceUnavailableException e) {
                throw new CloudRuntimeException("Error while cleaning up NIC " + e);
            }
        }
    }
    if (guestNic == null) {
        throw new CloudRuntimeException("Unable to add NIC to " + vmInstance);
    }
    CallContext.current().putContextParameter(Nic.class, guestNic.getUuid());
    s_logger.debug("Successful addition of " + network + " from " + vmInstance);
    return _vmDao.findById(vmInstance.getId());
}
Also used : Account(com.cloud.legacymodel.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) Zone(com.cloud.db.model.Zone) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ActionEvent(com.cloud.event.ActionEvent)

Example 99 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class ConsoleProxyManagerTest method getDefaultNetwork.

@Test
public void getDefaultNetwork() {
    final Zone zone = mock(Zone.class);
    when(zone.getNetworkType()).thenReturn(NetworkType.Advanced);
    when(zoneRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(zone));
    final NetworkVO network = Mockito.mock(NetworkVO.class);
    final NetworkVO badNetwork = Mockito.mock(NetworkVO.class);
    when(_networkDao.listByZoneAndTrafficType(anyLong(), eq(TrafficType.Public))).thenReturn(Collections.singletonList(network));
    when(_networkDao.listByZoneAndTrafficType(anyLong(), not(eq(TrafficType.Public)))).thenReturn(Collections.singletonList(badNetwork));
    final NetworkVO returnedNetwork = cpvmManager.getDefaultNetworkForAdvancedZone(zone);
    Assert.assertNotNull(returnedNetwork);
    Assert.assertEquals(network, returnedNetwork);
    Assert.assertNotEquals(badNetwork, returnedNetwork);
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) Zone(com.cloud.db.model.Zone) Test(org.junit.Test)

Example 100 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateReboot.

private void orchestrateReboot(final String vmUuid, final Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    // if there are active vm snapshots task, state change is not allowed
    if (_vmSnapshotMgr.hasActiveVMSnapshotTasks(vm.getId())) {
        s_logger.error("Unable to reboot VM " + vm + " due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
        throw new CloudRuntimeException("Unable to reboot VM " + vm + " due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
    }
    final Zone zone = _zoneRepository.findById(vm.getDataCenterId()).orElse(null);
    final Host host = _hostDao.findById(vm.getHostId());
    if (host == null) {
        // Should findById throw an Exception is the host is not found?
        throw new CloudRuntimeException("Unable to retrieve host with id " + vm.getHostId());
    }
    final Cluster cluster = _entityMgr.findById(Cluster.class, host.getClusterId());
    final Pod pod = _entityMgr.findById(Pod.class, host.getPodId());
    final DeployDestination dest = new DeployDestination(zone, pod, cluster, host);
    try {
        final Commands cmds = new Commands(Command.OnError.Stop);
        cmds.addCommand(new RebootCommand(vm.getInstanceName(), getExecuteInSequence(vm.getHypervisorType())));
        _agentMgr.send(host.getId(), cmds);
        final Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
        if (rebootAnswer != null && rebootAnswer.getResult()) {
            return;
        }
        s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
    } catch (final OperationTimedoutException e) {
        s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
        throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
    }
}
Also used : UnPlugNicAnswer(com.cloud.legacymodel.communication.answer.UnPlugNicAnswer) AgentControlAnswer(com.cloud.legacymodel.communication.answer.AgentControlAnswer) ClusterVMMetaDataSyncAnswer(com.cloud.legacymodel.communication.answer.ClusterVMMetaDataSyncAnswer) RestoreVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RestoreVMSnapshotAnswer) RebootAnswer(com.cloud.legacymodel.communication.answer.RebootAnswer) StartAnswer(com.cloud.legacymodel.communication.answer.StartAnswer) PlugNicAnswer(com.cloud.legacymodel.communication.answer.PlugNicAnswer) CheckVirtualMachineAnswer(com.cloud.legacymodel.communication.answer.CheckVirtualMachineAnswer) StopAnswer(com.cloud.legacymodel.communication.answer.StopAnswer) Answer(com.cloud.legacymodel.communication.answer.Answer) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) RebootCommand(com.cloud.legacymodel.communication.command.RebootCommand) Pod(com.cloud.legacymodel.dc.Pod) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) DeployDestination(com.cloud.deploy.DeployDestination) Commands(com.cloud.agent.manager.Commands) Cluster(com.cloud.legacymodel.dc.Cluster) Host(com.cloud.legacymodel.dc.Host)

Aggregations

Zone (com.cloud.db.model.Zone)109 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)34 ArrayList (java.util.ArrayList)34 DomainRouterVO (com.cloud.vm.DomainRouterVO)28 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)26 Network (com.cloud.legacymodel.network.Network)25 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)23 Account (com.cloud.legacymodel.user.Account)23 NetworkVO (com.cloud.network.dao.NetworkVO)23 NetworkTopology (com.cloud.network.topology.NetworkTopology)23 DeployDestination (com.cloud.deploy.DeployDestination)18 NicProfile (com.cloud.vm.NicProfile)17 List (java.util.List)17 HostPodVO (com.cloud.dc.HostPodVO)16 HostVO (com.cloud.host.HostVO)16 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)14 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)14 DB (com.cloud.utils.db.DB)14 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)12 NetworkOffering (com.cloud.offering.NetworkOffering)11