Search in sources :

Example 1 with AllocationState

use of com.cloud.model.enumeration.AllocationState in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method editPod.

@Override
@DB
public Pod editPod(final long id, String name, String startIp, String endIp, String gateway, String netmask, String allocationStateStr) {
    // verify parameters
    final HostPodVO pod = _podDao.findById(id);
    if (pod == null) {
        throw new InvalidParameterValueException("Unable to find pod by id " + id);
    }
    final String[] existingPodIpRange = pod.getDescription().split("-");
    String[] leftRangeToAdd = null;
    String[] rightRangeToAdd = null;
    boolean allowToDownsize = false;
    // pod has allocated private IP addresses
    if (podHasAllocatedPrivateIPs(id)) {
        if (netmask != null) {
            final long newCidr = NetUtils.getCidrSize(netmask);
            final long oldCidr = pod.getCidrSize();
            if (newCidr > oldCidr) {
                throw new CloudRuntimeException("The specified pod has allocated private IP addresses, so its IP address range can be extended only");
            }
        }
        if (startIp != null && !startIp.equals(existingPodIpRange[0])) {
            if (NetUtils.ipRangesOverlap(startIp, null, existingPodIpRange[0], existingPodIpRange[1])) {
                throw new CloudRuntimeException("The specified pod has allocated private IP addresses, so its IP address range can be extended only");
            } else {
                leftRangeToAdd = new String[2];
                final long endIpForUpdate = NetUtils.ip2Long(existingPodIpRange[0]) - 1;
                leftRangeToAdd[0] = startIp;
                leftRangeToAdd[1] = NetUtils.long2Ip(endIpForUpdate);
            }
        }
        if (endIp != null && !endIp.equals(existingPodIpRange[1])) {
            if (NetUtils.ipRangesOverlap(endIp, endIp, existingPodIpRange[0], existingPodIpRange[1])) {
                throw new CloudRuntimeException("The specified pod has allocated private IP addresses, so its IP address range can be extended only");
            } else {
                rightRangeToAdd = new String[2];
                final long startIpForUpdate = NetUtils.ip2Long(existingPodIpRange[1]) + 1;
                rightRangeToAdd[0] = NetUtils.long2Ip(startIpForUpdate);
                rightRangeToAdd[1] = endIp;
            }
        }
    } else {
        allowToDownsize = true;
    }
    if (gateway == null) {
        gateway = pod.getGateway();
    }
    if (netmask == null) {
        netmask = NetUtils.getCidrNetmask(pod.getCidrSize());
    }
    final String oldPodName = pod.getName();
    if (name == null) {
        name = oldPodName;
    }
    if (gateway == null) {
        gateway = pod.getGateway();
    }
    if (startIp == null) {
        startIp = existingPodIpRange[0];
    }
    if (endIp == null) {
        endIp = existingPodIpRange[1];
    }
    if (allocationStateStr == null) {
        allocationStateStr = pod.getAllocationState().toString();
    }
    // Verify pod's attributes
    final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
    final boolean checkForDuplicates = !oldPodName.equals(name);
    checkPodAttributes(id, name, pod.getDataCenterId(), gateway, cidr, startIp, endIp, allocationStateStr, checkForDuplicates, false);
    try {
        final String[] existingPodIpRangeFinal = existingPodIpRange;
        final String[] leftRangeToAddFinal = leftRangeToAdd;
        final String[] rightRangeToAddFinal = rightRangeToAdd;
        final boolean allowToDownsizeFinal = allowToDownsize;
        final String allocationStateStrFinal = allocationStateStr;
        final String startIpFinal = startIp;
        final String endIpFinal = endIp;
        final String nameFinal = name;
        final String gatewayFinal = gateway;
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                final long zoneId = pod.getDataCenterId();
                String startIp = startIpFinal;
                String endIp = endIpFinal;
                if (!allowToDownsizeFinal) {
                    if (leftRangeToAddFinal != null) {
                        _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), leftRangeToAddFinal[0], leftRangeToAddFinal[1]);
                    }
                    if (rightRangeToAddFinal != null) {
                        _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), rightRangeToAddFinal[0], rightRangeToAddFinal[1]);
                    }
                } else {
                    // delete the old range
                    _zoneDao.deletePrivateIpAddressByPod(pod.getId());
                    // add the new one
                    if (startIp == null) {
                        startIp = existingPodIpRangeFinal[0];
                    }
                    if (endIp == null) {
                        endIp = existingPodIpRangeFinal[1];
                    }
                    _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
                }
                pod.setName(nameFinal);
                pod.setDataCenterId(zoneId);
                pod.setGateway(gatewayFinal);
                pod.setCidrAddress(getCidrAddress(cidr));
                pod.setCidrSize(getCidrSize(cidr));
                final String ipRange = startIp + "-" + endIp;
                pod.setDescription(ipRange);
                final AllocationState allocationState;
                if (allocationStateStrFinal != null && !allocationStateStrFinal.isEmpty()) {
                    allocationState = AllocationState.valueOf(allocationStateStrFinal);
                    pod.setAllocationState(allocationState);
                }
                _podDao.update(id, pod);
            }
        });
    } catch (final Exception e) {
        s_logger.error("Unable to edit pod due to " + e.getMessage(), e);
        throw new CloudRuntimeException("Failed to edit pod. Please contact Cloud Support.");
    }
    return pod;
}
Also used : InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) AllocationState(com.cloud.model.enumeration.AllocationState) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) HostPodVO(com.cloud.dc.HostPodVO) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DB(com.cloud.utils.db.DB)

