Search in sources :

Example 11 with Hypervisor

use of com.cloud.hypervisor.Hypervisor in project cloudstack by apache.

the class ScaleIOPrimaryDataStoreLifeCycle method initialize.

@SuppressWarnings("unchecked")
@Override
public DataStore initialize(Map<String, Object> dsInfos) {
    String url = (String) dsInfos.get("url");
    Long zoneId = (Long) dsInfos.get("zoneId");
    Long podId = (Long) dsInfos.get("podId");
    Long clusterId = (Long) dsInfos.get("clusterId");
    String dataStoreName = (String) dsInfos.get("name");
    String providerName = (String) dsInfos.get("providerName");
    Long capacityBytes = (Long) dsInfos.get("capacityBytes");
    Long capacityIops = (Long) dsInfos.get("capacityIops");
    String tags = (String) dsInfos.get("tags");
    Map<String, String> details = (Map<String, String>) dsInfos.get("details");
    if (zoneId == null) {
        throw new CloudRuntimeException("Zone Id must be specified.");
    }
    PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters();
    if (clusterId != null) {
        // Primary datastore is cluster-wide, check and set the podId and clusterId parameters
        if (podId == null) {
            throw new CloudRuntimeException("Pod Id must also be specified when the Cluster Id is specified for Cluster-wide primary storage.");
        }
        Hypervisor.HypervisorType hypervisorType = getHypervisorTypeForCluster(clusterId);
        if (!isSupportedHypervisorType(hypervisorType)) {
            throw new CloudRuntimeException("Unsupported hypervisor type: " + hypervisorType.toString());
        }
        parameters.setPodId(podId);
        parameters.setClusterId(clusterId);
    } else if (podId != null) {
        throw new CloudRuntimeException("Cluster Id must also be specified when the Pod Id is specified for Cluster-wide primary storage.");
    }
    URI uri = null;
    try {
        uri = new URI(UriUtils.encodeURIComponent(url));
        if (uri.getScheme() == null || !uri.getScheme().equalsIgnoreCase("powerflex")) {
            throw new InvalidParameterValueException("scheme is invalid for url: " + url + ", should be powerflex://username:password@gatewayhost/pool");
        }
    } catch (Exception ignored) {
        throw new InvalidParameterValueException(url + " is not a valid uri");
    }
    String storagePoolName = null;
    try {
        storagePoolName = URLDecoder.decode(uri.getPath(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("[ignored] we are on a platform not supporting \"UTF-8\"!?!", e);
    }
    if (storagePoolName == null) {
        // if decoding fails, use getPath() anyway
        storagePoolName = uri.getPath();
    }
    storagePoolName = storagePoolName.replaceFirst("/", "");
    final String storageHost = uri.getHost();
    final int port = uri.getPort();
    String gatewayApiURL = null;
    if (port == -1) {
        gatewayApiURL = String.format("https://%s/api", storageHost);
    } else {
        gatewayApiURL = String.format("https://%s:%d/api", storageHost, port);
    }
    final String userInfo = uri.getUserInfo();
    final String gatewayUsername = userInfo.split(":")[0];
    final String gatewayPassword = userInfo.split(":")[1];
    List<StoragePoolVO> storagePoolVO = primaryDataStoreDao.findPoolsByProvider(ScaleIOUtil.PROVIDER_NAME);
    if (CollectionUtils.isNotEmpty(storagePoolVO)) {
        for (StoragePoolVO poolVO : storagePoolVO) {
            Map<String, String> poolDetails = primaryDataStoreDao.getDetails(poolVO.getId());
            String poolUrl = poolDetails.get(ScaleIOGatewayClient.GATEWAY_API_ENDPOINT);
            String poolName = poolDetails.get(ScaleIOGatewayClient.STORAGE_POOL_NAME);
            if (gatewayApiURL.equals(poolUrl) && storagePoolName.equals(poolName)) {
                throw new IllegalArgumentException("PowerFlex storage pool: " + storagePoolName + " already exists, please specify other storage pool.");
            }
        }
    }
    final org.apache.cloudstack.storage.datastore.api.StoragePool scaleIOPool = this.findStoragePool(gatewayApiURL, gatewayUsername, gatewayPassword, storagePoolName);
    parameters.setZoneId(zoneId);
    parameters.setName(dataStoreName);
    parameters.setProviderName(providerName);
    parameters.setManaged(true);
    parameters.setHost(storageHost);
    parameters.setPath(scaleIOPool.getId());
    parameters.setUserInfo(userInfo);
    parameters.setType(Storage.StoragePoolType.PowerFlex);
    parameters.setHypervisorType(Hypervisor.HypervisorType.KVM);
    parameters.setUuid(UUID.randomUUID().toString());
    parameters.setTags(tags);
    StoragePoolStatistics poolStatistics = scaleIOPool.getStatistics();
    if (poolStatistics != null) {
        if (capacityBytes == null) {
            parameters.setCapacityBytes(poolStatistics.getNetMaxCapacityInBytes());
        }
        parameters.setUsedBytes(poolStatistics.getNetUsedCapacityInBytes());
    }
    if (capacityBytes != null) {
        parameters.setCapacityBytes(capacityBytes);
    }
    if (capacityIops != null) {
        parameters.setCapacityIops(capacityIops);
    }
    details.put(ScaleIOGatewayClient.GATEWAY_API_ENDPOINT, gatewayApiURL);
    details.put(ScaleIOGatewayClient.GATEWAY_API_USERNAME, DBEncryptionUtil.encrypt(gatewayUsername));
    details.put(ScaleIOGatewayClient.GATEWAY_API_PASSWORD, DBEncryptionUtil.encrypt(gatewayPassword));
    details.put(ScaleIOGatewayClient.STORAGE_POOL_NAME, storagePoolName);
    details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, scaleIOPool.getSystemId());
    parameters.setDetails(details);
    return dataStoreHelper.createPrimaryDataStore(parameters);
}
Also used : Hypervisor(com.cloud.hypervisor.Hypervisor) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StoragePoolStatistics(org.apache.cloudstack.storage.datastore.api.StoragePoolStatistics) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PrimaryDataStoreParameters(org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMTemplateStoragePoolVO(com.cloud.storage.VMTemplateStoragePoolVO) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) Map(java.util.Map)

Example 12 with Hypervisor

use of com.cloud.hypervisor.Hypervisor in project cloudstack by apache.

the class DeployAsIsHelperImpl method retrieveTemplateGuestOsIdFromGuestOsInfo.

/**
 * Returns the mapped guest OS from the OVF file of the template to the CloudStack database OS ID
 */
private Long retrieveTemplateGuestOsIdFromGuestOsInfo(long templateId, String guestOsType, String guestOsDescription, String minimumHardwareVersion) {
    VMTemplateVO template = templateDao.findById(templateId);
    Hypervisor.HypervisorType hypervisor = template.getHypervisorType();
    if (hypervisor != Hypervisor.HypervisorType.VMware) {
        return null;
    }
    String minimumHypervisorVersion = getMinimumSupportedHypervisorVersionForHardwareVersion(minimumHardwareVersion);
    LOGGER.info("Minimum hardware version " + minimumHardwareVersion + " matched to hypervisor version " + minimumHypervisorVersion + ". " + "Checking guest OS supporting this version");
    List<GuestOSHypervisorVO> guestOsMappings = guestOSHypervisorDao.listByOsNameAndHypervisorMinimumVersion(guestOsType, hypervisor.toString(), minimumHypervisorVersion);
    if (CollectionUtils.isNotEmpty(guestOsMappings)) {
        Long guestOsId = null;
        if (guestOsMappings.size() == 1) {
            GuestOSHypervisorVO mapping = guestOsMappings.get(0);
            guestOsId = mapping.getGuestOsId();
        } else {
            if (StringUtils.isNotEmpty(guestOsDescription)) {
                for (GuestOSHypervisorVO guestOSHypervisorVO : guestOsMappings) {
                    GuestOSVO guestOSVO = guestOSDao.findByIdIncludingRemoved(guestOSHypervisorVO.getGuestOsId());
                    if (guestOSVO != null && guestOsDescription.equalsIgnoreCase(guestOSVO.getDisplayName())) {
                        guestOsId = guestOSHypervisorVO.getGuestOsId();
                        break;
                    }
                }
            }
            if (null == guestOsId) {
                GuestOSHypervisorVO mapping = guestOsMappings.get(guestOsMappings.size() - 1);
                guestOsId = mapping.getGuestOsId();
            }
        }
        return guestOsId;
    } else {
        throw new CloudRuntimeException("Did not find a guest OS with type " + guestOsType);
    }
}
Also used : GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) Hypervisor(com.cloud.hypervisor.Hypervisor) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO)

