Search in sources :

Example 56 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class UserVmManagerImpl method collectVmDiskStatistics.

@Override
public void collectVmDiskStatistics(final UserVmVO userVm) {
    // support KVM only util 2013.06.25
    if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
        return;
    s_logger.debug("Collect vm disk statistics from host before stopping Vm");
    long hostId = userVm.getHostId();
    List<String> vmNames = new ArrayList<String>();
    vmNames.add(userVm.getInstanceName());
    final HostVO host = _hostDao.findById(hostId);
    GetVmDiskStatsAnswer diskStatsAnswer = null;
    try {
        diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
    } catch (Exception e) {
        s_logger.warn("Error while collecting disk stats for vm: " + userVm.getInstanceName() + " from host: " + host.getName(), e);
        return;
    }
    if (diskStatsAnswer != null) {
        if (!diskStatsAnswer.getResult()) {
            s_logger.warn("Error while collecting disk stats vm: " + userVm.getInstanceName() + " from host: " + host.getName() + "; details: " + diskStatsAnswer.getDetails());
            return;
        }
        try {
            final GetVmDiskStatsAnswer diskStatsAnswerFinal = diskStatsAnswer;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswerFinal.getVmDiskStatsMap();
                    if (vmDiskStatsByName == null)
                        return;
                    List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
                    if (vmDiskStats == null)
                        return;
                    for (VmDiskStatsEntry vmDiskStat : vmDiskStats) {
                        SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
                        sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
                        List<VolumeVO> volumes = _volsDao.search(sc_volume, null);
                        if ((volumes == null) || (volumes.size() == 0))
                            break;
                        VolumeVO volume = volumes.get(0);
                        VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
                        VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
                        if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) {
                            s_logger.debug("Read/Write of IO and Bytes are both 0. Not updating vm_disk_statistics");
                            continue;
                        }
                        if (vmDiskStat_lock == null) {
                            s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + " and volumeId:" + volume.getId());
                            continue;
                        }
                        if (previousVmDiskStats != null && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock.getCurrentIOWrite()) || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats.getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) {
                            s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() + " Bytes Read: " + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite());
                            continue;
                        }
                        if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Read # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead());
                            }
                            vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
                        }
                        vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead());
                        if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Write # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite());
                            }
                            vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
                        }
                        vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite());
                        if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Read # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead());
                            }
                            vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
                        }
                        vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead());
                        if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Write # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + vmDiskStat_lock.getCurrentBytesWrite());
                            }
                            vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
                        }
                        vmDiskStat_lock.setCurrentBytesWrite(vmDiskStat.getBytesWrite());
                        if (!_dailyOrHourly) {
                            //update agg bytes
                            vmDiskStat_lock.setAggIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
                            vmDiskStat_lock.setAggIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
                            vmDiskStat_lock.setAggBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
                            vmDiskStat_lock.setAggBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
                        }
                        _vmDiskStatsDao.update(vmDiskStat_lock.getId(), vmDiskStat_lock);
                    }
                }
            });
        } catch (Exception e) {
            s_logger.warn("Unable to update vm disk statistics for vm: " + userVm.getId() + " from host: " + hostId, e);
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VmDiskStatisticsVO(com.cloud.user.VmDiskStatisticsVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) VmDiskStatsEntry(com.cloud.agent.api.VmDiskStatsEntry) HostVO(com.cloud.host.HostVO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) SearchCriteria(com.cloud.utils.db.SearchCriteria) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer) GetVmDiskStatsCommand(com.cloud.agent.api.GetVmDiskStatsCommand) VolumeVO(com.cloud.storage.VolumeVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List)

Example 57 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class CiscoNexusVSMElement method validateAndAddVsm.

