Search in sources :

Example 6 with Pool

use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.

the class XenServerResourceNewBase method initialize.

@Override
public StartupCommand[] initialize() throws IllegalArgumentException {
    final StartupCommand[] cmds = super.initialize();
    final Connection conn = getConnection();
    final Pool pool;
    try {
        pool = Pool.getByUuid(conn, _host.getPool());
        final Pool.Record poolr = pool.getRecord(conn);
        final Host.Record masterRecord = poolr.master.getRecord(conn);
        if (_host.getUuid().equals(masterRecord.uuid)) {
            _listener = new VmEventListener(true);
        // 
        // TODO disable event listener for now. Wait until everything else is ready
        // 
        // _listener.start();
        } else {
            _listener = new VmEventListener(false);
        }
    } catch (final XenAPIException e) {
        throw new CloudRuntimeException("Unable to determine who is the master", e);
    } catch (final XmlRpcException e) {
        throw new CloudRuntimeException("Unable to determine who is the master", e);
    }
    return cmds;
}
Also used : StartupCommand(com.cloud.agent.api.StartupCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Pool(com.xensource.xenapi.Pool) Host(com.xensource.xenapi.Host) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 7 with Pool

use of com.xensource.xenapi.Pool 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 = _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 = _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 = _clusterDao.findById(clusterId);
        if (clu.getGuid() == null) {
            setClusterGuid(clu, poolUuid);
        } else {
            final List<HostVO> clusterHosts = _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();
        _clusterDao.update(clusterId, clu);
        if (_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";
                    _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 (_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 = _networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer);
            final 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);
            }
            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 (final 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 (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.utils.exception.CloudRuntimeException) ConfigurationException(javax.naming.ConfigurationException) Pool(com.xensource.xenapi.Pool) XenServerConnectionPool(com.cloud.hypervisor.xenserver.resource.XenServerConnectionPool) DiscoveryException(com.cloud.exception.DiscoveryException) 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 8 with Pool

use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.

the class CitrixCreateVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final CreateVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
    final String vmName = command.getVmName();
    final String vmSnapshotName = command.getTarget().getSnapshotName();
    final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
    VmPowerState vmState = VmPowerState.HALTED;
    final String guestOSType = command.getGuestOSType();
    final String platformEmulator = command.getPlatformEmulator();
    final boolean snapshotMemory = command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
    final long timeout = command.getWait();
    final Connection conn = citrixResourceBase.getConnection();
    VM vm = null;
    VM vmSnapshot = null;
    boolean success = false;
    try {
        // check if VM snapshot already exists
        final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
        if (vmSnapshots == null || vmSnapshots.size() > 0) {
            return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
        }
        // check if there is already a task for this VM snapshot
        Task task = null;
        Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
        if (tasks == null) {
            tasks = new LinkedHashSet<>();
        }
        final Set<Task> tasksByName = Task.getByNameLabel(conn, "Async.VM.checkpoint");
        if (tasksByName != null) {
            tasks.addAll(tasksByName);
        }
        for (final Task taskItem : tasks) {
            if (taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")) {
                final String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
                if (vmSnapshotTaskName != null && vmSnapshotTaskName.equals(command.getTarget().getSnapshotName())) {
                    task = taskItem;
                }
            }
        }
        // create a new task if there is no existing task for this VM snapshot
        if (task == null) {
            try {
                vm = citrixResourceBase.getVM(conn, vmName);
                vmState = vm.getPowerState(conn);
            } catch (final Exception e) {
                if (!snapshotMemory) {
                    vm = citrixResourceBase.createWorkingVM(conn, vmName, guestOSType, platformEmulator, listVolumeTo);
                }
            }
            if (vm == null) {
                return new CreateVMSnapshotAnswer(command, false, "Creating VM Snapshot Failed due to can not find vm: " + vmName);
            }
            // call Xenserver API
            if (!snapshotMemory) {
                task = vm.snapshotAsync(conn, vmSnapshotName);
            } else {
                final Set<VBD> vbds = vm.getVBDs(conn);
                final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
                for (final VBD vbd : vbds) {
                    final VBD.Record vbdr = vbd.getRecord(conn);
                    if (vbdr.userdevice.equals("0")) {
                        final VDI vdi = vbdr.VDI;
                        final SR sr = vdi.getSR(conn);
                        // store memory image on the same SR with ROOT volume
                        pool.setSuspendImageSR(conn, sr);
                    }
                }
                task = vm.checkpointAsync(conn, vmSnapshotName);
            }
            task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
        }
        citrixResourceBase.waitForTask(conn, task, 1000, timeout * 1000);
        citrixResourceBase.checkForSuccess(conn, task);
        final String result = task.getResult(conn);
        // extract VM snapshot ref from result
        final String ref = result.substring("<value>".length(), result.length() - "</value>".length());
        vmSnapshot = Types.toVM(ref);
        try {
            Thread.sleep(5000);
        } catch (final InterruptedException ex) {
        }
        // calculate used capacity for this VM snapshot
        for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
            final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
            volumeTo.setSize(size);
        }
        success = true;
        return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
    } catch (final Exception e) {
        String msg = "";
        if (e instanceof Types.BadAsyncResult) {
            final String licenseKeyWord = "LICENCE_RESTRICTION";
            final Types.BadAsyncResult errorResult = (Types.BadAsyncResult) e;
            if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) {
                msg = licenseKeyWord;
            }
        } else {
            msg = e.toString();
        }
        s_logger.warn("Creating VM Snapshot " + command.getTarget().getSnapshotName() + " failed due to: " + msg, e);
        return new CreateVMSnapshotAnswer(command, false, msg);
    } finally {
        try {
            if (!success) {
                if (vmSnapshot != null) {
                    s_logger.debug("Delete exsisting VM Snapshot " + vmSnapshotName + " after making VolumeTO failed");
                    final Set<VBD> vbds = vmSnapshot.getVBDs(conn);
                    for (final VBD vbd : vbds) {
                        final VBD.Record vbdr = vbd.getRecord(conn);
                        if (vbdr.type == Types.VbdType.DISK) {
                            final VDI vdi = vbdr.VDI;
                            vdi.destroy(conn);
                        }
                    }
                    vmSnapshot.destroy(conn);
                }
            }
            if (vmState == VmPowerState.HALTED) {
                if (vm != null) {
                    vm.destroy(conn);
                }
            }
        } catch (final Exception e2) {
            s_logger.error("delete snapshot error due to " + e2.getMessage());
        }
    }
}
Also used : Types(com.xensource.xenapi.Types) Task(com.xensource.xenapi.Task) Connection(com.xensource.xenapi.Connection) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) VM(com.xensource.xenapi.VM) VolumeObjectTO(com.cloud.storage.to.VolumeObjectTO) VBD(com.xensource.xenapi.VBD) Pool(com.xensource.xenapi.Pool) VDI(com.xensource.xenapi.VDI) VmPowerState(com.xensource.xenapi.Types.VmPowerState) SR(com.xensource.xenapi.SR)

