Search in sources :

Example 1 with DiscoveredWithErrorException

use of com.cloud.exception.DiscoveredWithErrorException in project cloudstack by apache.

the class VmwareServerDiscoverer method validateCluster.

private String validateCluster(URI url, VmwareDatacenterVO vmwareDc) throws DiscoveryException {
    String msg;
    String vmwareDcNameFromDb;
    String vmwareDcNameFromApi;
    String vCenterHost;
    String updatedInventoryPath;
    String clusterName = null;
    String inventoryPath;
    vmwareDcNameFromApi = vmwareDcNameFromDb = vmwareDc.getVmwareDatacenterName();
    vCenterHost = vmwareDc.getVcenterHost();
    try {
        inventoryPath = updatedInventoryPath = URLDecoder.decode(url.getPath(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new DiscoveredWithErrorException("Unable to decode URL path, URL path : " + url.getPath(), e);
    }
    assert (inventoryPath != null);
    String[] pathTokens = inventoryPath.split("/");
    if (pathTokens.length == 2) {
        // DC name is not present in url.
        // Using DC name read from database.
        clusterName = pathTokens[1];
        updatedInventoryPath = "/" + vmwareDcNameFromDb + "/" + clusterName;
    } else if (pathTokens.length == 3) {
        vmwareDcNameFromApi = pathTokens[1];
        clusterName = pathTokens[2];
    }
    if (!vCenterHost.equalsIgnoreCase(url.getHost())) {
        msg = "This cluster " + clusterName + " belongs to vCenter " + url.getHost() + ". But this zone is associated with VMware DC from vCenter " + vCenterHost + ". Make sure the cluster being added belongs to vCenter " + vCenterHost + " and VMware DC " + vmwareDcNameFromDb;
        s_logger.error(msg);
        throw new DiscoveryException(msg);
    } else if (!vmwareDcNameFromDb.equalsIgnoreCase(vmwareDcNameFromApi)) {
        msg = "This cluster " + clusterName + " belongs to VMware DC " + vmwareDcNameFromApi + " .But this zone is associated with VMware DC " + vmwareDcNameFromDb + ". Make sure the cluster being added belongs to VMware DC " + vmwareDcNameFromDb + " in vCenter " + vCenterHost;
        s_logger.error(msg);
        throw new DiscoveryException(msg);
    }
    return updatedInventoryPath;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) DiscoveryException(com.cloud.exception.DiscoveryException)

Example 2 with DiscoveredWithErrorException

use of com.cloud.exception.DiscoveredWithErrorException in project cloudstack by apache.

the class XcpServerDiscoverer method find.

@Override
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List<String> hostTags) throws DiscoveryException {
    Map<CitrixResourceBase, Map<String, String>> resources = new HashMap<CitrixResourceBase, Map<String, String>>();
    Connection conn = null;
    if (!url.getScheme().equals("http")) {
        String msg = "urlString is not http so we're not taking care of the discovery for this: " + url;
        s_logger.debug(msg);
        return null;
    }
    if (clusterId == null) {
        String msg = "must specify cluster Id when add host";
        s_logger.debug(msg);
        throw new RuntimeException(msg);
    }
    if (podId == null) {
        String msg = "must specify pod Id when add host";
        s_logger.debug(msg);
        throw new RuntimeException(msg);
    }
    ClusterVO cluster = _clusterDao.findById(clusterId);
    if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer) {
        if (s_logger.isInfoEnabled())
            s_logger.info("invalid cluster id or cluster is not for XenServer hypervisors");
        return null;
    }
    try {
        String hostname = url.getHost();
        InetAddress ia = InetAddress.getByName(hostname);
        String hostIp = ia.getHostAddress();
        Queue<String> pass = new LinkedList<String>();
        pass.add(password);
        conn = _connPool.getConnect(hostIp, username, pass);
        if (conn == null) {
            String msg = "Unable to get a connection to " + url;
            s_logger.debug(msg);
            throw new DiscoveryException(msg);
        }
        Set<Pool> pools = Pool.getAll(conn);
        Pool pool = pools.iterator().next();
        Pool.Record pr = pool.getRecord(conn);
        String poolUuid = pr.uuid;
        Map<Host, Host.Record> hosts = Host.getAllRecords(conn);
        String latestHotFix = "";
        if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1004)) {
            latestHotFix = XenserverConfigs.XSHotFix62ESP1004;
        } else if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1)) {
            latestHotFix = XenserverConfigs.XSHotFix62ESP1;
        }
        /*set cluster hypervisor type to xenserver*/
        ClusterVO clu = _clusterDao.findById(clusterId);
        if (clu.getGuid() == null) {
            setClusterGuid(clu, poolUuid);
        } else {
            List<HostVO> clusterHosts = _resourceMgr.listAllHostsInCluster(clusterId);
            if (clusterHosts != null && clusterHosts.size() > 0) {
                if (!clu.getGuid().equals(poolUuid)) {
                    String msg = "Please join the host " + hostIp + " to XS pool  " + clu.getGuid() + " through XC/XS before adding it through CS UI";
                    s_logger.warn(msg);
                    throw new DiscoveryException(msg);
                }
            } else {
                setClusterGuid(clu, poolUuid);
            }
        }
        // can not use this conn after this point, because this host may join a pool, this conn is retired
        if (conn != null) {
            try {
                Session.logout(conn);
            } catch (Exception e) {
                s_logger.debug("Caught exception during logout", e);
            }
            conn.dispose();
            conn = null;
        }
        poolUuid = clu.getGuid();
        _clusterDao.update(clusterId, clu);
        if (_checkHvm) {
            for (Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
                Host.Record record = entry.getValue();
                boolean support_hvm = false;
                for (String capability : record.capabilities) {
                    if (capability.contains("hvm")) {
                        support_hvm = true;
                        break;
                    }
                }
                if (!support_hvm) {
                    String msg = "Unable to add host " + record.address + " because it doesn't support hvm";
                    _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg);
                    s_logger.debug(msg);
                    throw new RuntimeException(msg);
                }
            }
        }
        for (Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
            Host.Record record = entry.getValue();
            String hostAddr = record.address;
            String prodVersion = CitrixHelper.getProductVersion(record);
            String xenVersion = record.softwareVersion.get("xen");
            String hostOS = record.softwareVersion.get("product_brand");
            if (hostOS == null) {
                hostOS = record.softwareVersion.get("platform_name");
            }
            String hostOSVer = prodVersion;
            String hostKernelVer = record.softwareVersion.get("linux");
            if (_resourceMgr.findHostByGuid(record.uuid) != null) {
                s_logger.debug("Skipping " + record.address + " because " + record.uuid + " is already in the database.");
                continue;
            }
            CitrixResourceBase resource = createServerResource(dcId, podId, record, latestHotFix);
            s_logger.info("Found host " + record.hostname + " ip=" + record.address + " product version=" + prodVersion);
            Map<String, String> details = new HashMap<String, String>();
            Map<String, Object> params = new HashMap<String, Object>();
            details.put("url", hostAddr);
            details.put("username", username);
            params.put("username", username);
            details.put("password", password);
            params.put("password", password);
            params.put("zone", Long.toString(dcId));
            params.put("guid", record.uuid);
            params.put("pod", podId.toString());
            params.put("cluster", clusterId.toString());
            params.put("pool", poolUuid);
            params.put("ipaddress", record.address);
            details.put(HostInfo.HOST_OS, hostOS);
            details.put(HostInfo.HOST_OS_VERSION, hostOSVer);
            details.put(HostInfo.HOST_OS_KERNEL_VERSION, hostKernelVer);
            details.put(HostInfo.HYPERVISOR_VERSION, xenVersion);
            String privateNetworkLabel = _networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer);
            String storageNetworkLabel = _networkMgr.getDefaultStorageTrafficLabel(dcId, HypervisorType.XenServer);
            if (!params.containsKey("private.network.device") && privateNetworkLabel != null) {
                params.put("private.network.device", privateNetworkLabel);
                details.put("private.network.device", privateNetworkLabel);
            }
            if (!params.containsKey("storage.network.device1") && storageNetworkLabel != null) {
                params.put("storage.network.device1", storageNetworkLabel);
                details.put("storage.network.device1", storageNetworkLabel);
            }
            DataCenterVO zone = _dcDao.findById(dcId);
            boolean securityGroupEnabled = zone.isSecurityGroupEnabled();
            params.put("securitygroupenabled", Boolean.toString(securityGroupEnabled));
            params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
            params.put("wait", Integer.toString(_wait));
            details.put("wait", Integer.toString(_wait));
            params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
            params.put(Config.XenServerMaxNics.toString().toLowerCase(), _configDao.getValue(Config.XenServerMaxNics.toString()));
            params.put(Config.XenServerHeartBeatTimeout.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatTimeout.toString()));
            params.put(Config.XenServerHeartBeatInterval.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatInterval.toString()));
            params.put(Config.InstanceName.toString().toLowerCase(), _instance);
            details.put(Config.InstanceName.toString().toLowerCase(), _instance);
            try {
                resource.configure("XenServer", params);
            } catch (ConfigurationException e) {
                _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + record.address, "Error is " + e.getMessage());
                s_logger.warn("Unable to instantiate " + record.address, e);
                continue;
            }
            resource.start();
            resources.put(resource, details);
        }
    } catch (SessionAuthenticationFailed e) {
        throw new DiscoveredWithErrorException("Authentication error");
    } catch (XenAPIException e) {
        s_logger.warn("XenAPI exception", e);
        return null;
    } catch (XmlRpcException e) {
        s_logger.warn("Xml Rpc Exception", e);
        return null;
    } catch (UnknownHostException e) {
        s_logger.warn("Unable to resolve the host name", e);
        return null;
    } catch (Exception e) {
        s_logger.debug("other exceptions: " + e.toString(), e);
        return null;
    }
    return resources;
}
Also used : HashMap(java.util.HashMap) XenAPIException(com.xensource.xenapi.Types.XenAPIException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConfigurationException(javax.naming.ConfigurationException) Pool(com.xensource.xenapi.Pool) XenServerConnectionPool(com.cloud.hypervisor.xenserver.resource.XenServerConnectionPool) DiscoveryException(com.cloud.exception.DiscoveryException) DataCenterVO(com.cloud.dc.DataCenterVO) ClusterVO(com.cloud.dc.ClusterVO) UnknownHostException(java.net.UnknownHostException) Connection(com.xensource.xenapi.Connection) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) Host(com.xensource.xenapi.Host) LinkedList(java.util.LinkedList) HostVO(com.cloud.host.HostVO) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) DiscoveryException(com.cloud.exception.DiscoveryException) ConnectionException(com.cloud.exception.ConnectionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) EntityExistsException(javax.persistence.EntityExistsException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) ConfigurationException(javax.naming.ConfigurationException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HypervisorVersionChangedException(com.cloud.utils.exception.HypervisorVersionChangedException) UnknownHostException(java.net.UnknownHostException) UnableDeleteHostException(com.cloud.resource.UnableDeleteHostException) CitrixResourceBase(com.cloud.hypervisor.xenserver.resource.CitrixResourceBase) SessionAuthenticationFailed(com.xensource.xenapi.Types.SessionAuthenticationFailed) Map(java.util.Map) HashMap(java.util.HashMap) InetAddress(java.net.InetAddress) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 3 with DiscoveredWithErrorException

use of com.cloud.exception.DiscoveredWithErrorException in project cloudstack by apache.

the class LibvirtServerDiscoverer method find.

@Override
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI uri, String username, String password, List<String> hostTags) throws DiscoveryException {
    ClusterVO cluster = _clusterDao.findById(clusterId);
    if (cluster == null || cluster.getHypervisorType() != getHypervisorType()) {
        if (s_logger.isInfoEnabled())
            s_logger.info("invalid cluster id or cluster is not for " + getHypervisorType() + " hypervisors");
        return null;
    }
    Map<KvmDummyResourceBase, Map<String, String>> resources = new HashMap<KvmDummyResourceBase, Map<String, String>>();
    Map<String, String> details = new HashMap<String, String>();
    if (!uri.getScheme().equals("http")) {
        String msg = "urlString is not http so we're not taking care of the discovery for this: " + uri;
        s_logger.debug(msg);
        return null;
    }
    com.trilead.ssh2.Connection sshConnection = null;
    String agentIp = null;
    try {
        String hostname = uri.getHost();
        InetAddress ia = InetAddress.getByName(hostname);
        agentIp = ia.getHostAddress();
        String guid = UUID.nameUUIDFromBytes(agentIp.getBytes()).toString();
        List<HostVO> existingHosts = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.Routing, dcId);
        if (existingHosts != null) {
            for (HostVO existingHost : existingHosts) {
                if (existingHost.getGuid().toLowerCase().startsWith(guid.toLowerCase())) {
                    s_logger.debug("Skipping " + agentIp + " because " + guid + " is already in the database for resource " + existingHost.getGuid());
                    return null;
                }
            }
        }
        sshConnection = new com.trilead.ssh2.Connection(agentIp, 22);
        sshConnection.connect(null, 60000, 60000);
        if (!sshConnection.authenticateWithPassword(username, password)) {
            s_logger.debug("Failed to authenticate");
            throw new DiscoveredWithErrorException("Authentication error");
        }
        if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "lsmod|grep kvm", 3)) {
            s_logger.debug("It's not a KVM enabled machine");
            return null;
        }
        List<PhysicalNetworkSetupInfo> netInfos = _networkMgr.getPhysicalNetworkInfo(dcId, getHypervisorType());
        String kvmPrivateNic = null;
        String kvmPublicNic = null;
        String kvmGuestNic = null;
        for (PhysicalNetworkSetupInfo info : netInfos) {
            if (info.getPrivateNetworkName() != null) {
                kvmPrivateNic = info.getPrivateNetworkName();
            }
            if (info.getPublicNetworkName() != null) {
                kvmPublicNic = info.getPublicNetworkName();
            }
            if (info.getGuestNetworkName() != null) {
                kvmGuestNic = info.getGuestNetworkName();
            }
        }
        if (kvmPrivateNic == null && kvmPublicNic == null && kvmGuestNic == null) {
            kvmPrivateNic = _kvmPrivateNic;
            kvmPublicNic = _kvmPublicNic;
            kvmGuestNic = _kvmGuestNic;
        }
        if (kvmPublicNic == null) {
            kvmPublicNic = (kvmGuestNic != null) ? kvmGuestNic : kvmPrivateNic;
        }
        if (kvmPrivateNic == null) {
            kvmPrivateNic = (kvmPublicNic != null) ? kvmPublicNic : kvmGuestNic;
        }
        if (kvmGuestNic == null) {
            kvmGuestNic = (kvmPublicNic != null) ? kvmPublicNic : kvmPrivateNic;
        }
        String parameters = " -m " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -g " + guid + " -a";
        parameters += " --pubNic=" + kvmPublicNic;
        parameters += " --prvNic=" + kvmPrivateNic;
        parameters += " --guestNic=" + kvmGuestNic;
        parameters += " --hypervisor=" + cluster.getHypervisorType().toString().toLowerCase();
        String setupAgentCommand = "cloudstack-setup-agent ";
        if (!username.equals("root")) {
            setupAgentCommand = "sudo cloudstack-setup-agent ";
        }
        if (!SSHCmdHelper.sshExecuteCmd(sshConnection, setupAgentCommand + parameters, 3)) {
            s_logger.info("cloudstack agent setup command failed: " + setupAgentCommand + parameters);
            return null;
        }
        KvmDummyResourceBase kvmResource = new KvmDummyResourceBase();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
        params.put("zone", Long.toString(dcId));
        params.put("pod", Long.toString(podId));
        params.put("cluster", Long.toString(clusterId));
        params.put("guid", guid);
        params.put("agentIp", agentIp);
        kvmResource.configure("kvm agent", params);
        resources.put(kvmResource, details);
        HostVO connectedHost = waitForHostConnect(dcId, podId, clusterId, guid);
        if (connectedHost == null)
            return null;
        details.put("guid", connectedHost.getGuid());
        // place a place holder guid derived from cluster ID
        if (cluster.getGuid() == null) {
            cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString());
            _clusterDao.update(clusterId, cluster);
        }
        // save user name and password
        _hostDao.loadDetails(connectedHost);
        Map<String, String> hostDetails = connectedHost.getDetails();
        hostDetails.put("password", password);
        hostDetails.put("username", username);
        _hostDao.saveDetails(connectedHost);
        return resources;
    } catch (DiscoveredWithErrorException e) {
        throw e;
    } catch (Exception e) {
        String msg = " can't setup agent, due to " + e.toString() + " - " + e.getMessage();
        s_logger.warn(msg);
    } finally {
        if (sshConnection != null)
            sshConnection.close();
    }
    return null;
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) HashMap(java.util.HashMap) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) HostVO(com.cloud.host.HostVO) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) DiscoveryException(com.cloud.exception.DiscoveryException) ConfigurationException(javax.naming.ConfigurationException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) UnableDeleteHostException(com.cloud.resource.UnableDeleteHostException) HashMap(java.util.HashMap) Map(java.util.Map) InetAddress(java.net.InetAddress) PhysicalNetworkSetupInfo(com.cloud.network.PhysicalNetworkSetupInfo)