Example 2 with AllocationState

use of com.cloud.model.enumeration.AllocationState in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method editZone.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ZONE_EDIT, eventDescription = "editing zone", async = false)
public DataCenter editZone(final UpdateZoneCmd cmd) {
    // Parameter validation as from execute() method in V1
    final Long zoneId = cmd.getId();
    String zoneName = cmd.getZoneName();
    String dns1 = cmd.getDns1();
    String dns2 = cmd.getDns2();
    String ip6Dns1 = cmd.getIp6Dns1();
    String ip6Dns2 = cmd.getIp6Dns2();
    String internalDns1 = cmd.getInternalDns1();
    String internalDns2 = cmd.getInternalDns2();
    String guestCidr = cmd.getGuestCidrAddress();
    final List<String> dnsSearchOrder = cmd.getDnsSearchOrder();
    final Boolean isPublic = cmd.isPublic();
    final String allocationStateStr = cmd.getAllocationState();
    final String dhcpProvider = cmd.getDhcpProvider();
    final Map<?, ?> detailsMap = cmd.getDetails();
    final String networkDomain = cmd.getDomain();
    final Boolean localStorageEnabled = cmd.getLocalStorageEnabled();
    final Map<String, String> newDetails = new HashMap<>();
    if (detailsMap != null) {
        final Collection<?> zoneDetailsCollection = detailsMap.values();
        final Iterator<?> iter = zoneDetailsCollection.iterator();
        while (iter.hasNext()) {
            final HashMap<?, ?> detail = (HashMap<?, ?>) iter.next();
            final String key = (String) detail.get("key");
            final String value = (String) detail.get("value");
            if (key == null || value == null) {
                throw new InvalidParameterValueException("Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form:  details[0].key=XXX&details[0].value=YYY");
            }
            newDetails.put(key, value);
        }
    }
    // add the domain prefix list to details if not null
    if (dnsSearchOrder != null) {
        for (final String dom : dnsSearchOrder) {
            if (!NetUtils.verifyDomainName(dom)) {
                throw new InvalidParameterValueException("Invalid network domain suffixes. 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 \"-\"");
            }
        }
        newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ","));
    }
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
    }
    if (zoneName == null) {
        zoneName = zone.getName();
    }
    if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) {
        throw new InvalidParameterValueException("Please enter a valid guest cidr");
    }
    // Make sure the zone exists
    if (!validZone(zoneId)) {
        throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist.");
    }
    final String oldZoneName = zone.getName();
    if (zoneName == null) {
        zoneName = oldZoneName;
    }
    if (dns1 == null) {
        dns1 = zone.getDns1();
    }
    if (dns2 == null) {
        dns2 = zone.getDns2();
    }
    if (ip6Dns1 == null) {
        ip6Dns1 = zone.getIp6Dns1();
    }
    if (ip6Dns2 == null) {
        ip6Dns2 = zone.getIp6Dns2();
    }
    if (internalDns1 == null) {
        internalDns1 = zone.getInternalDns1();
    }
    if (internalDns2 == null) {
        internalDns2 = zone.getInternalDns2();
    }
    if (guestCidr == null) {
        guestCidr = zone.getGuestNetworkCidr();
    }
    // validate network domain
    if (networkDomain != null && !networkDomain.isEmpty()) {
        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 \"-\"");
        }
    }
    final boolean checkForDuplicates = !zoneName.equals(oldZoneName);
    // not allowing updating
    checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, checkForDuplicates, null, allocationStateStr, ip6Dns1, ip6Dns2);
    // domain associated with
    // a zone, once created
    zone.setName(zoneName);
    zone.setDns1(dns1);
    zone.setDns2(dns2);
    zone.setIp6Dns1(ip6Dns1);
    zone.setIp6Dns2(ip6Dns2);
    zone.setInternalDns1(internalDns1);
    zone.setInternalDns2(internalDns2);
    zone.setGuestNetworkCidr(guestCidr);
    if (localStorageEnabled != null) {
        zone.setLocalStorageEnabled(localStorageEnabled.booleanValue());
    }
    if (networkDomain != null) {
        if (networkDomain.isEmpty()) {
            zone.setDomain(null);
        } else {
            zone.setDomain(networkDomain);
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final Map<String, String> updatedDetails = new HashMap<>();
            _zoneDao.loadDetails(zone);
            if (zone.getDetails() != null) {
                updatedDetails.putAll(zone.getDetails());
            }
            updatedDetails.putAll(newDetails);
            zone.setDetails(updatedDetails);
            if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
                final AllocationState allocationState = AllocationState.valueOf(allocationStateStr);
                if (allocationState == AllocationState.Enabled) {
                    // check if zone has necessary trafficTypes before enabling
                    try {
                        final PhysicalNetwork mgmtPhyNetwork;
                        // zone should have a physical network with management
                        // traffiType
                        mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
                        if (NetworkType.Advanced == zone.getNetworkType()) {
                            // advanced zone should have a physical network with public type
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                        }
                        try {
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
                        } catch (final InvalidParameterValueException noStorage) {
                            final PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management);
                            _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), "vlan", mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVlan());
                            s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type");
                        }
                    } catch (final InvalidParameterValueException ex) {
                        throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage());
                    }
                }
                zone.setAllocationState(allocationState);
            }
            // update a private zone to public; not vice versa
            if (isPublic != null && isPublic) {
                zone.setDomainId(null);
                zone.setDomain(null);
                // release the dedication for this zone
                final DedicatedResourceVO resource = _dedicatedDao.findByZoneId(zoneId);
                final Long resourceId;
                if (resource != null) {
                    resourceId = resource.getId();
                    if (!_dedicatedDao.remove(resourceId)) {
                        throw new CloudRuntimeException("Failed to delete dedicated Zone Resource " + resourceId);
                    }
                    // find the group associated and check if there are any more
                    // resources under that group
                    final List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
                    if (resourcesInGroup.isEmpty()) {
                        // delete the group
                        _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null, null);
                    }
                }
            }
            if (!_zoneDao.update(zoneId, zone)) {
                throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support.");
            }
        }
    });
    return zone;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) AllocationState(com.cloud.model.enumeration.AllocationState) PhysicalNetwork(com.cloud.network.PhysicalNetwork) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) Map(java.util.Map) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 3 with AllocationState