Example 13 with Hypervisor

use of com.cloud.hypervisor.Hypervisor in project cloudstack by apache.

the class Upgrade41500to41510 method updateSystemVmTemplates.

@Override
@SuppressWarnings("serial")
public void updateSystemVmTemplates(final Connection conn) {
    LOG.debug("Updating System Vm template IDs");
    final Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
    try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
        ResultSet rs = pstmt.executeQuery()) {
        while (rs.next()) {
            switch(Hypervisor.HypervisorType.getType(rs.getString(1))) {
                case XenServer:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
                    break;
                case KVM:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
                    break;
                case VMware:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
                    break;
                case Hyperv:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
                    break;
                case LXC:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
                    break;
                case Ovm3:
                    hypervisorsListInUse.add(Hypervisor.HypervisorType.Ovm3);
                    break;
                default:
                    break;
            }
        }
    } catch (final SQLException e) {
        LOG.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage());
        throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e);
    }
    final Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>() {

        {
            put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.15.1");
            put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.15.1");
            put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.15.1");
            put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.15.1");
            put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.15.1");
            put(Hypervisor.HypervisorType.Ovm3, "systemvm-ovm3-4.15.1");
        }
    };
    final Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>() {

        {
            put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
            put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
            put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver");
            put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
            put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
            put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3");
        }
    };
    final Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>() {

        {
            put(Hypervisor.HypervisorType.KVM, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2");
            put(Hypervisor.HypervisorType.VMware, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-vmware.ova");
            put(Hypervisor.HypervisorType.XenServer, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-xen.vhd.bz2");
            put(Hypervisor.HypervisorType.Hyperv, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-hyperv.vhd.zip");
            put(Hypervisor.HypervisorType.LXC, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2");
            put(Hypervisor.HypervisorType.Ovm3, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-ovm.raw.bz2");
        }
    };
    final Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>() {

        {
            put(Hypervisor.HypervisorType.KVM, "0e9f9a7d0957c3e0a2088e41b2da2cec");
            put(Hypervisor.HypervisorType.XenServer, "86373992740b1eca8aff8b08ebf3aea5");
            put(Hypervisor.HypervisorType.VMware, "4006982765846d373eb3719b2fe4d720");
            put(Hypervisor.HypervisorType.Hyperv, "0b9514e4b6cba1f636fea2125f0f7a5f");
            put(Hypervisor.HypervisorType.LXC, "0e9f9a7d0957c3e0a2088e41b2da2cec");
            put(Hypervisor.HypervisorType.Ovm3, "ae3977e696b3e6c81bdcbb792d514d29");
        }
    };
    for (final Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
        LOG.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
        try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null and account_id in (select id from account where type = 1 and removed is NULL) order by id desc limit 1")) {
            // Get systemvm template id for corresponding hypervisor
            long templateId = -1;
            pstmt.setString(1, hypervisorAndTemplateName.getValue());
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    templateId = rs.getLong(1);
                }
            } catch (final SQLException e) {
                LOG.error("updateSystemVmTemplates: Exception caught while getting ids of templates: " + e.getMessage());
                throw new CloudRuntimeException("updateSystemVmTemplates: Exception caught while getting ids of templates", e);
            }
            // change template type to SYSTEM
            if (templateId != -1) {
                try (PreparedStatement templ_type_pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?")) {
                    templ_type_pstmt.setLong(1, templateId);
                    templ_type_pstmt.executeUpdate();
                } catch (final SQLException e) {
                    LOG.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': " + e.getMessage());
                    throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e);
                }
                // update template ID of system Vms
                try (PreparedStatement update_templ_id_pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ? and removed is NULL")) {
                    update_templ_id_pstmt.setLong(1, templateId);
                    update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
                    update_templ_id_pstmt.executeUpdate();
                } catch (final Exception e) {
                    LOG.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId + ": " + e.getMessage());
                    throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId, e);
                }
                // router.template.* for the corresponding hypervisor
                try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?")) {
                    update_pstmt.setString(1, hypervisorAndTemplateName.getValue());
                    update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
                    update_pstmt.executeUpdate();
                } catch (final SQLException e) {
                    LOG.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue() + ": " + e.getMessage());
                    throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e);
                }
                // minreq.sysvmtemplate.version for the ACS version
                try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?")) {
                    update_pstmt.setString(1, "4.15.1");
                    update_pstmt.setString(2, "minreq.sysvmtemplate.version");
                    update_pstmt.executeUpdate();
                } catch (final SQLException e) {
                    LOG.error("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.15.1: " + e.getMessage());
                    throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.15.1", e);
                }
            } else {
                if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) {
                    throw new CloudRuntimeException(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
                } else {
                    LOG.warn(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
                    // hypervisor
                    try (PreparedStatement update_templ_url_pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1")) {
                        update_templ_url_pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
                        update_templ_url_pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
                        update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
                        update_templ_url_pstmt.executeUpdate();
                    } catch (final SQLException e) {
                        LOG.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString() + ": " + e.getMessage());
                        throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString(), e);
                    }
                }
            }
        } catch (final SQLException e) {
            LOG.error("updateSystemVmTemplates:Exception while getting ids of templates: " + e.getMessage());
            throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
        }
    }
    LOG.debug("Updating System Vm Template IDs Complete");
}
Also used : Hypervisor(com.cloud.hypervisor.Hypervisor) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) PreparedStatement(java.sql.PreparedStatement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResultSet(java.sql.ResultSet) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 14 with Hypervisor

use of com.cloud.hypervisor.Hypervisor in project cloudstack by apache.

the class PremiumSecondaryStorageResource method executeRequest.

@Override
public Answer executeRequest(Command cmd) {
    String hypervisor = cmd.getContextParam("hypervisor");
    if (hypervisor != null) {
        Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(hypervisor);
        if (hypervisorType == null) {
            s_logger.error("Unsupported hypervisor type in command context, hypervisor: " + hypervisor);
            return defaultAction(cmd);
        }
        SecondaryStorageResourceHandler handler = getHandler(hypervisorType);
        if (handler == null) {
            s_logger.error("No handler can be found for hypervisor type in command context, hypervisor: " + hypervisor);
            return defaultAction(cmd);
        }
        return handler.executeRequest(cmd);
    }
    return defaultAction(cmd);
}
Also used : Hypervisor(com.cloud.hypervisor.Hypervisor) SecondaryStorageResourceHandler(org.apache.cloudstack.storage.resource.SecondaryStorageResourceHandler)

Example 15 with Hypervisor

use of com.cloud.hypervisor.Hypervisor in project cloudstack by apache.

the class ResourceManagerImpl method discoverCluster.

@DB
@Override
public List<? extends Cluster> discoverCluster(final AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException {
    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);
    }
    URI uri = null;
    // Check if the zone exists in the system
    final DataCenterVO zone = _dcDao.findById(dcId);
    if (zone == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Can't find zone by the id specified");
        ex.addProxyObject(String.valueOf(dcId), "dcId");
        throw ex;
    }
    final Account account = CallContext.current().getCallingAccount();
    if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) {
        final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled");
        ex.addProxyObject(zone.getUuid(), "dcId");
        throw ex;
    }
    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 ");
    }
    if (zone.isSecurityGroupEnabled() && zone.getNetworkType().equals(NetworkType.Advanced)) {
        if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.XenServer && hypervisorType != HypervisorType.LXC && hypervisorType != HypervisorType.Simulator) {
            throw new InvalidParameterValueException("Don't support hypervisor type " + hypervisorType + " in advanced security enabled zone");
        }
    }
    Cluster.ClusterType clusterType = null;
    if (cmd.getClusterType() != null && !cmd.getClusterType().isEmpty()) {
        clusterType = Cluster.ClusterType.valueOf(cmd.getClusterType());
    }
    if (clusterType == null) {
        clusterType = Cluster.ClusterType.CloudManaged;
    }
    Grouping.AllocationState allocationState = null;
    if (cmd.getAllocationState() != null && !cmd.getAllocationState().isEmpty()) {
        try {
            allocationState = Grouping.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 = Grouping.AllocationState.Enabled;
    }
    final Discoverer discoverer = getMatchingDiscover(hypervisorType);
    if (discoverer == null) {
        throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor());
    }
    if (hypervisorType == HypervisorType.VMware) {
        final Map<String, String> allParams = cmd.getFullUrlParams();
        discoverer.putParam(allParams);
    }
    final List<ClusterVO> result = new ArrayList<ClusterVO>();
    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<String, String>();
        // should do this nicer perhaps ?
        if (hypervisorType == HypervisorType.Ovm3) {
            final Map<String, String> allParams = cmd.getFullUrlParams();
            details.put("ovm3vip", allParams.get("ovm3vip"));
            details.put("ovm3pool", allParams.get("ovm3pool"));
            details.put("ovm3cluster", allParams.get("ovm3cluster"));
        }
        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<String, String>();
    details.put("url", url);
    details.put("username", StringUtils.defaultString(username));
    details.put("password", StringUtils.defaultString(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<HostVO>();
        Map<? extends ServerResource, Map<String, String>> resources = null;
        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.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) Grouping(com.cloud.org.Grouping) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) 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.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Map(java.util.Map) HashMap(java.util.HashMap) DB(com.cloud.utils.db.DB)

Aggregations

Hypervisor (com.cloud.hypervisor.Hypervisor)19 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)18 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)7 HostVO (com.cloud.host.HostVO)7 DB (com.cloud.utils.db.DB)7 URISyntaxException (java.net.URISyntaxException)7 ArrayList (java.util.ArrayList)7 ClusterVO (com.cloud.dc.ClusterVO)6 DiscoveryException (com.cloud.exception.DiscoveryException)6 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)6 ResourceInUseException (com.cloud.exception.ResourceInUseException)6 Cluster (com.cloud.org.Cluster)6 Grouping (com.cloud.org.Grouping)6 VMTemplateVO (com.cloud.storage.VMTemplateVO)6 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)6 HashSet (java.util.HashSet)6