Search in sources :

Example 6 with ReservationContextImpl

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

the class GloboDnsElementTest method testPrepareMethodCallGloboDnsToRegisterHostName.

@Test
public void testPrepareMethodCallGloboDnsToRegisterHostName() throws Exception {
    Network network = mock(Network.class);
    when(network.getDataCenterId()).thenReturn(zoneId);
    when(network.getId()).thenReturn(1l);
    NicProfile nic = new NicProfile();
    nic.setIPv4Address("10.11.12.13");
    VirtualMachineProfile vm = mock(VirtualMachineProfile.class);
    when(vm.getHostName()).thenReturn("vm-name");
    when(vm.getType()).thenReturn(VirtualMachine.Type.User);
    DataCenterVO dataCenterVO = mock(DataCenterVO.class);
    when(dataCenterVO.getId()).thenReturn(zoneId);
    when(_datacenterDao.findById(zoneId)).thenReturn(dataCenterVO);
    DeployDestination dest = new DeployDestination();
    ReservationContext context = new ReservationContextImpl(null, null, user);
    HostVO hostVO = mock(HostVO.class);
    when(hostVO.getId()).thenReturn(globoDnsHostId);
    when(_hostDao.findByTypeNameAndZoneId(eq(zoneId), eq(Provider.GloboDns.getName()), eq(Type.L2Networking))).thenReturn(hostVO);
    when(_agentMgr.easySend(eq(globoDnsHostId), isA(CreateOrUpdateRecordAndReverseCommand.class))).then(new org.mockito.stubbing.Answer<Answer>() {

        @Override
        public Answer answer(InvocationOnMock invocation) throws Throwable {
            Command cmd = (Command) invocation.getArguments()[1];
            return new Answer(cmd);
        }
    });
    _globodnsElement.prepare(network, nic, vm, dest, context);
    verify(_agentMgr, times(1)).easySend(eq(globoDnsHostId), isA(CreateOrUpdateRecordAndReverseCommand.class));
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) NicProfile(com.cloud.vm.NicProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) HostVO(com.cloud.host.HostVO) ReservationContext(com.cloud.vm.ReservationContext) Answer(com.cloud.agent.api.Answer) RemoveRecordCommand(com.globo.globodns.cloudstack.commands.RemoveRecordCommand) CreateOrUpdateRecordAndReverseCommand(com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand) Command(com.cloud.agent.api.Command) DeployDestination(com.cloud.deploy.DeployDestination) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Network(com.cloud.network.Network) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) CreateOrUpdateRecordAndReverseCommand(com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand) Test(org.junit.Test)

Example 7 with ReservationContextImpl

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

the class GloboDnsElementTest method testUpperCaseCharactersAreNotAllowed.

@Test(expected = InvalidParameterValueException.class)
public void testUpperCaseCharactersAreNotAllowed() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    Network network = mock(Network.class);
    when(network.getDataCenterId()).thenReturn(zoneId);
    when(network.getId()).thenReturn(1l);
    NicProfile nic = new NicProfile();
    VirtualMachineProfile vm = mock(VirtualMachineProfile.class);
    when(vm.getHostName()).thenReturn("UPPERCASENAME");
    when(vm.getType()).thenReturn(VirtualMachine.Type.User);
    when(_datacenterDao.findById(zoneId)).thenReturn(mock(DataCenterVO.class));
    DeployDestination dest = new DeployDestination();
    ReservationContext context = new ReservationContextImpl(null, null, user);
    _globodnsElement.prepare(network, nic, vm, dest, context);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) DeployDestination(com.cloud.deploy.DeployDestination) Network(com.cloud.network.Network) NicProfile(com.cloud.vm.NicProfile) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) Test(org.junit.Test)

Example 8 with ReservationContextImpl

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

