Search in sources :

Example 46 with ReservationContext

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

the class DomainManagerImpl method cleanupDomain.

private boolean cleanupDomain(final Long domainId, final Long ownerId) throws ConcurrentOperationException, ResourceUnavailableException {
    s_logger.debug("Cleaning up domain id=" + domainId);
    boolean success = true;
    {
        final DomainVO domainHandle = _domainDao.findById(domainId);
        domainHandle.setState(Domain.State.Inactive);
        _domainDao.update(domainId, domainHandle);
        final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("parent", SearchCriteria.Op.EQ, domainId);
        final List<DomainVO> domains = _domainDao.search(sc, null);
        final SearchCriteria<DomainVO> sc1 = _domainDao.createSearchCriteria();
        sc1.addAnd("path", SearchCriteria.Op.LIKE, "%" + domainHandle.getPath() + "%");
        final List<DomainVO> domainsToBeInactivated = _domainDao.search(sc1, null);
        // update all subdomains to inactive so no accounts/users can be created
        for (final DomainVO domain : domainsToBeInactivated) {
            domain.setState(Domain.State.Inactive);
            _domainDao.update(domain.getId(), domain);
        }
        // cleanup sub-domains first
        for (final DomainVO domain : domains) {
            success = (success && cleanupDomain(domain.getId(), domain.getAccountId()));
            if (!success) {
                s_logger.warn("Failed to cleanup domain id=" + domain.getId());
            }
        }
    }
    // delete users which will also delete accounts and release resources for those accounts
    final SearchCriteria<AccountVO> sc = _accountDao.createSearchCriteria();
    sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
    final List<AccountVO> accounts = _accountDao.search(sc, null);
    for (final AccountVO account : accounts) {
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            s_logger.debug("Deleting account " + account + " as a part of domain id=" + domainId + " cleanup");
            final boolean deleteAccount = _accountMgr.deleteAccount(account, CallContext.current().getCallingUserId(), CallContext.current().getCallingAccount());
            if (!deleteAccount) {
                s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup");
            }
            success = (success && deleteAccount);
        } else {
            final ProjectVO project = _projectDao.findByProjectAccountId(account.getId());
            s_logger.debug("Deleting project " + project + " as a part of domain id=" + domainId + " cleanup");
            final boolean deleteProject = _projectMgr.deleteProject(CallContext.current().getCallingAccount(), CallContext.current().getCallingUserId(), project);
            if (!deleteProject) {
                s_logger.warn("Failed to cleanup project " + project + " as a part of domain cleanup");
            }
            success = (success && deleteProject);
        }
    }
    // delete the domain shared networks
    boolean networksDeleted = true;
    s_logger.debug("Deleting networks for domain id=" + domainId);
    final List<Long> networkIds = _networkDomainDao.listNetworkIdsByDomain(domainId);
    final CallContext ctx = CallContext.current();
    final ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallingUserId()), ctx.getCallingAccount());
    for (final Long networkId : networkIds) {
        s_logger.debug("Deleting network id=" + networkId + " as a part of domain id=" + domainId + " cleanup");
        if (!_networkMgr.destroyNetwork(networkId, context, false)) {
            s_logger.warn("Unable to destroy network id=" + networkId + " as a part of domain id=" + domainId + " cleanup.");
            networksDeleted = false;
        } else {
            s_logger.debug("Network " + networkId + " successfully deleted as a part of domain id=" + domainId + " cleanup.");
        }
    }
    // don't proceed if networks failed to cleanup. The cleanup will be performed for inactive domain once again
    if (!networksDeleted) {
        s_logger.debug("Failed to delete the shared networks as a part of domain id=" + domainId + " clenaup");
        return false;
    }
    // don't remove the domain if there are accounts required cleanup
    final boolean deleteDomainSuccess;
    final List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
    if (accountsForCleanup.isEmpty()) {
        // release dedication if any, before deleting the domain
        final List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByDomainId(domainId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for domain" + domainId);
            for (final DedicatedResourceVO dr : dedicatedResources) {
                if (!_dedicatedDao.remove(dr.getId())) {
                    s_logger.warn("Fail to release dedicated resources for domain " + domainId);
                    return false;
                }
            }
        }
        // delete domain
        deleteDomainSuccess = _domainDao.remove(domainId);
        // Delete resource count and resource limits entries set for this domain (if there are any).
        _resourceCountDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
        _resourceLimitDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
    } else {
        s_logger.debug("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup");
        return false;
    }
    return success && deleteDomainSuccess;
}
Also used : CallContext(com.cloud.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) SearchCriteria(com.cloud.utils.db.SearchCriteria) ProjectVO(com.cloud.projects.ProjectVO) ReservationContext(com.cloud.vm.ReservationContext) DomainVO(com.cloud.domain.DomainVO) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Example 47 with ReservationContext

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

the class NetworkOrchestrator method commitNicForMigration.

