Search in sources :

Example 1 with DiscoveredWithErrorException

use of com.cloud.legacymodel.exceptions.DiscoveredWithErrorException in project cosmic by MissionCriticalCloud.

the class XcpServerDiscoverer method find.

@Override
public Map<? extends ServerResource, Map<String, String>> find(final long dcId, final Long podId, final Long clusterId, final URI url, final String username, final String password, final List<String> hostTags) throws DiscoveryException {
    final Map<CitrixResourceBase, Map<String, String>> resources = new HashMap<>();
    Connection conn = null;
    if (!url.getScheme().equals("http")) {
        final 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) {
        final String msg = "must specify cluster Id when add host";
        s_logger.debug(msg);
        throw new RuntimeException(msg);
    }
    if (podId == null) {
        final String msg = "must specify pod Id when add host";
        s_logger.debug(msg);
        throw new RuntimeException(msg);
    }
    final ClusterVO cluster = this._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 {
        final String hostname = url.getHost();
        final InetAddress ia = InetAddress.getByName(hostname);
        final String hostIp = ia.getHostAddress();
        final Queue<String> pass = new LinkedList<>();
        pass.add(password);
        conn = this._connPool.getConnect(hostIp, username, pass);
        if (conn == null) {
            final String msg = "Unable to get a connection to " + url;
            s_logger.debug(msg);
            throw new DiscoveryException(msg);
        }
        final Set<Pool> pools = Pool.getAll(conn);
        final Pool pool = pools.iterator().next();
        final Pool.Record pr = pool.getRecord(conn);
        String poolUuid = pr.uuid;
        final 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*/
        final ClusterVO clu = this._clusterDao.findById(clusterId);
        if (clu.getGuid() == null) {
            setClusterGuid(clu, poolUuid);
        } else {
            final List<HostVO> clusterHosts = this._resourceMgr.listAllHostsInCluster(clusterId);
            if (clusterHosts != null && clusterHosts.size() > 0) {
                if (!clu.getGuid().equals(poolUuid)) {
                    final 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 (final Exception e) {
                s_logger.debug("Caught exception during logout", e);
            }
            conn.dispose();
            conn = null;
        }
        poolUuid = clu.getGuid();
        this._clusterDao.update(clusterId, clu);
        if (this._checkHvm) {
            for (final Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
                final Host.Record record = entry.getValue();
                boolean support_hvm = false;
                for (final String capability : record.capabilities) {
                    if (capability.contains("hvm")) {
                        support_hvm = true;
                        break;
                    }
                }
                if (!support_hvm) {
                    final String msg = "Unable to add host " + record.address + " because it doesn't support hvm";
                    this._alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg);
                    s_logger.debug(msg);
                    throw new RuntimeException(msg);
                }
            }
        }
        for (final Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
            final Host.Record record = entry.getValue();
            final String hostAddr = record.address;
            final String prodVersion = CitrixHelper.getProductVersion(record);
            final String xenVersion = record.softwareVersion.get("xen");
            String hostOS = record.softwareVersion.get("product_brand");
            if (hostOS == null) {
                hostOS = record.softwareVersion.get("platform_name");
            }
            final String hostOSVer = prodVersion;
            final String hostKernelVer = record.softwareVersion.get("linux");
            if (this._resourceMgr.findHostByGuid(record.uuid) != null) {
                s_logger.debug("Skipping " + record.address + " because " + record.uuid + " is already in the database.");
                continue;
            }
            final CitrixResourceBase resource = createServerResource(dcId, podId, record, latestHotFix);
            s_logger.info("Found host " + record.hostname + " ip=" + record.address + " product version=" + prodVersion);
            final Map<String, String> details = new HashMap<>();
            final Map<String, Object> params = new HashMap<>();
            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);
            final String privateNetworkLabel = this._networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer);
            final String storageNetworkLabel = this._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);
            }
            params.put("router.aggregation.command.each.timeout", this._configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
            params.put("wait", Integer.toString(this._wait));
            details.put("wait", Integer.toString(this._wait));
            params.put("migratewait", this._configDao.getValue(Config.MigrateWait.toString()));
            params.put(Config.XenServerMaxNics.toString().toLowerCase(), this._configDao.getValue(Config.XenServerMaxNics.toString()));
            params.put(Config.XenServerHeartBeatTimeout.toString().toLowerCase(), this._configDao.getValue(Config.XenServerHeartBeatTimeout.toString()));
            params.put(Config.XenServerHeartBeatInterval.toString().toLowerCase(), this._configDao.getValue(Config.XenServerHeartBeatInterval.toString()));
            params.put(Config.InstanceName.toString().toLowerCase(), this._instance);
            details.put(Config.InstanceName.toString().toLowerCase(), this._instance);
            try {
                resource.configure("XenServer", params);
            } catch (final ConfigurationException e) {
                this._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 (final SessionAuthenticationFailed e) {
        throw new DiscoveredWithErrorException("Authentication error");
    } catch (final XenAPIException e) {
        s_logger.warn("XenAPI exception", e);
        return null;
    } catch (final XmlRpcException e) {
        s_logger.warn("Xml Rpc Exception", e);
        return null;
    } catch (final UnknownHostException e) {
        s_logger.warn("Unable to resolve the host name", e);
        return null;
    } catch (final 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.legacymodel.exceptions.CloudRuntimeException) ConfigurationException(javax.naming.ConfigurationException) Pool(com.xensource.xenapi.Pool) XenServerConnectionPool(com.cloud.hypervisor.xenserver.resource.XenServerConnectionPool) DiscoveryException(com.cloud.legacymodel.exceptions.DiscoveryException) ClusterVO(com.cloud.dc.ClusterVO) UnknownHostException(java.net.UnknownHostException) Connection(com.xensource.xenapi.Connection) DiscoveredWithErrorException(com.cloud.legacymodel.exceptions.DiscoveredWithErrorException) Host(com.xensource.xenapi.Host) LinkedList(java.util.LinkedList) HostVO(com.cloud.host.HostVO) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) DiscoveredWithErrorException(com.cloud.legacymodel.exceptions.DiscoveredWithErrorException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) EntityExistsException(javax.persistence.EntityExistsException) HypervisorVersionChangedException(com.cloud.legacymodel.exceptions.HypervisorVersionChangedException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) UnableDeleteHostException(com.cloud.legacymodel.exceptions.UnableDeleteHostException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) UnknownHostException(java.net.UnknownHostException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiscoveryException(com.cloud.legacymodel.exceptions.DiscoveryException) 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 2 with DiscoveredWithErrorException

use of com.cloud.legacymodel.exceptions.DiscoveredWithErrorException in project cosmic by MissionCriticalCloud.

the class LibvirtServerDiscoverer method find.

@Override
public Map<? extends ServerResource, Map<String, String>> find(final long dcId, final Long podId, final Long clusterId, final URI uri, final String username, final String password, final List<String> hostTags) throws DiscoveryException {
    final ClusterVO cluster = this._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;
    }
    final Map<KvmDummyResourceBase, Map<String, String>> resources = new HashMap<>();
    final Map<String, String> details = new HashMap<>();
    if (!uri.getScheme().equals("http")) {
        final 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 {
        final String hostname = uri.getHost();
        final InetAddress ia = InetAddress.getByName(hostname);
        agentIp = ia.getHostAddress();
        final String guid = UUID.nameUUIDFromBytes(agentIp.getBytes()).toString();
        final List<HostVO> existingHosts = this._resourceMgr.listAllHostsInOneZoneByType(HostType.Routing, dcId);
        if (existingHosts != null) {
            for (final 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, SSH_PORT);
        try {
            sshConnection.connect(null, 60000, 60000);
        } catch (final IOException e) {
            s_logger.error("Cannot connect to KVM host at " + agentIp + ":" + SSH_PORT + "  due to: " + e.getMessage(), e);
            return null;
        }
        try {
            if (!sshConnection.authenticateWithPassword(username, password)) {
                s_logger.warn("Failed to authenticate to KVM host at " + agentIp + ":" + SSH_PORT);
                throw new DiscoveredWithErrorException("Authentication error");
            }
        } catch (final IOException e) {
            s_logger.error("Failed to authenticate to KVM host at  " + agentIp + ":" + SSH_PORT + "  due to: " + e.getMessage(), e);
            return null;
        }
        if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "lsmod | grep kvm", 3)) {
            s_logger.debug("It's not a KVM enabled machine");
            return null;
        }
        final String parameters = " -m " + this._hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -g " + guid;
        String setupAgentCommand = "cosmic-setup-agent ";
        if (!username.equals("root")) {
            setupAgentCommand = "sudo cosmic-setup-agent ";
        }
        if (!SSHCmdHelper.sshExecuteCmd(sshConnection, setupAgentCommand + parameters, 3)) {
            s_logger.info("cosmic agent setup command failed: " + setupAgentCommand + parameters);
            return null;
        }
        final KvmDummyResourceBase kvmResource = new KvmDummyResourceBase();
        final Map<String, Object> params = new HashMap<>();
        params.put("router.aggregation.command.each.timeout", this._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);
        final 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());
            this._clusterDao.update(clusterId, cluster);
        }
        // save user name and password
        this._hostDao.loadDetails(connectedHost);
        final Map<String, String> hostDetails = connectedHost.getDetails();
        hostDetails.put("password", password);
        hostDetails.put("username", username);
        this._hostDao.saveDetails(connectedHost);
        return resources;
    } catch (final ConfigurationException e) {
        s_logger.error("Failed to obtain configuration parameters for KVM host: " + e.getMessage(), e);
    } catch (final UnknownHostException e) {
        s_logger.error("Failed to discover IP of KVM host at " + agentIp + " due to: " + e.getMessage(), e);
    } finally {
        if (sshConnection != null) {
            sshConnection.close();
        }
    }
    return null;
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) DiscoveredWithErrorException(com.cloud.legacymodel.exceptions.DiscoveredWithErrorException) IOException(java.io.IOException) HostVO(com.cloud.host.HostVO) ConfigurationException(javax.naming.ConfigurationException) HashMap(java.util.HashMap) Map(java.util.Map) InetAddress(java.net.InetAddress)

Aggregations

ClusterVO (com.cloud.dc.ClusterVO)2 HostVO (com.cloud.host.HostVO)2 DiscoveredWithErrorException (com.cloud.legacymodel.exceptions.DiscoveredWithErrorException)2 InetAddress (java.net.InetAddress)2 UnknownHostException (java.net.UnknownHostException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ConfigurationException (javax.naming.ConfigurationException)2 CitrixResourceBase (com.cloud.hypervisor.xenserver.resource.CitrixResourceBase)1 XenServerConnectionPool (com.cloud.hypervisor.xenserver.resource.XenServerConnectionPool)1 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)1 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)1 ConnectionException (com.cloud.legacymodel.exceptions.ConnectionException)1 DiscoveryException (com.cloud.legacymodel.exceptions.DiscoveryException)1 HypervisorVersionChangedException (com.cloud.legacymodel.exceptions.HypervisorVersionChangedException)1 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)1 UnableDeleteHostException (com.cloud.legacymodel.exceptions.UnableDeleteHostException)1 Connection (com.xensource.xenapi.Connection)1 Host (com.xensource.xenapi.Host)1 Pool (com.xensource.xenapi.Pool)1