the class NetworkServiceImpl method updateGuestNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, final Long networkOfferingId, Boolean changeCidr, String guestVmCidr, Boolean displayNetwork, String customId, boolean updateInSequence, boolean forced) {
    boolean restartNetwork = false;
    // verify input parameters
    final NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        // see NetworkVO.java
        InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system");
        ex.addProxyObject(String.valueOf(networkId), "networkId");
        throw ex;
    }
    //perform below validation if the network is vpc network
    if (network.getVpcId() != null && networkOfferingId != null) {
        Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
        _vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), network.getNetworkACLId());
    }
    // don't allow to update network in Destroy state
    if (network.getState() == Network.State.Destroy) {
        throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy);
    }
    // Don't allow to update system network
    NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
    if (offering.isSystemOnly()) {
        throw new InvalidParameterValueException("Can't update system networks");
    }
    // allow to upgrade only Guest networks
    if (network.getTrafficType() != Networks.TrafficType.Guest) {
        throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest);
    }
    _accountMgr.checkAccess(callerAccount, null, true, network);
    if (name != null) {
        network.setName(name);
    }
    if (displayText != null) {
        network.setDisplayText(displayText);
    }
    if (customId != null) {
        network.setUuid(customId);
    }
    // display flag is not null and has changed
    if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
        // Update resource count if it needs to be updated
        NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
        if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
            _resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
        }
        network.setDisplayNetwork(displayNetwork);
    }
    // network offering and domain suffix can be updated for Isolated networks only in 3.0
    if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) {
        throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only");
    }
    boolean networkOfferingChanged = false;
    final long oldNetworkOfferingId = network.getNetworkOfferingId();
    NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
    NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
    if (networkOfferingId != null) {
        if (networkOffering == null || networkOffering.isSystemOnly()) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id");
            ex.addProxyObject(networkOfferingId.toString(), "networkOfferingId");
            throw ex;
        }
        // network offering should be in Enabled state
        if (networkOffering.getState() != NetworkOffering.State.Enabled) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it");
            ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId");
            throw ex;
        }
        //can't update from vpc to non-vpc network offering
        boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
        boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
        if (forVpcNew != vorVpcOriginal) {
            String errMsg = forVpcNew ? "a vpc offering " : "not a vpc offering";
            throw new InvalidParameterValueException("Can't update as the new offering is " + errMsg);
        }
        if (networkOfferingId != oldNetworkOfferingId) {
            Collection<String> newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values();
            Collection<String> oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values();
            if (providersConfiguredForExternalNetworking(newProviders) != providersConfiguredForExternalNetworking(oldProviders) && !changeCidr) {
                throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!");
            }
            if (changeCidr) {
                if (!checkForNonStoppedVmInNetwork(network.getId())) {
                    InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!");
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
            }
            // check if the network is upgradable
            if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) {
                throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() + "; check logs for more information");
            }
            restartNetwork = true;
            networkOfferingChanged = true;
            //Setting the new network's isReduntant to the new network offering's RedundantRouter.
            network.setIsReduntant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
        }
    }
    final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<String, String>();
    // don't allow to modify network domain if the service is not supported
    if (domainSuffix != null) {
        // validate network domain
        if (!NetUtils.verifyDomainName(domainSuffix)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
        long offeringId = oldNetworkOfferingId;
        if (networkOfferingId != null) {
            offeringId = networkOfferingId;
        }
        Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
        String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
        if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
            // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject().
            throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId);
        }
        network.setNetworkDomain(domainSuffix);
        // have to restart the network
        restartNetwork = true;
    }
    //IP reservation checks
    // allow reservation only to Isolated Guest networks
    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    String networkCidr = network.getNetworkCidr();
    if (guestVmCidr != null) {
        if (dc.getNetworkType() == NetworkType.Basic) {
            throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking");
        }
        if (network.getGuestType() != GuestType.Isolated) {
            throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated);
        }
        if (networkOfferingChanged == true) {
            throw new InvalidParameterValueException("Cannot specify this nework offering change and guestVmCidr at same time. Specify only one.");
        }
        if (!(network.getState() == Network.State.Implemented)) {
            throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " + network.getState() + " state");
        }
        if (!NetUtils.isValidCIDR(guestVmCidr)) {
            throw new InvalidParameterValueException("Invalid format of Guest VM CIDR.");
        }
        if (!NetUtils.validateGuestCidr(guestVmCidr)) {
            throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. ");
        }
        // But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr
        if (networkCidr != null) {
            if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) {
                throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR  should be a subset of network CIDR : " + networkCidr);
            }
        } else {
            if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) {
                throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR  should be a subset of network CIDR :  " + network.getCidr());
            }
        }
        // This check makes sure there are no active IPs existing outside the guestVmCidr in the network
        String[] guestVmCidrPair = guestVmCidr.split("\\/");
        Long size = Long.valueOf(guestVmCidrPair[1]);
        List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
        String[] cidrIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
        s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]);
        long startIp = NetUtils.ip2Long(cidrIpRange[0]);
        long endIp = NetUtils.ip2Long(cidrIpRange[1]);
        long range = endIp - startIp + 1;
        s_logger.info("The specified guest vm cidr has " + range + " IPs");
        for (NicVO nic : nicsPresent) {
            long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
            //check if nic IP is outside the guest vm cidr
            if (nicIp < startIp || nicIp > endIp) {
                if (!(nic.getState() == Nic.State.Deallocating)) {
                    throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
                }
            }
        }
        // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
        if (network.getNetworkCidr() == null) {
            if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
                throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
            }
        } else {
            if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
                throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + " are same, " + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " + "specify guestVmCidr to be: " + network.getNetworkCidr());
            }
        }
        // Populate it with the actual network cidr
        if (network.getNetworkCidr() == null) {
            network.setNetworkCidr(network.getCidr());
        }
        // Condition for IP Reservation reset : guestVmCidr and network CIDR are same
        if (network.getNetworkCidr().equals(guestVmCidr)) {
            s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
            network.setNetworkCidr(null);
        }
        // Finally update "cidr" with the guestVmCidr
        // which becomes the effective address space for CloudStack guest VMs
        network.setCidr(guestVmCidr);
        _networksDao.update(networkId, network);
        s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
    }
    ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
    // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
    // states - Shutdown and Implementing
    int resourceCount = 1;
    if (updateInSequence && restartNetwork && _networkOfferingDao.findById(network.getNetworkOfferingId()).getRedundantRouter() && (networkOfferingId == null || _networkOfferingDao.findById(networkOfferingId).getRedundantRouter()) && network.getVpcId() == null) {
        _networkMgr.canUpdateInSequence(network, forced);
        NetworkDetailVO networkDetail = new NetworkDetailVO(network.getId(), Network.updatingInSequence, "true", true);
        _networkDetailsDao.persist(networkDetail);
        _networkMgr.configureUpdateInSequence(network);
        resourceCount = _networkMgr.getResourceCount(network);
    }
    List<String> servicesNotInNewOffering = null;
    if (networkOfferingId != null)
        servicesNotInNewOffering = _networkMgr.getServicesNotSupportedInNewOffering(network, networkOfferingId);
    if (!forced && servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) {
        NetworkOfferingVO newOffering = _networkOfferingDao.findById(networkOfferingId);
        throw new CloudRuntimeException("The new offering:" + newOffering.getUniqueName() + " will remove the following services " + servicesNotInNewOffering + "along with all the related configuration currently in use. will not proceed with the network update." + "set forced parameter to true for forcing an update.");
    }
    try {
        if (servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) {
            _networkMgr.cleanupConfigForServicesInNetwork(servicesNotInNewOffering, network);
        }
    } catch (Throwable e) {
        s_logger.debug("failed to cleanup config related to unused services error:" + e.getMessage());
    }
    boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated);
    try {
        do {
            if (restartNetwork) {
                if (validStateToShutdown) {
                    if (!changeCidr) {
                        s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update");
                        if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) {
                            s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network);
                            CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of specified id");
                            ex.addProxyObject(network.getUuid(), "networkId");
                            throw ex;
                        }
                    } else {
                        // We need to shutdown the network, since we want to re-implement the network.
                        s_logger.debug("Shutting down network id=" + networkId + " as a part of network update");
                        //check if network has reservation
                        if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) {
                            s_logger.warn("Existing IP reservation will become ineffective for the network with id =  " + networkId + " You need to reapply reservation after network reimplementation.");
                            //set cidr to the newtork cidr
                            network.setCidr(network.getNetworkCidr());
                            //set networkCidr to null to bring network back to no IP reservation state
                            network.setNetworkCidr(null);
                        }
                        if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) {
                            s_logger.warn("Failed to shutdown the network as a part of update to network with specified id");
                            CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id");
                            ex.addProxyObject(network.getUuid(), "networkId");
                            throw ex;
                        }
                    }
                } else {
                    CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState());
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
            }
            // 2) Only after all the elements and rules are shutdown properly, update the network VO
            // get updated network
            Network.State networkState = _networksDao.findById(networkId).getState();
            boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated);
            if (restartNetwork && !validStateToImplement) {
                CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState);
                ex.addProxyObject(network.getUuid(), "networkId");
                throw ex;
            }
            if (networkOfferingId != null) {
                if (networkOfferingChanged) {
                    Transaction.execute(new TransactionCallbackNoReturn() {

                        @Override
                        public void doInTransactionWithoutResult(TransactionStatus status) {
                            network.setNetworkOfferingId(networkOfferingId);
                            _networksDao.update(networkId, network, newSvcProviders);
                            // get all nics using this network
                            // log remove usage events for old offering
                            // log assign usage events for new offering
                            List<NicVO> nics = _nicDao.listByNetworkId(networkId);
                            for (NicVO nic : nics) {
                                long vmId = nic.getInstanceId();
                                VMInstanceVO vm = _vmDao.findById(vmId);
                                if (vm == null) {
                                    s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
                                    continue;
                                }
                                long isDefault = (nic.isDefaultNic()) ? 1 : 0;
                                String nicIdString = Long.toString(nic.getId());
                                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
                                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
                            }
                        }
                    });
                } else {
                    network.setNetworkOfferingId(networkOfferingId);
                    _networksDao.update(networkId, network, _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
                }
            } else {
                _networksDao.update(networkId, network);
            }
            // 3) Implement the elements and rules again
            if (restartNetwork) {
                if (network.getState() != Network.State.Allocated) {
                    DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null);
                    s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update");
                    try {
                        if (!changeCidr) {
                            _networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId()));
                        } else {
                            _networkMgr.implementNetwork(network.getId(), dest, context);
                        }
                    } catch (Exception ex) {
                        s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
                        CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update");
                        e.addProxyObject(network.getUuid(), "networkId");
                        throw e;
                    }
                }
            }
            // implement the network if its not already
            if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
                if (network.getState() == Network.State.Allocated) {
                    try {
                        DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null);
                        _networkMgr.implementNetwork(network.getId(), dest, context);
                    } catch (Exception ex) {
                        s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
                        CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network update");
                        e.addProxyObject(network.getUuid(), "networkId");
                        throw e;
                    }
                }
            }
            resourceCount--;
        } while (updateInSequence && resourceCount > 0);
    } catch (Exception exception) {
        if (updateInSequence)
            _networkMgr.finalizeUpdateInSequence(network, false);
        throw new CloudRuntimeException("failed to update network " + network.getUuid() + " due to " + exception.getMessage());
    } finally {
        if (updateInSequence) {
            if (_networkDetailsDao.findDetail(networkId, Network.updatingInSequence) != null) {
                _networkDetailsDao.removeDetail(networkId, Network.updatingInSequence);
            }
        }
    }
    return getNetwork(network.getId());
}
Also used : Vpc(com.cloud.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) NicVO(com.cloud.vm.NicVO) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) Capability(com.cloud.network.Network.Capability) NetworkOffering(com.cloud.offering.NetworkOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) UnknownHostException(java.net.UnknownHostException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DataCenter(com.cloud.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 9 with ReservationContextImpl

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

the class NetworkServiceImpl method deleteNetwork.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true)
public boolean deleteNetwork(long networkId, boolean forced) {
    Account caller = CallContext.current().getCallingAccount();
    // Verify network id
    NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        // see NetworkVO.java
        InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id");
        ex.addProxyObject(String.valueOf(networkId), "networkId");
        throw ex;
    }
    // don't allow to delete system network
    if (isNetworkSystem(network)) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed");
        ex.addProxyObject(network.getUuid(), "networkId");
        throw ex;
    }
    Account owner = _accountMgr.getAccount(network.getAccountId());
    // Only Admin can delete Shared networks
    if (network.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Only Admins can delete network with guest type " + GuestType.Shared);
    }
    // Perform permission check
    _accountMgr.checkAccess(caller, null, true, network);
    if (forced && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins");
    }
    User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
    return _networkMgr.destroyNetwork(networkId, context, forced);
}
Also used : Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) ActionEvent(com.cloud.event.ActionEvent)

