Search in sources :

Example 31 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method resetVMSSHKeyInternal.

private boolean resetVMSSHKeyInternal(final Long vmId, final String sshPublicKey, final String password) throws ResourceUnavailableException, InsufficientCapacityException {
    final Long userId = CallContext.current().getCallingUserId();
    final VMInstanceVO vmInstance = _vmDao.findById(vmId);
    final VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
    final Nic defaultNic = _networkModel.getDefaultNic(vmId);
    if (defaultNic == null) {
        s_logger.error("Unable to reset SSH Key for vm " + vmInstance + " as the instance doesn't have default nic");
        return false;
    }
    final Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
    final NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.getNetworkTag(template.getHypervisorType(), defaultNetwork));
    final VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance);
    if (template.getEnablePassword()) {
        vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password);
    }
    final UserDataServiceProvider element = _networkMgr.getSSHKeyResetProvider(defaultNetwork);
    if (element == null) {
        throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for SSH Key reset");
    }
    final boolean result = element.saveSSHKey(defaultNetwork, defaultNicProfile, vmProfile, sshPublicKey);
    // Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM
    if (!result) {
        s_logger.debug("Failed to reset SSH Key for the virutal machine; no need to reboot the vm");
        return false;
    } else {
        if (vmInstance.getState() == State.Stopped) {
            s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of SSH Key reset");
            return true;
        }
        if (rebootVirtualMachine(userId, vmId) == null) {
            s_logger.warn("Failed to reboot the vm " + vmInstance);
            return false;
        } else {
            s_logger.debug("Vm " + vmInstance + " is rebooted successfully as a part of SSH Key reset");
            return true;
        }
    }
}
Also used : CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) VMTemplateVO(com.cloud.storage.VMTemplateVO) Nic(com.cloud.legacymodel.network.Nic) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider)

Example 32 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method updateUserDataInternal.

private boolean updateUserDataInternal(final UserVm vm) throws ResourceUnavailableException, InsufficientCapacityException {
    final VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
    final List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
    if (nics == null || nics.isEmpty()) {
        s_logger.error("unable to find any nics for vm " + vm.getUuid());
        return false;
    }
    for (final Nic nic : nics) {
        final Network network = _networkDao.findById(nic.getNetworkId());
        final NicProfile nicProfile = new NicProfile(nic, network, null, null, null, _networkModel.getNetworkTag(template.getHypervisorType(), network));
        final VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm);
        final UserDataServiceProvider element = _networkModel.getUserDataUpdateProvider(network);
        if (element == null) {
            throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for UserData update");
        }
        final boolean result = element.saveUserData(network, nicProfile, vmProfile);
        if (!result) {
            s_logger.error("Failed to update userdata for vm " + vm + " and nic " + nic);
        }
    }
    return true;
}
Also used : CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) VMTemplateVO(com.cloud.storage.VMTemplateVO) Nic(com.cloud.legacymodel.network.Nic) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider)

Example 33 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method updateNicIpForVirtualMachine.