use of com.cloud.model.enumeration.AllocationState in project cosmic by MissionCriticalCloud.

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 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, isLocalStorageEnabled, ip6Dns1, ip6Dns2);
    if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
        final AllocationState allocationState = 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(AllocationState.Disabled);
    }
    return Transaction.execute(new TransactionCallback<DataCenterVO>() {

        @Override
        public DataCenterVO doInTransaction(final TransactionStatus status) {
            final DataCenterVO zone = _zoneDao.persist(zoneFinal);
            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) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) AllocationState(com.cloud.model.enumeration.AllocationState) TransactionStatus(com.cloud.utils.db.TransactionStatus) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) AffinityGroup(com.cloud.affinity.AffinityGroup) DB(com.cloud.utils.db.DB)

Example 4 with AllocationState

use of com.cloud.model.enumeration.AllocationState in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method createPod.

@Override
@DB
public HostPodVO createPod(final long userId, final String podName, final long zoneId, final String gateway, final String cidr, final String startIp, String endIp, final String allocationStateStr, final boolean skipGatewayOverlapCheck) {
    // Check if the zone is valid
    if (!validZone(zoneId)) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    // Check if zone is disabled
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    final Account account = CallContext.current().getCallingAccount();
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
    }
    final String cidrAddress = getCidrAddress(cidr);
    final int cidrSize = getCidrSize(cidr);
    // end ip of the pod's cidr
    if (startIp != null) {
        if (endIp == null) {
            endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
        }
    }
    // Validate new pod settings
    checkPodAttributes(-1, podName, zoneId, gateway, cidr, startIp, endIp, allocationStateStr, true, skipGatewayOverlapCheck);
    // Create the new pod in the database
    final String ipRange;
    if (startIp != null) {
        ipRange = startIp + "-" + endIp;
    } else {
        throw new InvalidParameterValueException("Start ip is required parameter");
    }
    final HostPodVO podFinal = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange);
    final AllocationState allocationState;
    if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
        allocationState = AllocationState.valueOf(allocationStateStr);
        podFinal.setAllocationState(allocationState);
    }
    final String endIpFinal = endIp;
    return Transaction.execute(new TransactionCallback<HostPodVO>() {

        @Override
        public HostPodVO doInTransaction(final TransactionStatus status) {
            final HostPodVO pod = _podDao.persist(podFinal);
            if (startIp != null) {
                _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIpFinal);
            }
            final String[] linkLocalIpRanges = getLinkLocalIPRange();
            if (linkLocalIpRanges != null) {
                _zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
            }
            return pod;
        }
    });
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) AllocationState(com.cloud.model.enumeration.AllocationState) TransactionStatus(com.cloud.utils.db.TransactionStatus) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) HostPodVO(com.cloud.dc.HostPodVO) DB(com.cloud.utils.db.DB)