@Override
@DB
public Pair<Boolean, Long> validateAndAddVsm(final String vsmIp, final String vsmUser, final String vsmPassword, final long clusterId, String clusterName) throws ResourceInUseException {
    CiscoNexusVSMDeviceVO vsm = null;
    boolean vsmAdded = false;
    Long vsmId = 0L;
    if (vsmIp != null && vsmUser != null && vsmPassword != null) {
        NetconfHelper netconfClient;
        try {
            netconfClient = new NetconfHelper(vsmIp, vsmUser, vsmPassword);
            netconfClient.disconnect();
        } catch (CloudRuntimeException e) {
            String msg = "Invalid credentials supplied for user " + vsmUser + " for Cisco Nexus 1000v VSM at " + vsmIp;
            s_logger.error(msg);
            _clusterDao.remove(clusterId);
            throw new CloudRuntimeException(msg);
        }
        // If VSM already exists and is mapped to a cluster, fail this operation.
        vsm = _vsmDao.getVSMbyIpaddress(vsmIp);
        if (vsm != null) {
            List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsm.getId());
            if (clusterList != null && !clusterList.isEmpty()) {
                s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster");
                ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id");
                // get clusterUuid to report error
                ClusterVO cluster = _clusterDao.findById(clusterList.get(0).getClusterId());
                ex.addProxyObject(cluster.getUuid());
                _clusterDao.remove(clusterId);
                throw ex;
            }
        }
        // persist credentials to database if the VSM entry is not already in the db.
        vsm = Transaction.execute(new TransactionCallback<CiscoNexusVSMDeviceVO>() {

            @Override
            public CiscoNexusVSMDeviceVO doInTransaction(TransactionStatus status) {
                CiscoNexusVSMDeviceVO vsm = null;
                if (_vsmDao.getVSMbyIpaddress(vsmIp) == null) {
                    vsm = new CiscoNexusVSMDeviceVO(vsmIp, vsmUser, vsmPassword);
                    _vsmDao.persist(vsm);
                }
                // Create a mapping between the cluster and the vsm.
                vsm = _vsmDao.getVSMbyIpaddress(vsmIp);
                if (vsm != null) {
                    ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsm.getId());
                    _clusterVSMDao.persist(connectorObj);
                }
                return vsm;
            }
        });
    } else {
        String msg;
        msg = "The global parameter " + Config.VmwareUseNexusVSwitch.toString() + " is set to \"true\". Following mandatory parameters are not specified. ";
        if (vsmIp == null) {
            msg += "vsmipaddress: Management IP address of Cisco Nexus 1000v dvSwitch. ";
        }
        if (vsmUser == null) {
            msg += "vsmusername: Name of a user account with admin privileges over Cisco Nexus 1000v dvSwitch. ";
        }
        if (vsmPassword == null) {
            if (vsmUser != null) {
                msg += "vsmpassword: Password of user account " + vsmUser + ". ";
            } else {
                msg += "vsmpassword: Password of user account with admin privileges over Cisco Nexus 1000v dvSwitch. ";
            }
        }
        s_logger.error(msg);
        // Cleaning up the cluster record as addCluster operation failed because of invalid credentials of Nexus dvSwitch.
        _clusterDao.remove(clusterId);
        throw new CloudRuntimeException(msg);
    }
    if (vsm != null) {
        vsmAdded = true;
        vsmId = vsm.getId();
    }
    return new Pair<Boolean, Long>(vsmAdded, vsmId);
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) CiscoNexusVSMDeviceVO(com.cloud.network.CiscoNexusVSMDeviceVO) ClusterVSMMapVO(com.cloud.dc.ClusterVSMMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallback(com.cloud.utils.db.TransactionCallback) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) NetconfHelper(com.cloud.utils.cisco.n1kv.vsm.NetconfHelper) Pair(com.cloud.utils.Pair) DB(com.cloud.utils.db.DB)

Example 58 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class ConfigurationManagerImpl method deletePod.