Example 4 with DiscoveredWithErrorException

use of com.cloud.exception.DiscoveredWithErrorException in project cloudstack by apache.

the class VmwareServerDiscoverer method find.

@Override
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List<String> hostTags) throws DiscoveryException {
    if (s_logger.isInfoEnabled())
        s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost());
    if (podId == null) {
        if (s_logger.isInfoEnabled())
            s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
        return null;
    }
    boolean failureInClusterDiscovery = true;
    String vsmIp = "";
    ClusterVO cluster = _clusterDao.findById(clusterId);
    if (cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
        if (s_logger.isInfoEnabled())
            s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
        return null;
    }
    Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
    boolean legacyZone = _vmwareMgr.isLegacyZone(dcId);
    boolean usernameNotProvided = (username == null || username.isEmpty());
    boolean passwordNotProvided = (password == null || password.isEmpty());
    //Check if NOT a legacy zone.
    if (!legacyZone) {
        // Retrieve VMware DC associated with specified zone
        VmwareDatacenterVO vmwareDc = fetchVmwareDatacenterByZone(dcId);
        // If either or both not provided, try to retrieve & use the credentials from database, which are provided earlier while adding VMware DC to zone.
        if (usernameNotProvided || passwordNotProvided) {
            // Retrieve credentials associated with VMware DC
            s_logger.info("Username and/or Password not provided while adding cluster to cloudstack zone. " + "Hence using both username & password provided while adding VMware DC to CloudStack zone.");
            username = vmwareDc.getUser();
            password = vmwareDc.getPassword();
            clusterDetails.put("username", username);
            clusterDetails.put("password", password);
            _clusterDetailsDao.persist(clusterId, clusterDetails);
        }
        String updatedInventoryPath = validateCluster(url, vmwareDc);
        try {
            if (!URLDecoder.decode(url.getPath(), "UTF-8").equals(updatedInventoryPath)) {
                // If url from API doesn't specify DC then update url in database with DC associated with this zone.
                clusterDetails.put("url", url.getScheme() + "://" + url.getHost() + updatedInventoryPath);
                _clusterDetailsDao.persist(clusterId, clusterDetails);
            }
        } catch (UnsupportedEncodingException e) {
            throw new DiscoveredWithErrorException("Unable to decode URL path, URL path : " + url.getPath(), e);
        }
    } else {
        // For legacy zones insist on the old model of asking for credentials for each cluster being added.
        if (usernameNotProvided) {
            if (passwordNotProvided) {
                throw new InvalidParameterValueException("Please provide username & password to add this cluster to zone");
            } else {
                throw new InvalidParameterValueException("Please provide username to add this cluster to zone");
            }
        } else if (passwordNotProvided) {
            throw new InvalidParameterValueException("Please provide password to add this cluster to zone");
        }
    }
    List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
    if (hosts != null && hosts.size() > 0) {
        int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(hosts.get(0).getHypervisorType(), hosts.get(0).getHypervisorVersion());
        if (hosts.size() >= maxHostsPerCluster) {
            String msg = "VMware cluster " + cluster.getName() + " is too big to add new host, current size: " + hosts.size() + ", max. size: " + maxHostsPerCluster;
            s_logger.error(msg);
            throw new DiscoveredWithErrorException(msg);
        }
    }
    String privateTrafficLabel = null;
    String publicTrafficLabel = null;
    String guestTrafficLabel = null;
    Map<String, String> vsmCredentials = null;
    VirtualSwitchType defaultVirtualSwitchType = VirtualSwitchType.StandardVirtualSwitch;
    String paramGuestVswitchType = null;
    String paramGuestVswitchName = null;
    String paramPublicVswitchType = null;
    String paramPublicVswitchName = null;
    VmwareTrafficLabel guestTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Guest);
    VmwareTrafficLabel publicTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Public);
    DataCenterVO zone = _dcDao.findById(dcId);
    NetworkType zoneType = zone.getNetworkType();
    _readGlobalConfigParameters();
    // Private traffic will be only on standard vSwitch for now.
    if (useDVS) {
        // Parse url parameters for type of vswitch and name of vswitch specified at cluster level
        paramGuestVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC);
        paramGuestVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_GUEST_TRAFFIC);
        paramPublicVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC);
        paramPublicVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_PUBLIC_TRAFFIC);
        defaultVirtualSwitchType = getDefaultVirtualSwitchType();
    }
    // Zone level vSwitch Type depends on zone level traffic labels
    //
    // User can override Zone wide vswitch type (for public and guest) by providing following optional parameters in addClusterCmd
    // param "guestvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
    // param "publicvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
    //
    // Format of label is <VSWITCH>,<VLANID>,<VSWITCHTYPE>
    // If a field <VLANID> OR <VSWITCHTYPE> is not present leave it empty.
    // Ex: 1) vswitch0
    // 2) dvswitch0,200,vmwaredvs
    // 3) nexusepp0,300,nexusdvs
    // 4) vswitch1,400,vmwaresvs
    // 5) vswitch0
    // default vswitchtype is 'vmwaresvs'.
    // <VSWITCHTYPE> 'vmwaresvs' is for vmware standard vswitch
    // <VSWITCHTYPE> 'vmwaredvs' is for vmware distributed virtual switch
    // <VSWITCHTYPE> 'nexusdvs' is for cisco nexus distributed virtual switch
    // Get zone wide traffic labels for Guest traffic and Public traffic
    guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
    // Process traffic label information provided at zone level and cluster level
    guestTrafficLabelObj = getTrafficInfo(TrafficType.Guest, guestTrafficLabel, defaultVirtualSwitchType, paramGuestVswitchType, paramGuestVswitchName, clusterId);
    if (zoneType == NetworkType.Advanced) {
        // Get zone wide traffic label for Public traffic
        publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
        // Process traffic label information provided at zone level and cluster level
        publicTrafficLabelObj = getTrafficInfo(TrafficType.Public, publicTrafficLabel, defaultVirtualSwitchType, paramPublicVswitchType, paramPublicVswitchName, clusterId);
        // Configuration Check: A physical network cannot be shared by different types of virtual switches.
        //
        // Check if different vswitch types are chosen for same physical network
        // 1. Get physical network for guest traffic - multiple networks
        // 2. Get physical network for public traffic - single network
        // See if 2 is in 1
        //  if no - pass
        //  if yes - compare publicTrafficLabelObj.getVirtualSwitchType() == guestTrafficLabelObj.getVirtualSwitchType()
        //      true  - pass
        //      false - throw exception - fail cluster add operation
        List<? extends PhysicalNetwork> pNetworkListGuestTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Guest);
        List<? extends PhysicalNetwork> pNetworkListPublicTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Public);
        // Public network would be on single physical network hence getting first object of the list would suffice.
        PhysicalNetwork pNetworkPublic = pNetworkListPublicTraffic.get(0);
        if (pNetworkListGuestTraffic.contains(pNetworkPublic)) {
            if (publicTrafficLabelObj.getVirtualSwitchType() != guestTrafficLabelObj.getVirtualSwitchType()) {
                String msg = "Both public traffic and guest traffic is over same physical network " + pNetworkPublic + ". And virtual switch type chosen for each traffic is different" + ". A physical network cannot be shared by different types of virtual switches.";
                s_logger.error(msg);
                throw new InvalidParameterValueException(msg);
            }
        }
    }
    privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
    if (privateTrafficLabel != null) {
        s_logger.info("Detected private network label : " + privateTrafficLabel);
    }
    Pair<Boolean, Long> vsmInfo = new Pair<Boolean, Long>(false, 0L);
    if (nexusDVS && (guestTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) || ((zoneType == NetworkType.Advanced) && (publicTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch))) {
        // 2) Atleast 1 traffic type uses Nexus distributed virtual switch as backend.
        if (zoneType != NetworkType.Basic) {
            publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
            if (publicTrafficLabel != null) {
                s_logger.info("Detected public network label : " + publicTrafficLabel);
            }
        }
        // Get physical network label
        guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
        if (guestTrafficLabel != null) {
            s_logger.info("Detected guest network label : " + guestTrafficLabel);
        }
        // Before proceeding with validation of Nexus 1000v VSM check if an instance of Nexus 1000v VSM is already associated with this cluster.
        boolean clusterHasVsm = _vmwareMgr.hasNexusVSM(clusterId);
        if (!clusterHasVsm) {
            vsmIp = _urlParams.get("vsmipaddress");
            String vsmUser = _urlParams.get("vsmusername");
            String vsmPassword = _urlParams.get("vsmpassword");
            String clusterName = cluster.getName();
            try {
                vsmInfo = _nexusElement.validateAndAddVsm(vsmIp, vsmUser, vsmPassword, clusterId, clusterName);
            } catch (ResourceInUseException ex) {
                DiscoveryException discEx = new DiscoveryException(ex.getLocalizedMessage() + ". The resource is " + ex.getResourceName());
                throw discEx;
            }
        }
        vsmCredentials = _vmwareMgr.getNexusVSMCredentialsByClusterId(clusterId);
    }
    VmwareContext context = null;
    try {
        context = VmwareContextFactory.create(url.getHost(), username, password);
        if (privateTrafficLabel != null)
            context.registerStockObject("privateTrafficLabel", privateTrafficLabel);
        if (nexusDVS) {
            if (vsmCredentials != null) {
                s_logger.info("Stocking credentials of Nexus VSM");
                context.registerStockObject("vsmcredentials", vsmCredentials);
            }
        }
        List<ManagedObjectReference> morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, URLDecoder.decode(url.getPath(), "UTF-8"));
        if (morHosts == null)
            s_logger.info("Found 0 hosts.");
        if (privateTrafficLabel != null)
            context.uregisterStockObject("privateTrafficLabel");
        if (morHosts == null) {
            s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath(), "UTF-8"));
            return null;
        }
        ManagedObjectReference morCluster = null;
        clusterDetails = _clusterDetailsDao.findDetails(clusterId);
        if (clusterDetails.get("url") != null) {
            URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url")));
            morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath(), "UTF-8"));
            if (morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) {
                s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url"));
                return null;
            } else {
                ClusterMO clusterMo = new ClusterMO(context, morCluster);
                if (clusterMo.isHAEnabled()) {
                    clusterDetails.put("NativeHA", "true");
                    _clusterDetailsDao.persist(clusterId, clusterDetails);
                }
            }
        }
        if (!validateDiscoveredHosts(context, morCluster, morHosts)) {
            if (morCluster == null)
                s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster");
            else
                s_logger.warn("The discovered host does not belong to the cluster");
            return null;
        }
        Map<VmwareResource, Map<String, String>> resources = new HashMap<VmwareResource, Map<String, String>>();
        for (ManagedObjectReference morHost : morHosts) {
            Map<String, String> details = new HashMap<String, String>();
            Map<String, Object> params = new HashMap<String, Object>();
            HostMO hostMo = new HostMO(context, morHost);
            details.put("url", hostMo.getHostName());
            details.put("username", username);
            details.put("password", password);
            String guid = morHost.getType() + ":" + morHost.getValue() + "@" + url.getHost();
            details.put("guid", guid);
            params.put("url", hostMo.getHostName());
            params.put("username", username);
            params.put("password", password);
            params.put("zone", Long.toString(dcId));
            params.put("pod", Long.toString(podId));
            params.put("cluster", Long.toString(clusterId));
            params.put("guid", guid);
            if (privateTrafficLabel != null) {
                params.put("private.network.vswitch.name", privateTrafficLabel);
            }
            params.put("guestTrafficInfo", guestTrafficLabelObj);
            params.put("publicTrafficInfo", publicTrafficLabelObj);
            params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
            VmwareResource resource = new VmwareResource();
            try {
                resource.configure("VMware", params);
            } catch (ConfigurationException e) {
                _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage());
                s_logger.warn("Unable to instantiate " + url.getHost(), e);
            }
            resource.start();
            resources.put(resource, details);
        }
        // place a place holder guid derived from cluster ID
        try {
            cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes("UTF-8")).toString());
        } catch (UnsupportedEncodingException e) {
            throw new DiscoveredWithErrorException("Unable to create UUID based on string " + String.valueOf(clusterId) + ". Bad clusterId or UTF-8 encoding error.");
        }
        _clusterDao.update(clusterId, cluster);
        // Flag cluster discovery success
        failureInClusterDiscovery = false;
        return resources;
    } catch (DiscoveredWithErrorException e) {
        throw e;
    } catch (Exception e) {
        s_logger.warn("Unable to connect to Vmware vSphere server. service address: " + url.getHost() + ". " + e);
        return null;
    } finally {
        if (context != null)
            context.close();
        if (failureInClusterDiscovery && vsmInfo.first()) {
            try {
                s_logger.debug("Deleting Nexus 1000v VSM " + vsmIp + " because cluster discovery and addition to zone has failed.");
                _nexusElement.deleteCiscoNexusVSM(vsmInfo.second().longValue());
            } catch (Exception e) {
                s_logger.warn("Deleting Nexus 1000v VSM " + vsmIp + " failed.");
            }
        }
    }
}
Also used : VmwareTrafficLabel(com.cloud.network.VmwareTrafficLabel) VmwareResource(com.cloud.hypervisor.vmware.resource.VmwareResource) HashMap(java.util.HashMap) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) ClusterMO(com.cloud.hypervisor.vmware.mo.ClusterMO) URI(java.net.URI) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) NetworkType(com.cloud.dc.DataCenter.NetworkType) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ResourceInUseException(com.cloud.exception.ResourceInUseException) DiscoveryException(com.cloud.exception.DiscoveryException) Pair(com.cloud.utils.Pair) DataCenterVO(com.cloud.dc.DataCenterVO) ClusterVO(com.cloud.dc.ClusterVO) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) HostVO(com.cloud.host.HostVO) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) DiscoveryException(com.cloud.exception.DiscoveryException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) UnableDeleteHostException(com.cloud.resource.UnableDeleteHostException) ResourceInUseException(com.cloud.exception.ResourceInUseException) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VirtualSwitchType(com.cloud.hypervisor.vmware.mo.VirtualSwitchType) Map(java.util.Map) HashMap(java.util.HashMap) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 5 with DiscoveredWithErrorException