Example 5 with AllocationState

use of com.cloud.model.enumeration.AllocationState in project cosmic by MissionCriticalCloud.

the class ResourceManagerImpl method discoverCluster.

@DB
@Override
public List<? extends Cluster> discoverCluster(final AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException {
    final ResourceChecker resourceChecker = ResourceChecker.builder().dataCenterDao(_dcDao).accountManager(_accountMgr).hostPodDao(_podDao).build();
    final long dcId = cmd.getZoneId();
    final long podId = cmd.getPodId();
    final String clusterName = cmd.getClusterName();
    String url = cmd.getUrl();
    final String username = cmd.getUsername();
    final String password = cmd.getPassword();
    if (url != null) {
        url = URLDecoder.decode(url);
    }
    final URI uri;
    final DataCenterVO zone = resourceChecker.checkIfDataCenterExists(dcId);
    final Account account = CallContext.current().getCallingAccount();
    resourceChecker.checkIfDataCenterIsUsable(zone, account);
    final HostPodVO pod = _podDao.findById(podId);
    if (pod == null) {
        throw new InvalidParameterValueException("Can't find pod with specified podId " + podId);
    }
    // Check if the pod exists in the system
    if (_podDao.findById(podId) == null) {
        throw new InvalidParameterValueException("Can't find pod by id " + podId);
    }
    // check if pod belongs to the zone
    if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified id doesn't belong to the zone " + dcId);
        ex.addProxyObject(pod.getUuid(), "podId");
        ex.addProxyObject(zone.getUuid(), "dcId");
        throw ex;
    }
    // Verify cluster information and create a new cluster if needed
    if (clusterName == null || clusterName.isEmpty()) {
        throw new InvalidParameterValueException("Please specify cluster name");
    }
    if (cmd.getHypervisor() == null || cmd.getHypervisor().isEmpty()) {
        throw new InvalidParameterValueException("Please specify a hypervisor");
    }
    final Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(cmd.getHypervisor());
    if (hypervisorType == null) {
        s_logger.error("Unable to resolve " + cmd.getHypervisor() + " to a valid supported hypervisor type");
        throw new InvalidParameterValueException("Unable to resolve " + cmd.getHypervisor() + " to a supported ");
    }
    Cluster.ClusterType clusterType = null;
    if (cmd.getClusterType() != null && !cmd.getClusterType().isEmpty()) {
        clusterType = Cluster.ClusterType.valueOf(cmd.getClusterType());
    }
    if (clusterType == null) {
        clusterType = Cluster.ClusterType.CloudManaged;
    }
    AllocationState allocationState = null;
    if (cmd.getAllocationState() != null && !cmd.getAllocationState().isEmpty()) {
        try {
            allocationState = AllocationState.valueOf(cmd.getAllocationState());
        } catch (final IllegalArgumentException ex) {
            throw new InvalidParameterValueException("Unable to resolve Allocation State '" + cmd.getAllocationState() + "' to a supported state");
        }
    }
    if (allocationState == null) {
        allocationState = AllocationState.Enabled;
    }
    final Discoverer discoverer = getMatchingDiscover(hypervisorType);
    if (discoverer == null) {
        throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor());
    }
    final List<ClusterVO> result = new ArrayList<>();
    ClusterVO cluster = new ClusterVO(dcId, podId, clusterName);
    cluster.setHypervisorType(hypervisorType.toString());
    cluster.setClusterType(clusterType);
    cluster.setAllocationState(allocationState);
    try {
        cluster = _clusterDao.persist(cluster);
    } catch (final Exception e) {
        // no longer tolerate exception during the cluster creation phase
        final CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod and data center with specified ids", e);
        // Get the pod VO object's table name.
        ex.addProxyObject(pod.getUuid(), "podId");
        ex.addProxyObject(zone.getUuid(), "dcId");
        throw ex;
    }
    result.add(cluster);
    if (clusterType == Cluster.ClusterType.CloudManaged) {
        final Map<String, String> details = new HashMap<>();
        details.put("cpuOvercommitRatio", CapacityManager.CpuOverprovisioningFactor.value().toString());
        details.put("memoryOvercommitRatio", CapacityManager.MemOverprovisioningFactor.value().toString());
        _clusterDetailsDao.persist(cluster.getId(), details);
        return result;
    }
    // save cluster details for later cluster/host cross-checking
    final Map<String, String> details = new HashMap<>();
    details.put("url", url);
    details.put("username", username);
    details.put("password", password);
    details.put("cpuOvercommitRatio", CapacityManager.CpuOverprovisioningFactor.value().toString());
    details.put("memoryOvercommitRatio", CapacityManager.MemOverprovisioningFactor.value().toString());
    _clusterDetailsDao.persist(cluster.getId(), details);
    boolean success = false;
    try {
        try {
            uri = new URI(UriUtils.encodeURIComponent(url));
            if (uri.getScheme() == null) {
                throw new InvalidParameterValueException("uri.scheme is null " + url + ", add http:// as a prefix");
            } else if (uri.getScheme().equalsIgnoreCase("http")) {
                if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) {
                    throw new InvalidParameterValueException("Your host and/or path is wrong.  Make sure it's of the format http://hostname/path");
                }
            }
        } catch (final URISyntaxException e) {
            throw new InvalidParameterValueException(url + " is not a valid uri");
        }
        final List<HostVO> hosts = new ArrayList<>();
        final Map<? extends ServerResource, Map<String, String>> resources;
        resources = discoverer.find(dcId, podId, cluster.getId(), uri, username, password, null);
        if (resources != null) {
            for (final Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
                final ServerResource resource = entry.getKey();
                final HostVO host = (HostVO) createHostAndAgent(resource, entry.getValue(), true, null, false);
                if (host != null) {
                    hosts.add(host);
                }
                discoverer.postDiscovery(hosts, _nodeId);
            }
            s_logger.info("External cluster has been successfully discovered by " + discoverer.getName());
            success = true;
            return result;
        }
        s_logger.warn("Unable to find the server resources at " + url);
        throw new DiscoveryException("Unable to add the external cluster");
    } finally {
        if (!success) {
            _clusterDetailsDao.deleteDetails(cluster.getId());
            _clusterDao.remove(cluster.getId());
        }
    }
}
Also used : Account(com.cloud.user.Account) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HostPodVO(com.cloud.dc.HostPodVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiscoveryException(com.cloud.exception.DiscoveryException) DataCenterVO(com.cloud.dc.DataCenterVO) ClusterVO(com.cloud.dc.ClusterVO) Hypervisor(com.cloud.hypervisor.Hypervisor) PodCluster(com.cloud.dc.PodCluster) Cluster(com.cloud.org.Cluster) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) URISyntaxException(java.net.URISyntaxException) DiscoveryException(com.cloud.exception.DiscoveryException) SshException(com.cloud.utils.ssh.SshException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) AllocationState(com.cloud.model.enumeration.AllocationState) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Map(java.util.Map) HashMap(java.util.HashMap) DB(com.cloud.utils.db.DB)

Aggregations

AllocationState (com.cloud.model.enumeration.AllocationState)7 DB (com.cloud.utils.db.DB)6 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)6 DataCenterVO (com.cloud.dc.DataCenterVO)5 TransactionStatus (com.cloud.utils.db.TransactionStatus)4 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 ClusterVO (com.cloud.dc.ClusterVO)3 HostPodVO (com.cloud.dc.HostPodVO)3 ConfigurationException (javax.naming.ConfigurationException)3 DedicatedResourceVO (com.cloud.dc.DedicatedResourceVO)2 PodCluster (com.cloud.dc.PodCluster)2 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)2 DiscoveryException (com.cloud.exception.DiscoveryException)2 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)2 ResourceInUseException (com.cloud.exception.ResourceInUseException)2 HostVO (com.cloud.host.HostVO)2 Hypervisor (com.cloud.hypervisor.Hypervisor)2 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)2 Cluster (com.cloud.org.Cluster)2 StoragePoolHostVO (com.cloud.storage.StoragePoolHostVO)2