@Override
@DB
public boolean deletePod(final DeletePodCmd cmd) {
    final Long podId = cmd.getId();
    // Make sure the pod exists
    if (!validPod(podId)) {
        throw new InvalidParameterValueException("A pod with ID: " + podId + " does not exist.");
    }
    checkIfPodIsDeletable(podId);
    final HostPodVO pod = _podDao.findById(podId);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            // Delete private ip addresses for the pod if there are any
            final List<DataCenterIpAddressVO> privateIps = _privateIpAddressDao.listByPodIdDcId(podId, pod.getDataCenterId());
            if (!privateIps.isEmpty()) {
                if (!_privateIpAddressDao.deleteIpAddressByPod(podId)) {
                    throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
                }
            }
            // Delete link local ip addresses for the pod
            final List<DataCenterLinkLocalIpAddressVO> localIps = _linkLocalIpAllocDao.listByPodIdDcId(podId, pod.getDataCenterId());
            if (!localIps.isEmpty()) {
                if (!_linkLocalIpAllocDao.deleteIpAddressByPod(podId)) {
                    throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
                }
            }
            // Delete vlans associated with the pod
            final List<? extends Vlan> vlans = _networkModel.listPodVlans(podId);
            if (vlans != null && !vlans.isEmpty()) {
                for (final Vlan vlan : vlans) {
                    _vlanDao.remove(vlan.getId());
                }
            }
            // Delete corresponding capacity records
            _capacityDao.removeBy(null, null, podId, null, null);
            // Delete the pod
            if (!_podDao.remove(podId)) {
                throw new CloudRuntimeException("Failed to delete pod " + podId);
            }
            // remove from dedicated resources
            final DedicatedResourceVO dr = _dedicatedDao.findByPodId(podId);
            if (dr != null) {
                _dedicatedDao.remove(dr.getId());
            }
        }
    });
    return true;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ArrayList(java.util.ArrayList) List(java.util.List) Vlan(com.cloud.dc.Vlan) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) HostPodVO(com.cloud.dc.HostPodVO) DB(com.cloud.utils.db.DB)

Example 59 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class CapacityManagerImpl method allocateVmCapacity.