@Override
public void commitNicForMigration(final VirtualMachineProfile src, final VirtualMachineProfile dst) {
    for (final NicProfile nicSrc : src.getNics()) {
        final NetworkVO network = _networksDao.findById(nicSrc.getNetworkId());
        final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
        final NicProfile nicDst = findNicProfileById(dst, nicSrc.getId());
        final ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null);
        final ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null);
        if (guru instanceof NetworkMigrationResponder) {
            ((NetworkMigrationResponder) guru).commitMigration(nicSrc, network, src, src_context, dst_context);
        }
        if (network.getGuestType() == Network.GuestType.L2 && src.getType() == VirtualMachine.Type.User) {
            _userVmMgr.setupVmForPvlan(true, src.getVirtualMachine().getHostId(), nicSrc);
        }
        final List<Provider> providersToImplement = getNetworkProviders(network.getId());
        for (final NetworkElement element : networkElements) {
            if (providersToImplement.contains(element.getProvider())) {
                if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) {
                    throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId());
                }
                if (element instanceof NetworkMigrationResponder) {
                    ((NetworkMigrationResponder) element).commitMigration(nicSrc, network, src, src_context, dst_context);
                }
            }
        }
        // update the reservation id
        final NicVO nicVo = _nicDao.findById(nicDst.getId());
        nicVo.setReservationId(nicDst.getReservationId());
        _nicDao.persist(nicVo);
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkMigrationResponder(com.cloud.network.NetworkMigrationResponder) NetworkElement(com.cloud.network.element.NetworkElement) ConfigDriveNetworkElement(com.cloud.network.element.ConfigDriveNetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkGuru(com.cloud.network.guru.NetworkGuru) NicProfile(com.cloud.vm.NicProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) NicVO(com.cloud.vm.NicVO) ReservationContext(com.cloud.vm.ReservationContext) DnsServiceProvider(com.cloud.network.element.DnsServiceProvider) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) Provider(com.cloud.network.Network.Provider)

Example 48 with ReservationContext

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

the class NetworkOrchestrator method rollbackNicForMigration.

@Override
public void rollbackNicForMigration(final VirtualMachineProfile src, final VirtualMachineProfile dst) {
    for (final NicProfile nicDst : dst.getNics()) {
        final NetworkVO network = _networksDao.findById(nicDst.getNetworkId());
        final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
        final NicProfile nicSrc = findNicProfileById(src, nicDst.getId());
        final ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null);
        final ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null);
        if (guru instanceof NetworkMigrationResponder) {
            ((NetworkMigrationResponder) guru).rollbackMigration(nicDst, network, dst, src_context, dst_context);
        }
        if (network.getGuestType() == Network.GuestType.L2 && src.getType() == VirtualMachine.Type.User) {
            _userVmMgr.setupVmForPvlan(true, dst.getVirtualMachine().getHostId(), nicDst);
        }
        final List<Provider> providersToImplement = getNetworkProviders(network.getId());
        for (final NetworkElement element : networkElements) {
            if (providersToImplement.contains(element.getProvider())) {
                if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) {
                    throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId());
                }
                if (element instanceof NetworkMigrationResponder) {
                    ((NetworkMigrationResponder) element).rollbackMigration(nicDst, network, dst, src_context, dst_context);
                }
            }
        }
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkMigrationResponder(com.cloud.network.NetworkMigrationResponder) NetworkElement(com.cloud.network.element.NetworkElement) ConfigDriveNetworkElement(com.cloud.network.element.ConfigDriveNetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkGuru(com.cloud.network.guru.NetworkGuru) NicProfile(com.cloud.vm.NicProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) DnsServiceProvider(com.cloud.network.element.DnsServiceProvider) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) Provider(com.cloud.network.Network.Provider)

Example 49 with ReservationContext

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

the class NetworkOrchestrator method prepareAllNicsForMigration.

/*
    Prepare All Nics for migration including the nics dynamically created and not stored in DB
    This is a temporary workaround work KVM migration
    Once clean fix is added by stored dynamically nics is DB, this workaround won't be needed
     */