@Override
public UserVm updateNicIpForVirtualMachine(final UpdateVmNicIpCmd cmd) {
    final Long nicId = cmd.getNicId();
    String ipaddr = cmd.getIpaddress();
    final Account caller = CallContext.current().getCallingAccount();
    // check whether the nic belongs to user vm.
    final NicVO nicVO = _nicDao.findById(nicId);
    if (nicVO == null) {
        throw new InvalidParameterValueException("There is no nic for the " + nicId);
    }
    if (nicVO.getVmType() != VirtualMachineType.User) {
        throw new InvalidParameterValueException("The nic is not belongs to user vm");
    }
    final UserVm vm = _vmDao.findById(nicVO.getInstanceId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the nic");
    }
    final Network network = _networkDao.findById(nicVO.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("There is no network with the nic");
    }
    // Don't allow to update vm nic ip if network is not in Implemented/Setup/Allocated state
    if (!(network.getState() == Network.State.Allocated || network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
        throw new InvalidParameterValueException("Network is not in the right state to update vm nic ip. Correct states are: " + Network.State.Allocated + ", " + Network.State.Implemented + ", " + Network.State.Setup);
    }
    final NetworkOfferingVO offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
    if (offering == null) {
        throw new InvalidParameterValueException("There is no network offering with the network");
    }
    if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && vm.getState() != State.Stopped) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to update the vm nic having the specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    // verify permissions
    _accountMgr.checkAccess(caller, null, true, vm);
    final Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
    // verify ip address
    s_logger.debug("Calling the ip allocation ...");
    final Zone zone = zoneRepository.findById(network.getDataCenterId()).orElse(null);
    if (zone == null) {
        throw new InvalidParameterValueException("There is no dc with the nic");
    }
    if (zone.getNetworkType() == NetworkType.Advanced && (network.getGuestType() == GuestType.Isolated || network.getGuestType() == GuestType.Private)) {
        try {
            ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
        } catch (final InsufficientAddressCapacityException e) {
            throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
        }
        if (ipaddr == null) {
            throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
        }
        if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
            final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
            if (oldIP != null) {
                oldIP.setVmIp(ipaddr);
                _ipAddressDao.persist(oldIP);
            }
        }
        // implementing the network elements and resources as a part of vm nic ip update if network has services and it is in Implemented state
        if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && network.getState() == Network.State.Implemented) {
            final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
            final ReservationContext context = new ReservationContextImpl(null, null, callerUser, caller);
            final DeployDestination dest = new DeployDestination(zoneRepository.findById(network.getDataCenterId()).orElse(null), null, null, null);
            s_logger.debug("Implementing the network " + network + " elements and resources as a part of vm nic ip update");
            try {
                // implement the network elements and rules again
                _networkMgr.implementNetworkElementsAndResources(dest, context, network, offering);
            } catch (final Exception ex) {
                s_logger.warn("Failed to implement network " + network + " elements and resources as a part of vm nic ip update due to ", ex);
                final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of vm nic ip " + "update");
                e.addProxyObject(network.getUuid(), "networkId");
                // restore to old ip address
                if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
                    final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
                    if (oldIP != null) {
                        oldIP.setVmIp(nicVO.getIPv4Address());
                        _ipAddressDao.persist(oldIP);
                    }
                }
                throw e;
            }
        }
    } else if (zone.getNetworkType() == NetworkType.Basic || network.getGuestType() == GuestType.Shared) {
        // handle the basic networks here
        // for basic zone, need to provide the podId to ensure proper ip alloation
        Long podId = null;
        if (zone.getNetworkType() == NetworkType.Basic) {
            podId = vm.getPodIdToDeployIn();
            if (podId == null) {
                throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
            }
        }
        try {
            ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, ipaddr);
            if (ipaddr == null) {
                throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
            }
            final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nicVO.getNetworkId(), nicVO.getIPv4Address());
            if (ip != null) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        _ipAddrMgr.markIpAsUnavailable(ip.getId());
                        _ipAddressDao.unassignIpAddress(ip.getId());
                    }
                });
            }
        } catch (final InsufficientAddressCapacityException e) {
            s_logger.error("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
            return null;
        }
    } else {
        s_logger.error("UpdateVmNicIpCmd is not supported in this network...");
        return null;
    }
    // update nic ipaddress
    nicVO.setIPv4Address(ipaddr);
    _nicDao.persist(nicVO);
    return vm;
}
Also used : Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) Zone(com.cloud.db.model.Zone) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) 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) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 34 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class NetworkModelTest method testGetSourceNatIpAddressForGuestNetwork.

@Test
public void testGetSourceNatIpAddressForGuestNetwork() {
    final IPAddressDao ipAddressDao = mock(IPAddressDao.class);
    modelImpl._ipAddressDao = ipAddressDao;
    final List<IPAddressVO> fakeList = new ArrayList<>();
    final IPAddressVO fakeIp = new IPAddressVO(new Ip(NetUtils.ip2Long("75.75.75.75")), 1, 0xaabbccddeeffL, 10, false);
    fakeList.add(fakeIp);
    final SearchBuilder<IPAddressVO> fakeSearch = mock(SearchBuilder.class);
    modelImpl.IpAddressSearch = fakeSearch;
    final VlanDao fakeVlanDao = mock(VlanDao.class);
    when(fakeVlanDao.findById(anyLong())).thenReturn(mock(VlanVO.class));
    modelImpl._vlanDao = fakeVlanDao;
    when(fakeSearch.create()).thenReturn(mock(SearchCriteria.class));
    when(ipAddressDao.search(any(SearchCriteria.class), (Filter) org.mockito.Matchers.isNull())).thenReturn(fakeList);
    when(ipAddressDao.findById(anyLong())).thenReturn(fakeIp);
    final Account fakeAccount = mock(Account.class);
    when(fakeAccount.getId()).thenReturn(1L);
    final Network fakeNetwork = mock(Network.class);
    when(fakeNetwork.getId()).thenReturn(1L);
    PublicIpAddress answer = modelImpl.getSourceNatIpAddressForGuestNetwork(fakeAccount, fakeNetwork);
    Assert.assertNull(answer);
    final IPAddressVO fakeIp2 = new IPAddressVO(new Ip(NetUtils.ip2Long("76.75.75.75")), 1, 0xaabb10ddeeffL, 10, true);
    fakeList.add(fakeIp2);
    when(ipAddressDao.findById(anyLong())).thenReturn(fakeIp2);
    answer = modelImpl.getSourceNatIpAddressForGuestNetwork(fakeAccount, fakeNetwork);
    Assert.assertNotNull(answer);
    Assert.assertEquals(answer.getAddress().addr(), "76.75.75.75");
}
Also used : Account(com.cloud.legacymodel.user.Account) VlanDao(com.cloud.dc.dao.VlanDao) IPAddressDao(com.cloud.network.dao.IPAddressDao) Ip(com.cloud.legacymodel.network.Ip) Network(com.cloud.legacymodel.network.Network) ArrayList(java.util.ArrayList) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) SearchCriteria(com.cloud.utils.db.SearchCriteria) Test(org.junit.Test)