Example 9 with Pool

use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.

the class CitrixClusterVMMetaDataSyncCommandWrapper method execute.

@Override
public Answer execute(final ClusterVMMetaDataSyncCommand command, final CitrixResourceBase citrixResourceBase) {
    final Connection conn = citrixResourceBase.getConnection();
    // check if this is master
    try {
        final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
        final Pool.Record poolr = pool.getRecord(conn);
        final Host.Record hostr = poolr.master.getRecord(conn);
        if (!citrixResourceBase.getHost().getUuid().equals(hostr.uuid)) {
            return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
        }
    } catch (XmlRpcException | XenAPIException e) {
        s_logger.warn("Check for master failed, failing the Cluster sync VMMetaData command");
        return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
    }
    final HashMap<String, String> vmMetadatum = citrixResourceBase.clusterVMMetaDataSync(conn);
    return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), vmMetadatum);
}
Also used : ClusterVMMetaDataSyncAnswer(com.cloud.agent.api.ClusterVMMetaDataSyncAnswer) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Pool(com.xensource.xenapi.Pool) Host(com.xensource.xenapi.Host) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 10 with Pool

use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.

the class NotAValidCommand method testClusterVMMetaDataSyncCommand.

@Test
public void testClusterVMMetaDataSyncCommand() {
    final String uuid = "6172d8b7-ba10-4a70-93f9-ecaf41f51d53";
    final Connection conn = Mockito.mock(Connection.class);
    final XsHost xsHost = Mockito.mock(XsHost.class);
    final Pool pool = PowerMockito.mock(Pool.class);
    final Pool.Record poolr = Mockito.mock(Pool.Record.class);
    final Host.Record hostr = Mockito.mock(Host.Record.class);
    final Host master = Mockito.mock(Host.class);
    final ClusterVMMetaDataSyncCommand vmDataSync = new ClusterVMMetaDataSyncCommand(10, 1l);
    final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
    assertNotNull(wrapper);
    when(citrixResourceBase.getConnection()).thenReturn(conn);
    try {
        when(citrixResourceBase.getHost()).thenReturn(xsHost);
        when(citrixResourceBase.getHost().getUuid()).thenReturn(uuid);
        when(xsHost.getPool()).thenReturn("pool");
        PowerMockito.mockStatic(Pool.class);
        when(Pool.getByUuid(conn, "pool")).thenReturn(pool);
        PowerMockito.mockStatic(Pool.Record.class);
        when(pool.getRecord(conn)).thenReturn(poolr);
        poolr.master = master;
        when(poolr.master.getRecord(conn)).thenReturn(hostr);
        hostr.uuid = uuid;
    } catch (final XenAPIException | XmlRpcException e) {
        fail(e.getMessage());
    }
    final Answer answer = wrapper.execute(vmDataSync, citrixResourceBase);
    verify(citrixResourceBase, times(1)).getConnection();
    assertTrue(answer.getResult());
}
Also used : XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) ClusterVMMetaDataSyncCommand(com.cloud.agent.api.ClusterVMMetaDataSyncCommand) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) Host(com.xensource.xenapi.Host) RebootAnswer(com.cloud.agent.api.RebootAnswer) CreateAnswer(com.cloud.agent.api.storage.CreateAnswer) Answer(com.cloud.agent.api.Answer) AttachAnswer(com.cloud.storage.command.AttachAnswer) Pool(com.xensource.xenapi.Pool) XmlRpcException(org.apache.xmlrpc.XmlRpcException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

Pool (com.xensource.xenapi.Pool)16 Connection (com.xensource.xenapi.Connection)14 XenAPIException (com.xensource.xenapi.Types.XenAPIException)13 XmlRpcException (org.apache.xmlrpc.XmlRpcException)13 Host (com.xensource.xenapi.Host)12 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 Types (com.xensource.xenapi.Types)6 StartupCommand (com.cloud.agent.api.StartupCommand)4 HashMap (java.util.HashMap)4 Answer (com.cloud.agent.api.Answer)2 ClusterVMMetaDataSyncAnswer (com.cloud.agent.api.ClusterVMMetaDataSyncAnswer)2 ClusterVMMetaDataSyncCommand (com.cloud.agent.api.ClusterVMMetaDataSyncCommand)2 CreateVMSnapshotAnswer (com.cloud.agent.api.CreateVMSnapshotAnswer)2 RebootAnswer (com.cloud.agent.api.RebootAnswer)2 SetupAnswer (com.cloud.agent.api.SetupAnswer)2 StartupRoutingCommand (com.cloud.agent.api.StartupRoutingCommand)2 StartupStorageCommand (com.cloud.agent.api.StartupStorageCommand)2 CreateAnswer (com.cloud.agent.api.storage.CreateAnswer)2 ClusterVO (com.cloud.dc.ClusterVO)2 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)2