@Override
public void prepareAllNicsForMigration(final VirtualMachineProfile vm, final DeployDestination dest) {
    final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), null, null);
    Long guestNetworkId = null;
    for (final NicVO nic : nics) {
        final NetworkVO network = _networksDao.findById(nic.getNetworkId());
        if (network.getTrafficType().equals(TrafficType.Guest) && network.getGuestType().equals(GuestType.Isolated)) {
            guestNetworkId = network.getId();
        }
        final Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
        final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
        final NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
        if (guru instanceof NetworkMigrationResponder) {
            if (!((NetworkMigrationResponder) guru).prepareMigration(profile, network, vm, dest, context)) {
                // XXX: Transaction error
                s_logger.error("NetworkGuru " + guru + " prepareForMigration failed.");
            }
        }
        final List<Provider> providersToImplement = getNetworkProviders(network.getId());
        for (final NetworkElement element : networkElements) {
            if (providersToImplement.contains(element.getProvider())) {
                if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) {
                    throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId());
                }
                if (element instanceof NetworkMigrationResponder) {
                    if (!((NetworkMigrationResponder) element).prepareMigration(profile, network, vm, dest, context)) {
                        // XXX: Transaction error
                        s_logger.error("NetworkElement " + element + " prepareForMigration failed.");
                    }
                }
            }
        }
        guru.updateNicProfile(profile, network);
        vm.addNic(profile);
    }
    final List<String> addedURIs = new ArrayList<String>();
    if (guestNetworkId != null) {
        final List<IPAddressVO> publicIps = _ipAddressDao.listByAssociatedNetwork(guestNetworkId, null);
        for (final IPAddressVO userIp : publicIps) {
            final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
            final URI broadcastUri = BroadcastDomainType.Vlan.toUri(publicIp.getVlanTag());
            final long ntwkId = publicIp.getNetworkId();
            final Nic nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(ntwkId, vm.getId(), broadcastUri.toString());
            if (nic == null && !addedURIs.contains(broadcastUri.toString())) {
                // Nic details are not available in DB
                // Create nic profile for migration
                s_logger.debug("Creating nic profile for migration. BroadcastUri: " + broadcastUri.toString() + " NetworkId: " + ntwkId + " Vm: " + vm.getId());
                final NetworkVO network = _networksDao.findById(ntwkId);
                final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
                final NicProfile profile = new NicProfile();
                // dummyId
                profile.setDeviceId(255);
                profile.setIPv4Address(userIp.getAddress().toString());
                profile.setIPv4Netmask(publicIp.getNetmask());
                profile.setIPv4Gateway(publicIp.getGateway());
                profile.setMacAddress(publicIp.getMacAddress());
                profile.setBroadcastType(network.getBroadcastDomainType());
                profile.setTrafficType(network.getTrafficType());
                profile.setBroadcastUri(broadcastUri);
                profile.setIsolationUri(Networks.IsolationType.Vlan.toUri(publicIp.getVlanTag()));
                profile.setSecurityGroupEnabled(_networkModel.isSecurityGroupSupportedInNetwork(network));
                profile.setName(_networkModel.getNetworkTag(vm.getHypervisorType(), network));
                profile.setNetworkRate(_networkModel.getNetworkRate(network.getId(), vm.getId()));
                profile.setNetworkId(network.getId());
                guru.updateNicProfile(profile, network);
                vm.addNic(profile);
                addedURIs.add(broadcastUri.toString());
            }
        }
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkMigrationResponder(com.cloud.network.NetworkMigrationResponder) PublicIp(com.cloud.network.addr.PublicIp) NetworkGuru(com.cloud.network.guru.NetworkGuru) ArrayList(java.util.ArrayList) Nic(com.cloud.vm.Nic) NicProfile(com.cloud.vm.NicProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) URI(java.net.URI) ReservationContext(com.cloud.vm.ReservationContext) DnsServiceProvider(com.cloud.network.element.DnsServiceProvider) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) Provider(com.cloud.network.Network.Provider) NetworkElement(com.cloud.network.element.NetworkElement) ConfigDriveNetworkElement(com.cloud.network.element.ConfigDriveNetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) NicVO(com.cloud.vm.NicVO)

Example 50 with ReservationContext

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

the class ElasticLoadBalancerManagerImplTest method testFinalizeStartWhenCmdsAnswerIsNotNullAndAnswerResultIsTrue.

@Test
public void testFinalizeStartWhenCmdsAnswerIsNotNullAndAnswerResultIsTrue() throws Exception {
    CheckSshAnswer answerMock = mock(CheckSshAnswer.class);
    when(answerMock.getResult()).thenReturn(true);
    VirtualMachineProfile profileMock = mock(VirtualMachineProfile.class);
    long hostId = 1L;
    Commands cmds = mock(Commands.class);
    when(cmds.getAnswer("checkSsh")).thenReturn(answerMock);
    ReservationContext context = mock(ReservationContext.class);
    boolean expected = true;
    boolean actual = elasticLoadBalancerManagerImpl.finalizeStart(profileMock, hostId, cmds, context);
    assertEquals(expected, actual);
}
Also used : CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) Commands(com.cloud.agent.manager.Commands) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) ReservationContext(com.cloud.vm.ReservationContext) Test(org.junit.Test)

Aggregations

ReservationContext (com.cloud.vm.ReservationContext)72 Account (com.cloud.user.Account)45 ReservationContextImpl (com.cloud.vm.ReservationContextImpl)42 DeployDestination (com.cloud.deploy.DeployDestination)41 NetworkVO (com.cloud.network.dao.NetworkVO)41 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)38 Test (org.junit.Test)33 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)28 NetworkOffering (com.cloud.offering.NetworkOffering)27 Network (com.cloud.network.Network)24 Domain (com.cloud.domain.Domain)23 HostVO (com.cloud.host.HostVO)22 DataCenter (com.cloud.dc.DataCenter)21 URI (java.net.URI)19 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)17 NicProfile (com.cloud.vm.NicProfile)17 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)14 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)14 User (com.cloud.user.User)14 NicVO (com.cloud.vm.NicVO)14