@DB
@Override
public void allocateVmCapacity(VirtualMachine vm, final boolean fromLastHost) {
    final long hostId = vm.getHostId();
    HostVO host = _hostDao.findById(hostId);
    final long clusterId = host.getClusterId();
    final float cpuOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio").getValue());
    final float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "memoryOvercommitRatio").getValue());
    final ServiceOfferingVO svo = _offeringsDao.findById(vm.getId(), vm.getServiceOfferingId());
    CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, Capacity.CAPACITY_TYPE_CPU);
    CapacityVO capacityMem = _capacityDao.findByHostIdType(hostId, Capacity.CAPACITY_TYPE_MEMORY);
    if (capacityCpu == null || capacityMem == null || svo == null) {
        return;
    }
    final int cpu = svo.getCpu() * svo.getSpeed();
    final long ram = svo.getRamSize() * 1024L * 1024L;
    try {
        final long capacityCpuId = capacityCpu.getId();
        final long capacityMemId = capacityMem.getId();
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                CapacityVO capacityCpu = _capacityDao.lockRow(capacityCpuId, true);
                CapacityVO capacityMem = _capacityDao.lockRow(capacityMemId, true);
                long usedCpu = capacityCpu.getUsedCapacity();
                long usedMem = capacityMem.getUsedCapacity();
                long reservedCpu = capacityCpu.getReservedCapacity();
                long reservedMem = capacityMem.getReservedCapacity();
                long actualTotalCpu = capacityCpu.getTotalCapacity();
                long actualTotalMem = capacityMem.getTotalCapacity();
                long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
                long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
                }
                long freeCpu = totalCpu - (reservedCpu + usedCpu);
                long freeMem = totalMem - (reservedMem + usedMem);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("We are allocating VM, increasing the used capacity of this host:" + hostId);
                    s_logger.debug("Current Used CPU: " + usedCpu + " , Free CPU:" + freeCpu + " ,Requested CPU: " + cpu);
                    s_logger.debug("Current Used RAM: " + usedMem + " , Free RAM:" + freeMem + " ,Requested RAM: " + ram);
                }
                capacityCpu.setUsedCapacity(usedCpu + cpu);
                capacityMem.setUsedCapacity(usedMem + ram);
                if (fromLastHost) {
                    /* alloc from reserved */
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("We are allocating VM to the last host again, so adjusting the reserved capacity if it is not less than required");
                        s_logger.debug("Reserved CPU: " + reservedCpu + " , Requested CPU: " + cpu);
                        s_logger.debug("Reserved RAM: " + reservedMem + " , Requested RAM: " + ram);
                    }
                    if (reservedCpu >= cpu && reservedMem >= ram) {
                        capacityCpu.setReservedCapacity(reservedCpu - cpu);
                        capacityMem.setReservedCapacity(reservedMem - ram);
                    }
                } else {
                    /* alloc from free resource */
                    if (!((reservedCpu + usedCpu + cpu <= totalCpu) && (reservedMem + usedMem + ram <= totalMem))) {
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Host doesnt seem to have enough free capacity, but increasing the used capacity anyways, " + "since the VM is already starting on this host ");
                        }
                    }
                }
                s_logger.debug("CPU STATS after allocation: for host: " + hostId + ", old used: " + usedCpu + ", old reserved: " + reservedCpu + ", actual total: " + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used:" + capacityCpu.getUsedCapacity() + ", reserved:" + capacityCpu.getReservedCapacity() + "; requested cpu:" + cpu + ",alloc_from_last:" + fromLastHost);
                s_logger.debug("RAM STATS after allocation: for host: " + hostId + ", old used: " + usedMem + ", old reserved: " + reservedMem + ", total: " + totalMem + "; new used: " + capacityMem.getUsedCapacity() + ", reserved: " + capacityMem.getReservedCapacity() + "; requested mem: " + ram + ",alloc_from_last:" + fromLastHost);
                _capacityDao.update(capacityCpu.getId(), capacityCpu);
                _capacityDao.update(capacityMem.getId(), capacityMem);
            }
        });
    } catch (Exception e) {
        s_logger.error("Exception allocating VM capacity", e);
        return;
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) ConnectionException(com.cloud.exception.ConnectionException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DB(com.cloud.utils.db.DB)

Example 60 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class ConfigurationManagerImpl method createZone.

@Override
@DB
public DataCenterVO createZone(final long userId, final String zoneName, final String dns1, final String dns2, final String internalDns1, final String internalDns2, final String guestCidr, final String domain, final Long domainId, final NetworkType zoneType, final String allocationStateStr, final String networkDomain, final boolean isSecurityGroupEnabled, final boolean isLocalStorageEnabled, final String ip6Dns1, final String ip6Dns2) {
    // hence the method below is generic to check for common params
    if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) {
        throw new InvalidParameterValueException("Please enter a valid guest cidr");
    }
    // Validate network domain
    if (networkDomain != null) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            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 \"-\"");
        }
    }
    checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, true, domainId, allocationStateStr, ip6Dns1, ip6Dns2);
    final byte[] bytes = (zoneName + System.currentTimeMillis()).getBytes();
    final String zoneToken = UUID.nameUUIDFromBytes(bytes).toString();
    // Create the new zone in the database
    final DataCenterVO zoneFinal = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2);
    if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
        final Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
        zoneFinal.setAllocationState(allocationState);
    } else {
        // Zone will be disabled since 3.0. Admin should enable it after
        // physical network and providers setup.
        zoneFinal.setAllocationState(Grouping.AllocationState.Disabled);
    }
    return Transaction.execute(new TransactionCallback<DataCenterVO>() {

        @Override
        public DataCenterVO doInTransaction(final TransactionStatus status) {
            final DataCenterVO zone = _zoneDao.persist(zoneFinal);
            CallContext.current().putContextParameter(DataCenter.class, zone.getUuid());
            if (domainId != null) {
                // zone is explicitly dedicated to this domain
                // create affinity group associated and dedicate the zone.
                final AffinityGroup group = createDedicatedAffinityGroup(null, domainId, null);
                final DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zone.getId(), null, null, null, domainId, null, group.getId());
                _dedicatedDao.persist(dedicatedResource);
            }
            // Create default system networks
            createDefaultSystemNetworks(zone.getId());
            return zone;
        }
    });
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AllocationState(com.cloud.org.Grouping.AllocationState) TransactionStatus(com.cloud.utils.db.TransactionStatus) Grouping(com.cloud.org.Grouping) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) AffinityGroup(org.apache.cloudstack.affinity.AffinityGroup) DB(com.cloud.utils.db.DB)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)171 DB (com.cloud.utils.db.DB)139 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)100 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)93 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)77 ArrayList (java.util.ArrayList)54 Account (com.cloud.user.Account)44 List (java.util.List)44 ActionEvent (com.cloud.event.ActionEvent)40 ConfigurationException (javax.naming.ConfigurationException)40 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)35 IPAddressVO (com.cloud.network.dao.IPAddressVO)26 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)26 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)23 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)23 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)22 HashMap (java.util.HashMap)22 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)21 Network (com.cloud.network.Network)20 DataCenterVO (com.cloud.dc.DataCenterVO)17