Refactoring the whole XsHost thing

Refactor the ReadyCommand
Fixing the old test
Adding basic tests for ReadyCommandWrapper
This commit is contained in:
wilderrodrigues 2015-03-20 13:51:46 +01:00
parent c3ae8c793b
commit 30e72e4a15
16 changed files with 1556 additions and 1304 deletions

View File

@ -16,11 +16,8 @@
// under the License.
package com.cloud.hypervisor.xenserver.resource;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import com.xensource.xenapi.Host;
/**
@ -28,18 +25,13 @@ import com.xensource.xenapi.Host;
*
*/
public class CitrixHelper {
private static final Logger s_logger = Logger.getLogger(CitrixHelper.class);
private static final HashMap<String, MemoryValues> XenServerGuestOsMemoryMap = new HashMap<String, MemoryValues>(70);
private static final ArrayList<String> GuestOsList = new ArrayList<String>(70);
public static class MemoryValues {
long max;
long min;
public MemoryValues(long min, long max) {
public MemoryValues(final long min, final long max) {
this.min = min * 1024 * 1024;
this.max = max * 1024 * 1024;
}
@ -53,8 +45,6 @@ public class CitrixHelper {
}
}
static {
XenServerGuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l));
XenServerGuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l));
@ -207,37 +197,37 @@ public class CitrixHelper {
XenServerGuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(256l, 4 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(512l, 32 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(512l, 128 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 14.04 (32-bit)", new MemoryValues(512l, 32 * 1024l));
XenServerGuestOsMemoryMap.put("Ubuntu 14.04 (64-bit)", new MemoryValues(512l, 128 * 1024l));
}
public static long getXenServerStaticMax(String stdType, boolean bootFromCD) {
MemoryValues recommendedMaxMinMemory = XenServerGuestOsMemoryMap.get(stdType);
public static long getXenServerStaticMax(final String stdType, final boolean bootFromCD) {
final MemoryValues recommendedMaxMinMemory = XenServerGuestOsMemoryMap.get(stdType);
if (recommendedMaxMinMemory == null) {
return 0l;
}
return recommendedMaxMinMemory.getMax();
}
public static long getXenServerStaticMin(String stdType, boolean bootFromCD) {
MemoryValues recommendedMaxMinMemory = XenServerGuestOsMemoryMap.get(stdType);
public static long getXenServerStaticMin(final String stdType, final boolean bootFromCD) {
final MemoryValues recommendedMaxMinMemory = XenServerGuestOsMemoryMap.get(stdType);
if (recommendedMaxMinMemory == null) {
return 0l;
}
return recommendedMaxMinMemory.getMin();
}
public static String getProductVersion(Host.Record record) {
public static String getProductVersion(final Host.Record record) {
String prodVersion = record.softwareVersion.get("product_version");
if (prodVersion == null) {
prodVersion = record.softwareVersion.get("platform_version").trim();
} else {
prodVersion = prodVersion.trim();
String[] items = prodVersion.split("\\.");
final String[] items = prodVersion.split("\\.");
if (Integer.parseInt(items[0]) > 6) {
prodVersion = "6.5.0";
} else if (Integer.parseInt(items[0]) == 6 && Integer.parseInt(items[1]) >= 4) {

View File

@ -27,15 +27,6 @@ import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.NetworkUsageAnswer;
@ -49,6 +40,14 @@ import com.cloud.resource.ServerResource;
import com.cloud.storage.Storage;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
@Local(value = ServerResource.class)
public class XcpOssResource extends CitrixResourceBase {
@ -57,55 +56,55 @@ public class XcpOssResource extends CitrixResourceBase {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xcposs/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xcposs/patch";
final String patchfilePath = Script.findScript("", patch);
if (patchfilePath == null) {
throw new CloudRuntimeException("Unable to find patch file " + patch);
}
File file = new File(patchfilePath);
final File file = new File(patchfilePath);
files.add(file);
return files;
}
@Override
protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) {
protected void fillHostInfo(final Connection conn, final StartupRoutingCommand cmd) {
super.fillHostInfo(conn, cmd);
cmd.setCaps(cmd.getCapabilities() + " , hvm");
}
@Override
protected boolean launchHeartBeat(Connection conn) {
protected boolean launchHeartBeat(final Connection conn) {
return true;
}
@Override
protected StartupStorageCommand initializeLocalSR(Connection conn) {
SR extsr = getLocalEXTSR(conn);
protected StartupStorageCommand initializeLocalSR(final Connection conn) {
final SR extsr = getLocalEXTSR(conn);
if (extsr != null) {
try {
String extuuid = extsr.getUuid(conn);
_host.localSRuuid = extuuid;
long cap = extsr.getPhysicalSize(conn);
final String extuuid = extsr.getUuid(conn);
_host.setLocalSRuuid(extuuid);
final long cap = extsr.getPhysicalSize(conn);
if (cap > 0) {
long avail = cap - extsr.getPhysicalUtilisation(conn);
String name = "Cloud Stack Local EXT Storage Pool for " + _host.uuid;
final long avail = cap - extsr.getPhysicalUtilisation(conn);
final String name = "Cloud Stack Local EXT Storage Pool for " + _host.getUuid();
extsr.setNameDescription(conn, name);
Host host = Host.getByUuid(conn, _host.uuid);
String address = host.getAddress(conn);
StoragePoolInfo pInfo = new StoragePoolInfo(extsr.getNameLabel(conn), address, SRType.EXT.toString(), SRType.EXT.toString(), Storage.StoragePoolType.EXT, cap, avail);
StartupStorageCommand cmd = new StartupStorageCommand();
final Host host = Host.getByUuid(conn, _host.getUuid());
final String address = host.getAddress(conn);
final StoragePoolInfo pInfo = new StoragePoolInfo(extsr.getNameLabel(conn), address, SRType.EXT.toString(), SRType.EXT.toString(), Storage.StoragePoolType.EXT, cap, avail);
final StartupStorageCommand cmd = new StartupStorageCommand();
cmd.setPoolInfo(pInfo);
cmd.setGuid(_host.uuid);
cmd.setGuid(_host.getUuid());
cmd.setDataCenter(Long.toString(_dcId));
cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
return cmd;
}
} catch (XenAPIException e) {
String msg = "build local EXT info err in host:" + _host.uuid + e.toString();
} catch (final XenAPIException e) {
final String msg = "build local EXT info err in host:" + _host.getUuid() + e.toString();
s_logger.warn(msg);
} catch (XmlRpcException e) {
String msg = "build local EXT info err in host:" + _host.uuid + e.getMessage();
} catch (final XmlRpcException e) {
final String msg = "build local EXT info err in host:" + _host.getUuid() + e.getMessage();
s_logger.warn(msg);
}
}
@ -113,7 +112,7 @@ public class XcpOssResource extends CitrixResourceBase {
}
@Override
protected String getGuestOsType(String stdType, String platformEmulator, boolean bootFromCD) {
protected String getGuestOsType(final String stdType, final String platformEmulator, final boolean bootFromCD) {
if (stdType.equalsIgnoreCase("Debian GNU/Linux 6(64-bit)")) {
return "Debian Squeeze 6.0 (64-bit)";
} else if (stdType.equalsIgnoreCase("CentOS 5.6 (64-bit)")) {
@ -124,21 +123,21 @@ public class XcpOssResource extends CitrixResourceBase {
}
@Override
protected synchronized VBD createPatchVbd(Connection conn, String vmName, VM vm) throws XmlRpcException, XenAPIException {
if (_host.localSRuuid != null) {
protected synchronized VBD createPatchVbd(final Connection conn, final String vmName, final VM vm) throws XmlRpcException, XenAPIException {
if (_host.getLocalSRuuid() != null) {
//create an iso vdi on it
String result = callHostPlugin(conn, "vmops", "createISOVHD", "uuid", _host.localSRuuid);
final String result = callHostPlugin(conn, "vmops", "createISOVHD", "uuid", _host.getLocalSRuuid());
if (result == null || result.equalsIgnoreCase("Failed")) {
throw new CloudRuntimeException("can not create systemvm vdi");
}
Set<VDI> vdis = VDI.getByNameLabel(conn, "systemvm-vdi");
final Set<VDI> vdis = VDI.getByNameLabel(conn, "systemvm-vdi");
if (vdis.size() != 1) {
throw new CloudRuntimeException("can not find systemvmiso");
}
VDI systemvmVDI = vdis.iterator().next();
final VDI systemvmVDI = vdis.iterator().next();
VBD.Record cdromVBDR = new VBD.Record();
final VBD.Record cdromVBDR = new VBD.Record();
cdromVBDR.VM = vm;
cdromVBDR.empty = false;
cdromVBDR.bootable = false;
@ -146,32 +145,32 @@ public class XcpOssResource extends CitrixResourceBase {
cdromVBDR.mode = Types.VbdMode.RO;
cdromVBDR.type = Types.VbdType.DISK;
cdromVBDR.VDI = systemvmVDI;
VBD cdromVBD = VBD.create(conn, cdromVBDR);
final VBD cdromVBD = VBD.create(conn, cdromVBDR);
return cdromVBD;
} else {
throw new CloudRuntimeException("can not find local sr");
}
}
protected NetworkUsageAnswer execute(NetworkUsageCommand cmd) {
protected NetworkUsageAnswer execute(final NetworkUsageCommand cmd) {
try {
Connection conn = getConnection();
final Connection conn = getConnection();
if (cmd.getOption() != null && cmd.getOption().equals("create")) {
String result = networkUsage(conn, cmd.getPrivateIP(), "create", null);
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
final String result = networkUsage(conn, cmd.getPrivateIP(), "create", null);
final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
return answer;
}
long[] stats = getNetworkStats(conn, cmd.getPrivateIP());
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
final long[] stats = getNetworkStats(conn, cmd.getPrivateIP());
final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
return answer;
} catch (Exception ex) {
} catch (final Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(cmd, ex);
}
}
@Override
public Answer executeRequest(Command cmd) {
public Answer executeRequest(final Command cmd) {
if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand) cmd);
} else {
@ -180,18 +179,18 @@ public class XcpOssResource extends CitrixResourceBase {
}
@Override
public StopAnswer execute(StopCommand cmd) {
StopAnswer answer = super.execute(cmd);
String vmName = cmd.getVmName();
public StopAnswer execute(final StopCommand cmd) {
final StopAnswer answer = super.execute(cmd);
final String vmName = cmd.getVmName();
if (vmName.startsWith("v-")) {
Connection conn = getConnection();
final Connection conn = getConnection();
callHostPlugin(conn, "vmops", "setDNATRule", "add", "false");
}
return answer;
}
@Override
protected void setMemory(Connection conn, VM vm, long minMemsize, long maxMemsize) throws XmlRpcException, XenAPIException {
protected void setMemory(final Connection conn, final VM vm, final long minMemsize, final long maxMemsize) throws XmlRpcException, XenAPIException {
vm.setMemoryLimits(conn, mem_32m, maxMemsize, minMemsize, maxMemsize);
}
}

View File

@ -89,7 +89,7 @@ public class XenServer56Resource extends CitrixResourceBase {
final String bridge = networkr.bridge.trim();
for (final PIF pif : networkr.PIFs) {
final PIF.Record pifr = pif.getRecord(conn);
if (!pifr.host.getUuid(conn).equalsIgnoreCase(_host.uuid)) {
if (!pifr.host.getUuid(conn).equalsIgnoreCase(_host.getUuid())) {
continue;
}
@ -102,13 +102,13 @@ public class XenServer56Resource extends CitrixResourceBase {
}
try {
vlan.destroy(conn);
final Host host = Host.getByUuid(conn, _host.uuid);
final Host host = Host.getByUuid(conn, _host.getUuid());
host.forgetDataSourceArchives(conn, "pif_" + bridge + "_tx");
host.forgetDataSourceArchives(conn, "pif_" + bridge + "_rx");
host.forgetDataSourceArchives(conn, "pif_" + device + "." + vlannum + "_tx");
host.forgetDataSourceArchives(conn, "pif_" + device + "." + vlannum + "_rx");
} catch (final XenAPIException e) {
s_logger.trace("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.uuid + " due to " + e.toString());
s_logger.trace("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.getUuid() + " due to " + e.toString());
}
}
return;
@ -210,7 +210,7 @@ public class XenServer56Resource extends CitrixResourceBase {
}
protected Boolean check_heartbeat(final String hostuuid) {
final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.ip, 22);
final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
try {
sshConnection.connect(null, 60000, 60000);
if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {

View File

@ -24,23 +24,10 @@ import java.util.Set;
import javax.ejb.Local;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Task;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.MigrateWithStorageAnswer;
@ -62,6 +49,17 @@ import com.cloud.network.Networks.TrafficType;
import com.cloud.resource.ServerResource;
import com.cloud.storage.Volume;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Task;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
@Local(value = ServerResource.class)
public class XenServer610Resource extends XenServer600Resource {
@ -72,7 +70,7 @@ public class XenServer610Resource extends XenServer600Resource {
}
@Override
public Answer executeRequest(Command cmd) {
public Answer executeRequest(final Command cmd) {
if (cmd instanceof MigrateWithStorageCommand) {
return execute((MigrateWithStorageCommand)cmd);
} else if (cmd instanceof MigrateWithStorageReceiveCommand) {
@ -88,34 +86,34 @@ public class XenServer610Resource extends XenServer600Resource {
}
}
private List<VolumeObjectTO> getUpdatedVolumePathsOfMigratedVm(Connection connection, VM migratedVm, DiskTO[] volumes) throws CloudRuntimeException {
List<VolumeObjectTO> volumeToList = new ArrayList<VolumeObjectTO>();
private List<VolumeObjectTO> getUpdatedVolumePathsOfMigratedVm(final Connection connection, final VM migratedVm, final DiskTO[] volumes) throws CloudRuntimeException {
final List<VolumeObjectTO> volumeToList = new ArrayList<VolumeObjectTO>();
try {
// Volume paths would have changed. Return that information.
Set<VBD> vbds = migratedVm.getVBDs(connection);
Map<String, VDI> deviceIdToVdiMap = new HashMap<String, VDI>();
final Set<VBD> vbds = migratedVm.getVBDs(connection);
final Map<String, VDI> deviceIdToVdiMap = new HashMap<String, VDI>();
// get vdi:vbdr to a map
for (VBD vbd : vbds) {
VBD.Record vbdr = vbd.getRecord(connection);
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(connection);
if (vbdr.type == Types.VbdType.DISK) {
VDI vdi = vbdr.VDI;
final VDI vdi = vbdr.VDI;
deviceIdToVdiMap.put(vbdr.userdevice, vdi);
}
}
for (DiskTO volumeTo : volumes) {
for (final DiskTO volumeTo : volumes) {
if (volumeTo.getType() != Volume.Type.ISO) {
VolumeObjectTO vol = (VolumeObjectTO)volumeTo.getData();
Long deviceId = volumeTo.getDiskSeq();
VDI vdi = deviceIdToVdiMap.get(deviceId.toString());
VolumeObjectTO newVol = new VolumeObjectTO();
final VolumeObjectTO vol = (VolumeObjectTO)volumeTo.getData();
final Long deviceId = volumeTo.getDiskSeq();
final VDI vdi = deviceIdToVdiMap.get(deviceId.toString());
final VolumeObjectTO newVol = new VolumeObjectTO();
newVol.setPath(vdi.getUuid(connection));
newVol.setId(vol.getId());
volumeToList.add(newVol);
}
}
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Unable to get the updated VDI paths of the migrated vm " + e.toString(), e);
throw new CloudRuntimeException("Unable to get the updated VDI paths of the migrated vm " + e.toString(), e);
}
@ -123,10 +121,10 @@ public class XenServer610Resource extends XenServer600Resource {
return volumeToList;
}
protected MigrateWithStorageAnswer execute(MigrateWithStorageCommand cmd) {
Connection connection = getConnection();
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
Map<VolumeTO, StorageFilerTO> volumeToFiler = cmd.getVolumeToFiler();
protected MigrateWithStorageAnswer execute(final MigrateWithStorageCommand cmd) {
final Connection connection = getConnection();
final VirtualMachineTO vmSpec = cmd.getVirtualMachine();
final Map<VolumeTO, StorageFilerTO> volumeToFiler = cmd.getVolumeToFiler();
final String vmName = vmSpec.getName();
Task task = null;
@ -134,24 +132,24 @@ public class XenServer610Resource extends XenServer600Resource {
prepareISO(connection, vmSpec.getName());
// Get the list of networks and recreate VLAN, if required.
for (NicTO nicTo : vmSpec.getNics()) {
for (final NicTO nicTo : vmSpec.getNics()) {
getNetwork(connection, nicTo);
}
Map<String, String> other = new HashMap<String, String>();
final Map<String, String> other = new HashMap<String, String>();
other.put("live", "true");
Network networkForSm = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork();
Host host = Host.getByUuid(connection, _host.uuid);
Map<String, String> token = host.migrateReceive(connection, networkForSm, other);
final Network networkForSm = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork();
final Host host = Host.getByUuid(connection, _host.getUuid());
final Map<String, String> token = host.migrateReceive(connection, networkForSm, other);
// Get the vm to migrate.
Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
VM vmToMigrate = vms.iterator().next();
final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
final VM vmToMigrate = vms.iterator().next();
// Create the vif map. The vm stays in the same cluster so we have to pass an empty vif map.
Map<VIF, Network> vifMap = new HashMap<VIF, Network>();
Map<VDI, SR> vdiMap = new HashMap<VDI, SR>();
for (Map.Entry<VolumeTO, StorageFilerTO> entry : volumeToFiler.entrySet()) {
final Map<VIF, Network> vifMap = new HashMap<VIF, Network>();
final Map<VDI, SR> vdiMap = new HashMap<VDI, SR>();
for (final Map.Entry<VolumeTO, StorageFilerTO> entry : volumeToFiler.entrySet()) {
vdiMap.put(getVDIbyUuid(connection, entry.getKey().getPath()), getStorageRepository(connection, entry.getValue().getUuid()));
}
@ -159,10 +157,10 @@ public class XenServer610Resource extends XenServer600Resource {
task = vmToMigrate.assertCanMigrateAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds
long timeout = (_migratewait) * 1000L;
final long timeout = _migratewait * 1000L;
waitForTask(connection, task, 1000, timeout);
checkForSuccess(connection, task);
} catch (Types.HandleInvalid e) {
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while checking if vm " + vmName + " can be migrated to the destination host " + host, e);
throw new CloudRuntimeException("Error while checking if vm " + vmName + " can be migrated to the " + "destination host " + host, e);
}
@ -171,90 +169,90 @@ public class XenServer610Resource extends XenServer600Resource {
task = vmToMigrate.migrateSendAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds.
long timeout = (_migratewait) * 1000L;
final long timeout = _migratewait * 1000L;
waitForTask(connection, task, 1000, timeout);
checkForSuccess(connection, task);
} catch (Types.HandleInvalid e) {
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while migrating vm " + vmName + " to the destination host " + host, e);
throw new CloudRuntimeException("Error while migrating vm " + vmName + " to the destination host " + host, e);
}
// Volume paths would have changed. Return that information.
List<VolumeObjectTO> volumeToList = getUpdatedVolumePathsOfMigratedVm(connection, vmToMigrate, vmSpec.getDisks());
final List<VolumeObjectTO> volumeToList = getUpdatedVolumePathsOfMigratedVm(connection, vmToMigrate, vmSpec.getDisks());
vmToMigrate.setAffinity(connection, host);
return new MigrateWithStorageAnswer(cmd, volumeToList);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.warn("Catch Exception " + e.getClass().getName() + ". Storage motion failed due to " + e.toString(), e);
return new MigrateWithStorageAnswer(cmd, e);
} finally {
if (task != null) {
try {
task.destroy(connection);
} catch (Exception e) {
s_logger.debug("Unable to destroy task " + task.toString() + " on host " + _host.uuid + " due to " + e.toString());
} catch (final Exception e) {
s_logger.debug("Unable to destroy task " + task.toString() + " on host " + _host.getUuid() + " due to " + e.toString());
}
}
}
}
protected MigrateWithStorageReceiveAnswer execute(MigrateWithStorageReceiveCommand cmd) {
Connection connection = getConnection();
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
Map<VolumeTO, StorageFilerTO> volumeToFiler = cmd.getVolumeToFiler();
protected MigrateWithStorageReceiveAnswer execute(final MigrateWithStorageReceiveCommand cmd) {
final Connection connection = getConnection();
final VirtualMachineTO vmSpec = cmd.getVirtualMachine();
final Map<VolumeTO, StorageFilerTO> volumeToFiler = cmd.getVolumeToFiler();
try {
// Get a map of all the SRs to which the vdis will be migrated.
Map<VolumeTO, Object> volumeToSr = new HashMap<VolumeTO, Object>();
for (Map.Entry<VolumeTO, StorageFilerTO> entry : volumeToFiler.entrySet()) {
SR sr = getStorageRepository(connection, entry.getValue().getUuid());
final Map<VolumeTO, Object> volumeToSr = new HashMap<VolumeTO, Object>();
for (final Map.Entry<VolumeTO, StorageFilerTO> entry : volumeToFiler.entrySet()) {
final SR sr = getStorageRepository(connection, entry.getValue().getUuid());
volumeToSr.put(entry.getKey(), sr);
}
// Get the list of networks to which the vifs will attach.
Map<NicTO, Object> nicToNetwork = new HashMap<NicTO, Object>();
for (NicTO nicTo : vmSpec.getNics()) {
Network network = getNetwork(connection, nicTo);
final Map<NicTO, Object> nicToNetwork = new HashMap<NicTO, Object>();
for (final NicTO nicTo : vmSpec.getNics()) {
final Network network = getNetwork(connection, nicTo);
nicToNetwork.put(nicTo, network);
}
Map<String, String> other = new HashMap<String, String>();
final Map<String, String> other = new HashMap<String, String>();
other.put("live", "true");
Network network = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork();
Host host = Host.getByUuid(connection, _host.uuid);
Map<String, String> token = host.migrateReceive(connection, network, other);
final Network network = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork();
final Host host = Host.getByUuid(connection, _host.getUuid());
final Map<String, String> token = host.migrateReceive(connection, network, other);
return new MigrateWithStorageReceiveAnswer(cmd, volumeToSr, nicToNetwork, token);
} catch (CloudRuntimeException e) {
} catch (final CloudRuntimeException e) {
s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageReceiveAnswer(cmd, e);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageReceiveAnswer(cmd, e);
}
}
protected MigrateWithStorageSendAnswer execute(MigrateWithStorageSendCommand cmd) {
Connection connection = getConnection();
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
Map<VolumeTO, Object> volumeToSr = cmd.getVolumeToSr();
Map<NicTO, Object> nicToNetwork = cmd.getNicToNetwork();
Map<String, String> token = cmd.getToken();
protected MigrateWithStorageSendAnswer execute(final MigrateWithStorageSendCommand cmd) {
final Connection connection = getConnection();
final VirtualMachineTO vmSpec = cmd.getVirtualMachine();
final Map<VolumeTO, Object> volumeToSr = cmd.getVolumeToSr();
final Map<NicTO, Object> nicToNetwork = cmd.getNicToNetwork();
final Map<String, String> token = cmd.getToken();
final String vmName = vmSpec.getName();
Set<VolumeTO> volumeToSet = null;
final Set<VolumeTO> volumeToSet = null;
boolean migrated = false;
Task task = null;
try {
Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
VM vmToMigrate = vms.iterator().next();
Map<String, String> other = new HashMap<String, String>();
final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
final VM vmToMigrate = vms.iterator().next();
final Map<String, String> other = new HashMap<String, String>();
other.put("live", "true");
// Create the vdi map which tells what volumes of the vm need to go on which sr on the destination.
Map<VDI, SR> vdiMap = new HashMap<VDI, SR>();
for (Map.Entry<VolumeTO, Object> entry : volumeToSr.entrySet()) {
final Map<VDI, SR> vdiMap = new HashMap<VDI, SR>();
for (final Map.Entry<VolumeTO, Object> entry : volumeToSr.entrySet()) {
if (entry.getValue() instanceof SR) {
SR sr = (SR)entry.getValue();
VDI vdi = getVDIbyUuid(connection, entry.getKey().getPath());
final SR sr = (SR)entry.getValue();
final VDI vdi = getVDIbyUuid(connection, entry.getKey().getPath());
vdiMap.put(vdi, sr);
} else {
throw new CloudRuntimeException("The object " + entry.getValue() + " passed is not of type SR.");
@ -262,11 +260,11 @@ public class XenServer610Resource extends XenServer600Resource {
}
// Create the vif map.
Map<VIF, Network> vifMap = new HashMap<VIF, Network>();
for (Map.Entry<NicTO, Object> entry : nicToNetwork.entrySet()) {
final Map<VIF, Network> vifMap = new HashMap<VIF, Network>();
for (final Map.Entry<NicTO, Object> entry : nicToNetwork.entrySet()) {
if (entry.getValue() instanceof Network) {
Network network = (Network)entry.getValue();
VIF vif = getVifByMac(connection, vmToMigrate, entry.getKey().getMac());
final Network network = (Network)entry.getValue();
final VIF vif = getVifByMac(connection, vmToMigrate, entry.getKey().getMac());
vifMap.put(vif, network);
} else {
throw new CloudRuntimeException("The object " + entry.getValue() + " passed is not of type Network.");
@ -277,10 +275,10 @@ public class XenServer610Resource extends XenServer600Resource {
task = vmToMigrate.assertCanMigrateAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds.
long timeout = (_migratewait) * 1000L;
final long timeout = _migratewait * 1000L;
waitForTask(connection, task, 1000, timeout);
checkForSuccess(connection, task);
} catch (Types.HandleInvalid e) {
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while checking if vm " + vmName + " can be migrated.", e);
throw new CloudRuntimeException("Error while checking if vm " + vmName + " can be migrated.", e);
}
@ -289,41 +287,41 @@ public class XenServer610Resource extends XenServer600Resource {
task = vmToMigrate.migrateSendAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds.
long timeout = (_migratewait) * 1000L;
final long timeout = _migratewait * 1000L;
waitForTask(connection, task, 1000, timeout);
checkForSuccess(connection, task);
} catch (Types.HandleInvalid e) {
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while migrating vm " + vmName, e);
throw new CloudRuntimeException("Error while migrating vm " + vmName, e);
}
migrated = true;
return new MigrateWithStorageSendAnswer(cmd, volumeToSet);
} catch (CloudRuntimeException e) {
} catch (final CloudRuntimeException e) {
s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageSendAnswer(cmd, e);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageSendAnswer(cmd, e);
} finally {
if (task != null) {
try {
task.destroy(connection);
} catch (Exception e) {
s_logger.debug("Unable to destroy task " + task.toString() + " on host " + _host.uuid + " due to " + e.toString());
} catch (final Exception e) {
s_logger.debug("Unable to destroy task " + task.toString() + " on host " + _host.getUuid() + " due to " + e.toString());
}
}
}
}
protected MigrateWithStorageCompleteAnswer execute(MigrateWithStorageCompleteCommand cmd) {
Connection connection = getConnection();
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
protected MigrateWithStorageCompleteAnswer execute(final MigrateWithStorageCompleteCommand cmd) {
final Connection connection = getConnection();
final VirtualMachineTO vmSpec = cmd.getVirtualMachine();
try {
Host host = Host.getByUuid(connection, _host.uuid);
Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
VM migratedVm = vms.iterator().next();
final Host host = Host.getByUuid(connection, _host.getUuid());
final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
final VM migratedVm = vms.iterator().next();
// Check the vm is present on the new host.
if (migratedVm == null) {
@ -331,47 +329,47 @@ public class XenServer610Resource extends XenServer600Resource {
}
// Volume paths would have changed. Return that information.
List<VolumeObjectTO> volumeToSet = getUpdatedVolumePathsOfMigratedVm(connection, migratedVm, vmSpec.getDisks());
final List<VolumeObjectTO> volumeToSet = getUpdatedVolumePathsOfMigratedVm(connection, migratedVm, vmSpec.getDisks());
migratedVm.setAffinity(connection, host);
return new MigrateWithStorageCompleteAnswer(cmd, volumeToSet);
} catch (CloudRuntimeException e) {
} catch (final CloudRuntimeException e) {
s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageCompleteAnswer(cmd, e);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageCompleteAnswer(cmd, e);
}
}
protected MigrateVolumeAnswer execute(MigrateVolumeCommand cmd) {
Connection connection = getConnection();
String volumeUUID = cmd.getVolumePath();
StorageFilerTO poolTO = cmd.getPool();
protected MigrateVolumeAnswer execute(final MigrateVolumeCommand cmd) {
final Connection connection = getConnection();
final String volumeUUID = cmd.getVolumePath();
final StorageFilerTO poolTO = cmd.getPool();
try {
SR destinationPool = getStorageRepository(connection, poolTO.getUuid());
VDI srcVolume = getVDIbyUuid(connection, volumeUUID);
Map<String, String> other = new HashMap<String, String>();
final SR destinationPool = getStorageRepository(connection, poolTO.getUuid());
final VDI srcVolume = getVDIbyUuid(connection, volumeUUID);
final Map<String, String> other = new HashMap<String, String>();
other.put("live", "true");
// Live migrate the vdi across pool.
Task task = srcVolume.poolMigrateAsync(connection, destinationPool, other);
long timeout = (_migratewait) * 1000L;
final Task task = srcVolume.poolMigrateAsync(connection, destinationPool, other);
final long timeout = _migratewait * 1000L;
waitForTask(connection, task, 1000, timeout);
checkForSuccess(connection, task);
VDI dvdi = Types.toVDI(task, connection);
final VDI dvdi = Types.toVDI(task, connection);
return new MigrateVolumeAnswer(cmd, true, null, dvdi.getUuid(connection));
} catch (Exception e) {
String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString();
} catch (final Exception e) {
final String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString();
s_logger.error(msg, e);
return new MigrateVolumeAnswer(cmd, false, msg, null);
}
}
@Override
protected void plugDom0Vif(Connection conn, VIF dom0Vif) throws XmlRpcException, XenAPIException {
protected void plugDom0Vif(final Connection conn, final VIF dom0Vif) throws XmlRpcException, XenAPIException {
// do nothing. In xenserver 6.1 and beyond this step isn't needed.
}
}

View File

@ -20,18 +20,16 @@ import java.util.Set;
import javax.ejb.Local;
import org.apache.cloudstack.hypervisor.xenserver.XenserverConfigs;
import org.apache.log4j.Logger;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.resource.ServerResource;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.HostPatch;
import com.xensource.xenapi.PoolPatch;
import org.apache.cloudstack.hypervisor.xenserver.XenserverConfigs;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.resource.ServerResource;
@Local(value = ServerResource.class)
public class XenServer620Resource extends XenServer610Resource {
private static final Logger s_logger = Logger.getLogger(XenServer620Resource.class);
@ -40,34 +38,33 @@ public class XenServer620Resource extends XenServer610Resource {
super();
}
protected boolean hostHasHotFix(Connection conn, String hotFixUuid) {
protected boolean hostHasHotFix(final Connection conn, final String hotFixUuid) {
try {
Host host = Host.getByUuid(conn, _host.uuid);
Host.Record re = host.getRecord(conn);
Set<HostPatch> patches = re.patches;
PoolPatch poolPatch = PoolPatch.getByUuid(conn, hotFixUuid);
for(HostPatch patch : patches) {
PoolPatch pp = patch.getPoolPatch(conn);
final Host host = Host.getByUuid(conn, _host.getUuid());
final Host.Record re = host.getRecord(conn);
final Set<HostPatch> patches = re.patches;
final PoolPatch poolPatch = PoolPatch.getByUuid(conn, hotFixUuid);
for(final HostPatch patch : patches) {
final PoolPatch pp = patch.getPoolPatch(conn);
if (pp.equals(poolPatch) && patch.getApplied(conn)) {
return true;
}
}
} catch (Exception e) {
} catch (final Exception e) {
s_logger.debug("can't get patches information for hotFix: " + hotFixUuid);
}
return false;
}
@Override
protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) {
protected void fillHostInfo(final Connection conn, final StartupRoutingCommand cmd) {
super.fillHostInfo(conn, cmd);
Map<String, String> details = cmd.getHostDetails();
Boolean hotFix62ESP1004 = hostHasHotFix(conn, XenserverConfigs.XSHotFix62ESP1004);
final Map<String, String> details = cmd.getHostDetails();
final Boolean hotFix62ESP1004 = hostHasHotFix(conn, XenserverConfigs.XSHotFix62ESP1004);
if( hotFix62ESP1004 != null && hotFix62ESP1004 ) {
details.put(XenserverConfigs.XS620HotFix , XenserverConfigs.XSHotFix62ESP1004);
} else {
Boolean hotFix62ESP1 = hostHasHotFix(conn, XenserverConfigs.XSHotFix62ESP1);
final Boolean hotFix62ESP1 = hostHasHotFix(conn, XenserverConfigs.XSHotFix62ESP1);
if( hotFix62ESP1 != null && hotFix62ESP1 ) {
details.put(XenserverConfigs.XS620HotFix , XenserverConfigs.XSHotFix62ESP1);
}

View File

@ -28,6 +28,15 @@ import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetGPUStatsAnswer;
import com.cloud.agent.api.GetGPUStatsCommand;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.resource.ServerResource;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.GPUGroup;
import com.xensource.xenapi.Host;
@ -38,16 +47,6 @@ import com.xensource.xenapi.VGPUType;
import com.xensource.xenapi.VGPUType.Record;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetGPUStatsAnswer;
import com.cloud.agent.api.GetGPUStatsCommand;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.resource.ServerResource;
@Local(value=ServerResource.class)
public class XenServer620SP1Resource extends XenServer620Resource {
private static final Logger s_logger = Logger.getLogger(XenServer620SP1Resource.class);
@ -57,8 +56,8 @@ public class XenServer620SP1Resource extends XenServer620Resource {
}
@Override
public Answer executeRequest(Command cmd) {
Class<? extends Command> clazz = cmd.getClass();
public Answer executeRequest(final Command cmd) {
final Class<? extends Command> clazz = cmd.getClass();
if (clazz == GetGPUStatsCommand.class) {
return execute((GetGPUStatsCommand) cmd);
} else {
@ -66,28 +65,28 @@ public class XenServer620SP1Resource extends XenServer620Resource {
}
}
protected GetGPUStatsAnswer execute(GetGPUStatsCommand cmd) {
Connection conn = getConnection();
protected GetGPUStatsAnswer execute(final GetGPUStatsCommand cmd) {
final Connection conn = getConnection();
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = new HashMap<String, HashMap<String, VgpuTypesInfo>>();
try {
groupDetails = getGPUGroupDetails(conn);
} catch (Exception e) {
String msg = "Unable to get GPU stats" + e.toString();
} catch (final Exception e) {
final String msg = "Unable to get GPU stats" + e.toString();
s_logger.warn(msg, e);
}
return new GetGPUStatsAnswer(cmd, groupDetails);
}
@Override
protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) {
protected void fillHostInfo(final Connection conn, final StartupRoutingCommand cmd) {
super.fillHostInfo(conn, cmd);
try {
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = getGPUGroupDetails(conn);
final HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = getGPUGroupDetails(conn);
cmd.setGpuGroupDetails(groupDetails);
if (groupDetails != null && !groupDetails.isEmpty()) {
cmd.setHostTags("GPU");
}
} catch (Exception e) {
} catch (final Exception e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Error while getting GPU device info from host " + cmd.getName(), e);
}
@ -95,26 +94,26 @@ public class XenServer620SP1Resource extends XenServer620Resource {
}
@Override
protected HashMap<String, HashMap<String, VgpuTypesInfo>> getGPUGroupDetails(Connection conn) throws XenAPIException, XmlRpcException {
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = new HashMap<String, HashMap<String, VgpuTypesInfo>>();
Host host = Host.getByUuid(conn, _host.uuid);
Set<PGPU> pgpus = host.getPGPUs(conn);
Iterator<PGPU> iter = pgpus.iterator();
protected HashMap<String, HashMap<String, VgpuTypesInfo>> getGPUGroupDetails(final Connection conn) throws XenAPIException, XmlRpcException {
final HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = new HashMap<String, HashMap<String, VgpuTypesInfo>>();
final Host host = Host.getByUuid(conn, _host.getUuid());
final Set<PGPU> pgpus = host.getPGPUs(conn);
final Iterator<PGPU> iter = pgpus.iterator();
while (iter.hasNext()) {
PGPU pgpu = iter.next();
GPUGroup gpuGroup = pgpu.getGPUGroup(conn);
Set<VGPUType> enabledVGPUTypes = gpuGroup.getEnabledVGPUTypes(conn);
String groupName = gpuGroup.getNameLabel(conn);
final PGPU pgpu = iter.next();
final GPUGroup gpuGroup = pgpu.getGPUGroup(conn);
final Set<VGPUType> enabledVGPUTypes = gpuGroup.getEnabledVGPUTypes(conn);
final String groupName = gpuGroup.getNameLabel(conn);
HashMap<String, VgpuTypesInfo> gpuCapacity = new HashMap<String, VgpuTypesInfo>();
if (groupDetails.get(groupName) != null) {
gpuCapacity = groupDetails.get(groupName);
}
// Get remaining capacity of all the enabled VGPU in a PGPU
if(enabledVGPUTypes != null) {
Iterator<VGPUType> it = enabledVGPUTypes.iterator();
final Iterator<VGPUType> it = enabledVGPUTypes.iterator();
while (it.hasNext()) {
VGPUType type = it.next();
Record record = type.getRecord(conn);
final VGPUType type = it.next();
final Record record = type.getRecord(conn);
Long remainingCapacity = pgpu.getRemainingCapacity(conn, type);
Long maxCapacity = pgpu.getSupportedVGPUMaxCapacities(conn).get(type);
VgpuTypesInfo entry;
@ -125,7 +124,7 @@ public class XenServer620SP1Resource extends XenServer620Resource {
entry.setMaxVmCapacity(maxCapacity);
gpuCapacity.put(record.modelName, entry);
} else {
VgpuTypesInfo vgpuTypeRecord = new VgpuTypesInfo(null, record.modelName, record.framebufferSize, record.maxHeads,
final VgpuTypesInfo vgpuTypeRecord = new VgpuTypesInfo(null, record.modelName, record.framebufferSize, record.maxHeads,
record.maxResolutionX, record.maxResolutionY, maxCapacity, remainingCapacity, maxCapacity);
gpuCapacity.put(record.modelName, vgpuTypeRecord);
}
@ -137,27 +136,27 @@ public class XenServer620SP1Resource extends XenServer620Resource {
}
@Override
protected void createVGPU(Connection conn, StartCommand cmd, VM vm, GPUDeviceTO gpuDevice) throws XenAPIException, XmlRpcException {
protected void createVGPU(final Connection conn, final StartCommand cmd, final VM vm, final GPUDeviceTO gpuDevice) throws XenAPIException, XmlRpcException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating VGPU of VGPU type [ " + gpuDevice.getVgpuType() + " ] in gpu group" + gpuDevice.getGpuGroup()
+ " for VM " + cmd.getVirtualMachine().getName());
}
Set<GPUGroup> groups = GPUGroup.getByNameLabel(conn, gpuDevice.getGpuGroup());
final Set<GPUGroup> groups = GPUGroup.getByNameLabel(conn, gpuDevice.getGpuGroup());
assert groups.size() == 1 : "Should only have 1 group but found " + groups.size();
GPUGroup gpuGroup = groups.iterator().next();
final GPUGroup gpuGroup = groups.iterator().next();
Set<VGPUType> vgpuTypes = gpuGroup.getEnabledVGPUTypes(conn);
Iterator<VGPUType> iter = vgpuTypes.iterator();
final Set<VGPUType> vgpuTypes = gpuGroup.getEnabledVGPUTypes(conn);
final Iterator<VGPUType> iter = vgpuTypes.iterator();
VGPUType vgpuType = null;
while (iter.hasNext()) {
VGPUType entry = iter.next();
final VGPUType entry = iter.next();
if (entry.getModelName(conn).equals(gpuDevice.getVgpuType())) {
vgpuType = entry;
}
}
String device = "0"; // Only allow device = "0" for now, as XenServer supports just a single vGPU per VM.
Map<String, String> other_config = new HashMap<String, String>();
final String device = "0"; // Only allow device = "0" for now, as XenServer supports just a single vGPU per VM.
final Map<String, String> other_config = new HashMap<String, String>();
VGPU.create(conn, vm, gpuGroup, device, other_config, vgpuType);
if (s_logger.isDebugEnabled()) {
@ -166,5 +165,4 @@ public class XenServer620SP1Resource extends XenServer620Resource {
// Calculate and set remaining GPU capacity in the host.
cmd.getVirtualMachine().getGpuDevice().setGroupDetails(getGPUGroupDetails(conn));
}
}
}

View File

@ -24,22 +24,20 @@ import java.util.List;
import javax.ejb.Local;
import org.apache.cloudstack.hypervisor.xenserver.XenServerResourceNewBase;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VM;
import org.apache.cloudstack.hypervisor.xenserver.XenServerResourceNewBase;
import com.cloud.resource.ServerResource;
import com.cloud.storage.resource.StorageSubsystemCommandHandler;
import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SSHCmdHelper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VM;
@Local(value=ServerResource.class)
public class Xenserver625Resource extends XenServerResourceNewBase {
@ -51,49 +49,48 @@ public class Xenserver625Resource extends XenServerResourceNewBase {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch";
final String patchfilePath = Script.findScript("", patch);
if (patchfilePath == null) {
throw new CloudRuntimeException("Unable to find patch file " + patch);
}
File file = new File(patchfilePath);
final File file = new File(patchfilePath);
files.add(file);
return files;
}
@Override
protected StorageSubsystemCommandHandler getStorageHandler() {
XenServerStorageProcessor processor = new Xenserver625StorageProcessor(this);
final XenServerStorageProcessor processor = new Xenserver625StorageProcessor(this);
return new StorageSubsystemCommandHandlerBase(processor);
}
@Override
protected void umountSnapshotDir(Connection conn, Long dcId) {
public void umountSnapshotDir(final Connection conn, final Long dcId) {
}
@Override
protected boolean setupServer(Connection conn,Host host) {
com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.ip, 22);
protected boolean setupServer(final Connection conn,final Host host) {
final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
try {
sshConnection.connect(null, 60000, 60000);
if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
throw new CloudRuntimeException("Unable to authenticate");
}
String cmd = "rm -f /opt/xensource/sm/hostvmstats.py " +
"/opt/xensource/bin/copy_vhd_to_secondarystorage.sh " +
"/opt/xensource/bin/copy_vhd_from_secondarystorage.sh " +
"/opt/xensource/bin/create_privatetemplate_from_snapshot.sh " +
"/opt/xensource/bin/vhd-util " +
"/opt/cloud/bin/copy_vhd_to_secondarystorage.sh " +
"/opt/cloud/bin/copy_vhd_from_secondarystorage.sh " +
"/opt/cloud/bin/create_privatetemplate_from_snapshot.sh " +
"/opt/cloud/bin/vhd-util";
final String cmd = "rm -f /opt/xensource/sm/hostvmstats.py " +
"/opt/xensource/bin/copy_vhd_to_secondarystorage.sh " +
"/opt/xensource/bin/copy_vhd_from_secondarystorage.sh " +
"/opt/xensource/bin/create_privatetemplate_from_snapshot.sh " +
"/opt/xensource/bin/vhd-util " +
"/opt/cloud/bin/copy_vhd_to_secondarystorage.sh " +
"/opt/cloud/bin/copy_vhd_from_secondarystorage.sh " +
"/opt/cloud/bin/create_privatetemplate_from_snapshot.sh " +
"/opt/cloud/bin/vhd-util";
SSHCmdHelper.sshExecuteCmd(sshConnection, cmd);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.debug("Catch exception " + e.toString(), e);
} finally {
sshConnection.close();
@ -102,11 +99,11 @@ public class Xenserver625Resource extends XenServerResourceNewBase {
}
@Override
protected String revertToSnapshot(Connection conn, VM vmSnapshot,
String vmName, String oldVmUuid, Boolean snapshotMemory, String hostUUID)
throws Types.XenAPIException, XmlRpcException {
protected String revertToSnapshot(final Connection conn, final VM vmSnapshot,
final String vmName, final String oldVmUuid, final Boolean snapshotMemory, final String hostUUID)
throws Types.XenAPIException, XmlRpcException {
String results = callHostPluginAsync(conn, "vmopsSnapshot",
final String results = callHostPluginAsync(conn, "vmopsSnapshot",
"revert_memory_snapshot", 10 * 60 * 1000, "snapshotUUID",
vmSnapshot.getUuid(conn), "vmName", vmName, "oldVmUuid",
oldVmUuid, "snapshotMemory", snapshotMemory.toString(), "hostUUID", hostUUID);

View File

@ -0,0 +1,212 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.xenserver.resource;
import com.xensource.xenapi.Network;
/**
* A list of UUIDs that are gathered from the XenServer when the resource first
* connects to XenServer. These UUIDs do not change over time.
*/
public class XsHost {
private String systemvmisouuid;
private String uuid;
private String ip;
private String publicNetwork;
private String privateNetwork;
private String linkLocalNetwork;
private Network vswitchNetwork;
private String storageNetwork1;
private String guestNetwork;
private String guestPif;
private String publicPif;
private String privatePif;
private String storagePif1;
private String storagePif2;
private String pool;
private int speed;
private Integer cpuSockets;
private int cpus;
private String productVersion;
private String localSRuuid;
public String getSystemvmisouuid() {
return systemvmisouuid;
}
public void setSystemvmisouuid(final String systemvmisouuid) {
this.systemvmisouuid = systemvmisouuid;
}
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getIp() {
return ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public String getPublicNetwork() {
return publicNetwork;
}
public void setPublicNetwork(final String publicNetwork) {
this.publicNetwork = publicNetwork;
}
public String getPrivateNetwork() {
return privateNetwork;
}
public void setPrivateNetwork(final String privateNetwork) {
this.privateNetwork = privateNetwork;
}
public String getLinkLocalNetwork() {
return linkLocalNetwork;
}
public void setLinkLocalNetwork(final String linkLocalNetwork) {
this.linkLocalNetwork = linkLocalNetwork;
}
public Network getVswitchNetwork() {
return vswitchNetwork;
}
public void setVswitchNetwork(final Network vswitchNetwork) {
this.vswitchNetwork = vswitchNetwork;
}
public String getStorageNetwork1() {
return storageNetwork1;
}
public void setStorageNetwork1(final String storageNetwork1) {
this.storageNetwork1 = storageNetwork1;
}
public String getGuestNetwork() {
return guestNetwork;
}
public void setGuestNetwork(final String guestNetwork) {
this.guestNetwork = guestNetwork;
}
public String getGuestPif() {
return guestPif;
}
public void setGuestPif(final String guestPif) {
this.guestPif = guestPif;
}
public String getPublicPif() {
return publicPif;
}
public void setPublicPif(final String publicPif) {
this.publicPif = publicPif;
}
public String getPrivatePif() {
return privatePif;
}
public void setPrivatePif(final String privatePif) {
this.privatePif = privatePif;
}
public String getStoragePif1() {
return storagePif1;
}
public void setStoragePif1(final String storagePif1) {
this.storagePif1 = storagePif1;
}
public String getStoragePif2() {
return storagePif2;
}
public void setStoragePif2(final String storagePif2) {
this.storagePif2 = storagePif2;
}
public String getPool() {
return pool;
}
public void setPool(final String pool) {
this.pool = pool;
}
public int getSpeed() {
return speed;
}
public void setSpeed(final int speed) {
this.speed = speed;
}
public Integer getCpuSockets() {
return cpuSockets;
}
public void setCpuSockets(final Integer cpuSockets) {
this.cpuSockets = cpuSockets;
}
public int getCpus() {
return cpus;
}
public void setCpus(final int cpus) {
this.cpus = cpus;
}
public String getProductVersion() {
return productVersion;
}
public void setProductVersion(final String productVersion) {
this.productVersion = productVersion;
}
public String getLocalSRuuid() {
return localSRuuid;
}
public void setLocalSRuuid(final String localSRuuid) {
this.localSRuuid = localSRuuid;
}
@Override
public String toString() {
return new StringBuilder("XS[").append(uuid).append("-").append(ip).append("]").toString();
}
}

View File

@ -0,0 +1,75 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.hypervisor.xenserver.resource.wrapper;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
public final class CitrixReadyCommandWrapper extends CommandWrapper<ReadyCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixReadyCommandWrapper.class);
@Override
public Answer execute(final ReadyCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final Long dcId = command.getDataCenterId();
// Ignore the result of the callHostPlugin. Even if unmounting the
// snapshots dir fails, let Ready command
// succeed.
citrixResourceBase.umountSnapshotDir(conn, dcId);
citrixResourceBase.setupLinkLocalNetwork(conn);
// try to destroy CD-ROM device for all system VMs on this host
try {
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
final Set<VM> vms = host.getResidentVMs(conn);
for (final VM vm : vms) {
citrixResourceBase.destroyPatchVbd(conn, vm.getNameLabel(conn));
}
} catch (final Exception e) {
}
try {
final boolean result = citrixResourceBase.cleanupHaltedVms(conn);
if (!result) {
return new ReadyAnswer(command, "Unable to cleanup halted vms");
}
} catch (final XenAPIException e) {
s_logger.warn("Unable to cleanup halted vms", e);
return new ReadyAnswer(command, "Unable to cleanup halted vms");
} catch (final XmlRpcException e) {
s_logger.warn("Unable to cleanup halted vms", e);
return new ReadyAnswer(command, "Unable to cleanup halted vms");
}
return new ReadyAnswer(command);
}
}

View File

@ -23,6 +23,7 @@ import java.util.Hashtable;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
@ -53,6 +54,7 @@ public class CitrixRequestWrapper extends RequestWrapper {
map.put(CreateCommand.class, new CitrixCreateCommandWrapper());
map.put(CheckConsoleProxyLoadCommand.class, new CitrixCheckConsoleProxyLoadCommandWrapper());
map.put(WatchConsoleProxyLoadCommand.class, new CitrixWatchConsoleProxyLoadCommandWrapper());
map.put(ReadyCommand.class, new CitrixReadyCommandWrapper());
}
public static CitrixRequestWrapper getInstance() {

View File

@ -25,6 +25,11 @@ import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.StartupCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer620SP1Resource;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Event;
import com.xensource.xenapi.EventBatch;
@ -35,12 +40,6 @@ import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.StartupCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer620SP1Resource;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine;
/**
*
* XenServerResourceNewBase is an abstract base class that encapsulates how
@ -67,16 +66,16 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
@Override
public StartupCommand[] initialize() throws IllegalArgumentException {
StartupCommand[] cmds = super.initialize();
final StartupCommand[] cmds = super.initialize();
Connection conn = getConnection();
final Connection conn = getConnection();
Pool pool;
try {
pool = Pool.getByUuid(conn, _host.pool);
Pool.Record poolr = pool.getRecord(conn);
pool = Pool.getByUuid(conn, _host.getPool());
final Pool.Record poolr = pool.getRecord(conn);
Host.Record masterRecord = poolr.master.getRecord(conn);
if (_host.uuid.equals(masterRecord.uuid)) {
final Host.Record masterRecord = poolr.master.getRecord(conn);
if (_host.getUuid().equals(masterRecord.uuid)) {
_listener = new VmEventListener(true);
//
@ -87,36 +86,37 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
} else {
_listener = new VmEventListener(false);
}
} catch (XenAPIException e) {
} catch (final XenAPIException e) {
throw new CloudRuntimeException("Unable to determine who is the master", e);
} catch (XmlRpcException e) {
} catch (final XmlRpcException e) {
throw new CloudRuntimeException("Unable to determine who is the master", e);
}
return cmds;
}
protected void waitForTask2(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException, TimeoutException {
long beginTime = System.currentTimeMillis();
protected void waitForTask2(final Connection c, final Task task, final long pollInterval, final long timeout) throws XenAPIException, XmlRpcException, TimeoutException {
final long beginTime = System.currentTimeMillis();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Task " + task.getNameLabel(c) + " (" + task.getType(c) + ") sent to " + c.getSessionReference() + " is pending completion with a " + timeout +
"ms timeout");
"ms timeout");
}
Set<String> classes = new HashSet<String>();
final Set<String> classes = new HashSet<String>();
classes.add("Task/" + task.toWireString());
String token = "";
Double t = new Double(timeout / 1000);
final Double t = new Double(timeout / 1000);
while (true) {
EventBatch map = Event.from(c, classes, token, t);
final EventBatch map = Event.from(c, classes, token, t);
token = map.token;
@SuppressWarnings("unchecked")
final
Set<Event.Record> events = map.events;
if (events.size() == 0) {
String msg = "No event for task " + task.toWireString();
final String msg = "No event for task " + task.toWireString();
s_logger.warn(msg);
task.cancel(c);
throw new TimeoutException(msg);
}
for (Event.Record rec : events) {
for (final Event.Record rec : events) {
if (!(rec.snapshot instanceof Task.Record)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Skipping over " + rec);
@ -124,7 +124,7 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
continue;
}
Task.Record taskRecord = (Task.Record)rec.snapshot;
final Task.Record taskRecord = (Task.Record)rec.snapshot;
if (taskRecord.status != Types.TaskStatusType.PENDING) {
if (s_logger.isDebugEnabled()) {
@ -139,7 +139,7 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
}
}
if (System.currentTimeMillis() - beginTime > timeout) {
String msg = "Async " + timeout / 1000 + " seconds timeout for task " + task.toString();
final String msg = "Async " + timeout / 1000 + " seconds timeout for task " + task.toString();
s_logger.warn(msg);
task.cancel(c);
throw new TimeoutException(msg);
@ -155,7 +155,7 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
Set<String> _classes;
String _token = "";
public VmEventListener(boolean isMaster) {
public VmEventListener(final boolean isMaster) {
_isMaster = isMaster;
_classes = new HashSet<String>();
_classes.add("VM");
@ -163,22 +163,23 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
@Override
public void run() {
setName("XS-Listener-" + _host.ip);
setName("XS-Listener-" + _host.getIp());
while (!_stop) {
try {
Connection conn = getConnection();
final Connection conn = getConnection();
EventBatch results;
try {
results = Event.from(conn, _classes, _token, new Double(30));
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Retrying the waiting on VM events due to: ", e);
continue;
}
_token = results.token;
@SuppressWarnings("unchecked")
final
Set<Event.Record> events = results.events;
for (Event.Record event : events) {
for (final Event.Record event : events) {
try {
if (!(event.snapshot instanceof VM.Record)) {
if (s_logger.isDebugEnabled()) {
@ -186,24 +187,24 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
}
continue;
}
VM.Record vm = (VM.Record)event.snapshot;
final VM.Record vm = (VM.Record)event.snapshot;
String hostUuid = null;
if (vm.residentOn != null && !vm.residentOn.toWireString().contains("OpaqueRef:NULL")) {
hostUuid = vm.residentOn.getUuid(conn);
}
recordChanges(conn, vm, hostUuid);
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Skipping over " + event, e);
}
}
} catch (Throwable th) {
} catch (final Throwable th) {
s_logger.error("Exception caught in eventlistener thread: ", th);
}
}
}
protected void recordChanges(Connection conn, VM.Record rec, String hostUuid) {
protected void recordChanges(final Connection conn, final VM.Record rec, final String hostUuid) {
}
@ -211,16 +212,16 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
public void start() {
if (_isMaster) {
// Throw away the initial set of events because they're history
Connection conn = getConnection();
final Connection conn = getConnection();
EventBatch results;
try {
results = Event.from(conn, _classes, _token, new Double(30));
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Retrying the waiting on VM events due to: ", e);
throw new CloudRuntimeException("Unable to start a listener thread to listen to VM events", e);
}
_token = results.token;
s_logger.debug("Starting the event listener thread for " + _host.uuid);
s_logger.debug("Starting the event listener thread for " + _host.getUuid());
super.start();
}
}
@ -234,7 +235,7 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
if (_changes.size() == 0) {
return null;
}
HashMap<String, Pair<String, VirtualMachine.State>> diff = _changes;
final HashMap<String, Pair<String, VirtualMachine.State>> diff = _changes;
_changes = new HashMap<String, Pair<String, VirtualMachine.State>>();
return diff;
}

View File

@ -39,6 +39,10 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import com.cloud.agent.api.ScaleVmAnswer;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
@ -46,35 +50,29 @@ import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
import com.xensource.xenapi.XenAPIObject;
import com.cloud.agent.api.ScaleVmAnswer;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.XsHost;
public class CitrixResourceBaseTest {
@Spy
CitrixResourceBase _resource = new CitrixResourceBase() {
@Override
public ScaleVmAnswer execute(ScaleVmCommand cmd) {
public ScaleVmAnswer execute(final ScaleVmCommand cmd) {
return super.execute(cmd);
}
@Override
public String callHostPlugin(Connection conn, String plugin, String cmd, String... params) {
public String callHostPlugin(final Connection conn, final String plugin, final String cmd, final String... params) {
return "Success";
}
@Override
protected void scaleVM(Connection conn, VM vm, VirtualMachineTO vmSpec, Host host) throws Types.XenAPIException, XmlRpcException {
_host.speed = 500;
protected void scaleVM(final Connection conn, final VM vm, final VirtualMachineTO vmSpec, final Host host) throws Types.XenAPIException, XmlRpcException {
_host.setSpeed(500);
super.scaleVM(conn, vm, vmSpec, host);
}
@Override
protected boolean isDmcEnabled(Connection conn, Host host) throws Types.XenAPIException, XmlRpcException {
protected boolean isDmcEnabled(final Connection conn, final Host host) throws Types.XenAPIException, XmlRpcException {
return true;
}
};
@ -105,18 +103,18 @@ public class CitrixResourceBaseTest {
@Test(expected = XmlRpcException.class)
public void testScaleVMF1() throws Types.BadServerResponse, Types.XenAPIException, XmlRpcException {
doReturn(conn).when(_resource).getConnection();
Set<VM> vms = mock(Set.class);
final Set<VM> vms = mock(Set.class);
Iterator iter = mock(Iterator.class);
final Iterator iter = mock(Iterator.class);
doReturn(iter).when(vms).iterator();
when(iter.hasNext()).thenReturn(true).thenReturn(false);
doReturn(vm).when(iter).next();
VM.Record vmr = mock(VM.Record.class);
final VM.Record vmr = mock(VM.Record.class);
when(vm.getRecord(conn)).thenThrow(new XmlRpcException("XmlRpcException"));
when(vm.getRecord(conn)).thenReturn(vmr);
vmr.powerState = Types.VmPowerState.RUNNING;
vmr.residentOn = mock(Host.class);
XenAPIObject object = mock(XenAPIObject.class);
final XenAPIObject object = mock(XenAPIObject.class);
doReturn(new String("OpaqueRef:NULL")).when(object).toWireString();
doNothing().when(_resource).scaleVM(conn, vm, vmSpec, host);
@ -139,7 +137,7 @@ public class CitrixResourceBaseTest {
doNothing().when(vm).setVCPUsNumberLive(conn, 1L);
doReturn(500).when(vmSpec).getMinSpeed();
doReturn(false).when(vmSpec).getLimitCpuUse();
Map<String, String> args = mock(HashMap.class);
final Map<String, String> args = mock(HashMap.class);
when(host.callPlugin(conn, "vmops", "add_to_VCPUs_params_live", args)).thenReturn("Success");
doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
@ -164,7 +162,7 @@ public class CitrixResourceBaseTest {
doReturn(500).when(vmSpec).getMaxSpeed();
doReturn(true).when(vmSpec).getLimitCpuUse();
doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", "99", "vmname", "i-2-3-VM");
Map<String, String> args = mock(HashMap.class);
final Map<String, String> args = mock(HashMap.class);
when(host.callPlugin(conn, "vmops", "add_to_VCPUs_params_live", args)).thenReturn("Success");
doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
@ -178,12 +176,12 @@ public class CitrixResourceBaseTest {
@Test
public void testSetNicDevIdIfCorrectVifIsNotNull() throws Exception {
IpAddressTO ip = mock(IpAddressTO.class);
final IpAddressTO ip = mock(IpAddressTO.class);
when(ip.isAdd()).thenReturn(false);
VIF correctVif = null;
final VIF correctVif = null;
try {
_resource.setNicDevIdIfCorrectVifIsNotNull(conn, ip, correctVif);
} catch (NullPointerException e) {
} catch (final NullPointerException e) {
fail("this test is meant to show that null pointer is not thrown");
}
}

View File

@ -14,6 +14,7 @@ import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
@ -96,4 +97,16 @@ public class CitrixRequestWrapperTest {
assertFalse(answer.getResult());
}
@Test
public void testReadyCommandCommand() {
final ReadyCommand readyCommand = new ReadyCommand();
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(readyCommand, citrixResourceBase);
assertFalse(answer.getResult());
}
}