Example 35 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class NetworkModelTest method testGetAvailableIps.

@Test
public void testGetAvailableIps() {
    Network network = new NetworkVO(1L, null, null, null, 1L, 1L, 1L, 1L, null, null, null, null, 1L, null, null, false, null, false, null, null, "10.0.0.1-10.0.0.3,10.0.0.5", "boot.cloud9.example.org", "/boot/me.bin");
    ((NetworkVO) network).setCidr("10.0.0.0/29");
    final NicDao nicDao = mock(NicDao.class);
    modelImpl._nicDao = nicDao;
    final NicSecondaryIpDao nicSecondaryIpDao = mock(NicSecondaryIpDao.class);
    modelImpl._nicSecondaryIpDao = nicSecondaryIpDao;
    final List<String> fakeList = new ArrayList<>();
    final SearchBuilder<IPAddressVO> fakeSearch = mock(SearchBuilder.class);
    when(fakeSearch.create()).thenReturn(mock(SearchCriteria.class));
    when(nicDao.search(any(SearchCriteria.class), (Filter) org.mockito.Matchers.isNull())).thenReturn(fakeList);
    when(nicSecondaryIpDao.search(any(SearchCriteria.class), (Filter) org.mockito.Matchers.isNull())).thenReturn(fakeList);
    SortedSet<Long> possibleAddresses = modelImpl.getAvailableIps(network, "10.0.0.5");
    org.junit.Assert.assertNull(possibleAddresses);
    possibleAddresses = modelImpl.getAvailableIps(network, "10.0.0.6");
    org.junit.Assert.assertEquals(possibleAddresses.size(), 2);
    network = new NetworkVO(1L, null, null, null, 1L, 1L, 1L, 1L, null, null, null, null, 1L, null, null, false, null, false, null, null, null, null, null);
    ((NetworkVO) network).setCidr("10.0.0.0/29");
    possibleAddresses = modelImpl.getAvailableIps(network, "10.0.0.6");
    org.junit.Assert.assertEquals(possibleAddresses.size(), 6);
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) NicSecondaryIpDao(com.cloud.vm.dao.NicSecondaryIpDao) NicDao(com.cloud.vm.dao.NicDao) Network(com.cloud.legacymodel.network.Network) ArrayList(java.util.ArrayList) Matchers.anyLong(org.mockito.Matchers.anyLong) IPAddressVO(com.cloud.network.dao.IPAddressVO) SearchCriteria(com.cloud.utils.db.SearchCriteria) Test(org.junit.Test)

Aggregations

Network (com.cloud.legacymodel.network.Network)160 ArrayList (java.util.ArrayList)57 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)56 Account (com.cloud.legacymodel.user.Account)46 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)42 NetworkOffering (com.cloud.offering.NetworkOffering)36 PhysicalNetwork (com.cloud.network.PhysicalNetwork)34 IPAddressVO (com.cloud.network.dao.IPAddressVO)32 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)30 NetworkVO (com.cloud.network.dao.NetworkVO)28 List (java.util.List)28 Zone (com.cloud.db.model.Zone)27 DB (com.cloud.utils.db.DB)27 NicProfile (com.cloud.vm.NicProfile)26 Nic (com.cloud.legacymodel.network.Nic)21 DataCenter (com.cloud.legacymodel.dc.DataCenter)20 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)20 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)19 DomainRouterVO (com.cloud.vm.DomainRouterVO)18 ActionEvent (com.cloud.event.ActionEvent)17