Example 10 with ReservationContextImpl

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

the class DomainManagerImpl method cleanupDomain.

protected boolean cleanupDomain(Long domainId, Long ownerId) throws ConcurrentOperationException, ResourceUnavailableException {
    s_logger.debug("Cleaning up domain id=" + domainId);
    boolean success = true;
    DomainVO domainHandle = _domainDao.findById(domainId);
    {
        domainHandle.setState(Domain.State.Inactive);
        _domainDao.update(domainId, domainHandle);
        SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("parent", SearchCriteria.Op.EQ, domainId);
        List<DomainVO> domains = _domainDao.search(sc, null);
        SearchCriteria<DomainVO> sc1 = _domainDao.createSearchCriteria();
        sc1.addAnd("path", SearchCriteria.Op.LIKE, "%" + "replace(" + domainHandle.getPath() + ", '%', '[%]')" + "%");
        List<DomainVO> domainsToBeInactivated = _domainDao.search(sc1, null);
        // update all subdomains to inactive so no accounts/users can be created
        for (DomainVO domain : domainsToBeInactivated) {
            domain.setState(Domain.State.Inactive);
            _domainDao.update(domain.getId(), domain);
        }
        // cleanup sub-domains first
        for (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
    SearchCriteria<AccountVO> sc = _accountDao.createSearchCriteria();
    sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
    List<AccountVO> accounts = _accountDao.search(sc, null);
    for (AccountVO account : accounts) {
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            s_logger.debug("Deleting account " + account + " as a part of domain id=" + domainId + " cleanup");
            boolean deleteAccount = _accountMgr.deleteAccount(account, CallContext.current().getCallingUserId(), getCaller());
            if (!deleteAccount) {
                s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup");
            }
            success = (success && deleteAccount);
        } else {
            ProjectVO project = _projectDao.findByProjectAccountId(account.getId());
            s_logger.debug("Deleting project " + project + " as a part of domain id=" + domainId + " cleanup");
            boolean deleteProject = _projectMgr.deleteProject(getCaller(), 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);
    List<Long> networkIds = _networkDomainDao.listNetworkIdsByDomain(domainId);
    CallContext ctx = CallContext.current();
    ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallingUserId()), ctx.getCallingAccount());
    for (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
    boolean deleteDomainSuccess = true;
    List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
    if (accountsForCleanup.isEmpty()) {
        //release dedication if any, before deleting the domain
        List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByDomainId(domainId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for domain" + domainId);
            for (DedicatedResourceVO dr : dedicatedResources) {
                if (!_dedicatedDao.remove(dr.getId())) {
                    s_logger.warn("Fail to release dedicated resources for domain " + domainId);
                    return false;
                }
            }
        }
        //delete domain
        _messageBus.publish(_name, MESSAGE_PRE_REMOVE_DOMAIN_EVENT, PublishScope.LOCAL, domainHandle);
        deleteDomainSuccess = _domainDao.remove(domainId);
        _messageBus.publish(_name, MESSAGE_REMOVE_DOMAIN_EVENT, PublishScope.LOCAL, domainHandle);
        // 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(org.apache.cloudstack.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)

Aggregations

ReservationContextImpl (com.cloud.vm.ReservationContextImpl)20 ReservationContext (com.cloud.vm.ReservationContext)19 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)10 NetworkVO (com.cloud.network.dao.NetworkVO)9 DeployDestination (com.cloud.deploy.DeployDestination)8 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)8 Account (com.cloud.user.Account)8 NicProfile (com.cloud.vm.NicProfile)7 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)6 DataCenter (com.cloud.dc.DataCenter)5 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)5 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)5 User (com.cloud.user.User)5 NicVO (com.cloud.vm.NicVO)5 ActionEvent (com.cloud.event.ActionEvent)4 Provider (com.cloud.network.Network.Provider)4 NetworkElement (com.cloud.network.element.NetworkElement)4 StaticNatServiceProvider (com.cloud.network.element.StaticNatServiceProvider)4 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)4