use of com.cloud.exception.DiscoveredWithErrorException in project cloudstack by apache.

the class VmwareManagerImpl method addHostToPodCluster.

@Override
public List<ManagedObjectReference> addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId, String hostInventoryPath) throws Exception {
    if (serviceContext == null) {
        throw new CloudRuntimeException("Invalid serviceContext");
    }
    ManagedObjectReference mor = serviceContext.getHostMorByPath(hostInventoryPath);
    String privateTrafficLabel = null;
    privateTrafficLabel = serviceContext.getStockObject("privateTrafficLabel");
    if (privateTrafficLabel == null) {
        privateTrafficLabel = _privateNetworkVSwitchName;
    }
    if (mor != null) {
        List<ManagedObjectReference> returnedHostList = new ArrayList<ManagedObjectReference>();
        if (mor.getType().equals("ComputeResource")) {
            List<ManagedObjectReference> hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host");
            assert (hosts != null && hosts.size() > 0);
            // For ESX host, we need to enable host firewall to allow VNC access
            HostMO hostMo = new HostMO(serviceContext, hosts.get(0));
            prepareHost(hostMo, privateTrafficLabel);
            returnedHostList.add(hosts.get(0));
            return returnedHostList;
        } else if (mor.getType().equals("ClusterComputeResource")) {
            List<ManagedObjectReference> hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host");
            assert (hosts != null);
            if (hosts.size() > 0) {
                AboutInfo about = (AboutInfo) (serviceContext.getVimClient().getDynamicProperty(hosts.get(0), "config.product"));
                String version = about.getApiVersion();
                int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(HypervisorType.VMware, version);
                if (hosts.size() > maxHostsPerCluster) {
                    String msg = "Failed to add VMware cluster as size is too big, current size: " + hosts.size() + ", max. size: " + maxHostsPerCluster;
                    s_logger.error(msg);
                    throw new DiscoveredWithErrorException(msg);
                }
            }
            for (ManagedObjectReference morHost : hosts) {
                // For ESX host, we need to enable host firewall to allow VNC access
                HostMO hostMo = new HostMO(serviceContext, morHost);
                prepareHost(hostMo, privateTrafficLabel);
                returnedHostList.add(morHost);
            }
            return returnedHostList;
        } else if (mor.getType().equals("HostSystem")) {
            // For ESX host, we need to enable host firewall to allow VNC access
            HostMO hostMo = new HostMO(serviceContext, mor);
            prepareHost(hostMo, privateTrafficLabel);
            returnedHostList.add(mor);
            return returnedHostList;
        } else {
            s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath);
            return null;
        }
    }
    s_logger.error("Unable to find host from inventory path: " + hostInventoryPath);
    return null;
}
Also used : HostMO(com.cloud.hypervisor.vmware.mo.HostMO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) AboutInfo(com.vmware.vim25.AboutInfo) DiscoveredWithErrorException(com.cloud.exception.DiscoveredWithErrorException) ArrayList(java.util.ArrayList) List(java.util.List) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

DiscoveredWithErrorException (com.cloud.exception.DiscoveredWithErrorException)5 DiscoveryException (com.cloud.exception.DiscoveryException)4 ClusterVO (com.cloud.dc.ClusterVO)3 HostVO (com.cloud.host.HostVO)3 UnableDeleteHostException (com.cloud.resource.UnableDeleteHostException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ConfigurationException (javax.naming.ConfigurationException)3 DataCenterVO (com.cloud.dc.DataCenterVO)2 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)2 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)2 HostMO (com.cloud.hypervisor.vmware.mo.HostMO)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 InetAddress (java.net.InetAddress)2 NetworkType (com.cloud.dc.DataCenter.NetworkType)1 ConnectionException (com.cloud.exception.ConnectionException)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 ResourceInUseException (com.cloud.exception.ResourceInUseException)1