diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixHelper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixHelper.java index 5bc80363e17..265573d7e4a 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixHelper.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixHelper.java @@ -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 XenServerGuestOsMemoryMap = new HashMap(70); - private static final ArrayList GuestOsList = new ArrayList(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) { diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java index b2847681292..850cbb39aa9 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java @@ -349,8 +349,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return true; } - protected boolean cleanupHaltedVms(final Connection conn) throws XenAPIException, XmlRpcException { - final Host host = Host.getByUuid(conn, _host.uuid); + public boolean cleanupHaltedVms(final Connection conn) throws XenAPIException, XmlRpcException { + final Host host = Host.getByUuid(conn, _host.getUuid()); final Map vms = VM.getAllRecords(conn); boolean success = true; if(vms != null && !vms.isEmpty()) { @@ -397,19 +397,19 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected boolean pingXAPI() { final Connection conn = getConnection(); try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); if( !host.getEnabled(conn) ) { - s_logger.debug("Host " + _host.ip + " is not enabled!"); + s_logger.debug("Host " + _host.getIp() + " is not enabled!"); return false; } } catch (final Exception e) { - s_logger.debug("cannot get host enabled status, host " + _host.ip + " due to " + e.toString(), e); + s_logger.debug("cannot get host enabled status, host " + _host.getIp() + " due to " + e.toString(), e); return false; } try { callHostPlugin(conn, "echo", "main"); } catch (final Exception e) { - s_logger.debug("cannot ping host " + _host.ip + " due to " + e.toString(), e); + s_logger.debug("cannot ping host " + _host.getIp() + " due to " + e.toString(), e); return false; } return true; @@ -417,7 +417,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected String logX(final XenAPIObject obj, final String msg) { - return new StringBuilder("Host ").append(_host.ip).append(" ").append(obj.toWireString()).append(": ").append(msg).toString(); + return new StringBuilder("Host ").append(_host.getIp()).append(" ").append(obj.toWireString()).append(": ").append(msg).toString(); } @Override @@ -554,7 +554,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cmdline = cmdline.replaceAll(";", "\\\\;"); try { s_logger.debug("Executing command in VR: " + cmdline); - result = SshHelper.sshExecute(_host.ip, 22, _username, null, _password.peek(), cmdline, + result = SshHelper.sshExecute(_host.getIp(), 22, _username, null, _password.peek(), cmdline, 60000, 60000, timeout * 1000); } catch (final Exception e) { return new ExecutionResult(false, e.getMessage()); @@ -573,11 +573,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final Connection conn = getConnection(); final String hostPath = "/tmp/"; - s_logger.debug("Copying VR with ip " + routerIp +" config file into host "+ _host.ip ); + s_logger.debug("Copying VR with ip " + routerIp +" config file into host "+ _host.getIp() ); try { - SshHelper.scpTo(_host.ip, 22, _username, null, _password.peek(), hostPath, content.getBytes(Charset.defaultCharset()), filename, null); + SshHelper.scpTo(_host.getIp(), 22, _username, null, _password.peek(), hostPath, content.getBytes(Charset.defaultCharset()), filename, null); } catch (final Exception e) { - s_logger.warn("scp VR config file into host " + _host.ip + " failed with exception " + e.getMessage().toString()); + s_logger.warn("scp VR config file into host " + _host.getIp() + " failed with exception " + e.getMessage().toString()); } final String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "srcfilepath", hostPath + filename, "dstfilepath", path); @@ -652,7 +652,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args)); } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); task = host.callPluginAsync(conn, plugin, cmd, args); // poll every 1 seconds waitForTask(conn, task, 1000, timeout); @@ -678,7 +678,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -706,14 +706,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe // weight based allocation - cpuWeight = (int)(speed * 0.99 / _host.speed * _maxWeight); + cpuWeight = (int)(speed * 0.99 / _host.getSpeed() * _maxWeight); if (cpuWeight > _maxWeight) { cpuWeight = _maxWeight; } if (vmSpec.getLimitCpuUse()) { long utilization = 0; // max CPU cap, default is unlimited - utilization = (int)(vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus() / _host.speed * 100); + utilization = (int)(vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus() / _host.getSpeed() * 100); //vm.addToVCPUsParamsLive(conn, "cap", Long.toString(utilization)); currently xenserver doesnot support Xapi to add VCPUs params live. callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", Long.toString(utilization), "vmname", vmSpec.getName()); } @@ -728,11 +728,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { final Connection conn = getConnection(); final Set vms = VM.getByNameLabel(conn, vmName); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); // If DMC is not enable then don't execute this command. if (!isDmcEnabled(conn, host)) { - throw new CloudRuntimeException("Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:" + _host.uuid + + throw new CloudRuntimeException("Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:" + _host.getUuid() + " ,check your license and hypervisor version."); } @@ -743,13 +743,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final VM.Record vmr = vm.getRecord(conn); if (vmr.powerState == VmPowerState.HALTED || - vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) { + vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.getUuid())) { iter.remove(); } } if (vms.size() == 0) { - s_logger.info("No running VM " + vmName + " exists on XenServer" + _host.uuid); + s_logger.info("No running VM " + vmName + " exists on XenServer" + _host.getUuid()); return new ScaleVmAnswer(cmd, false, "VM does not exist"); } @@ -812,7 +812,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } // call plugin to execute revert - revertToSnapshot(conn, vmSnapshot, vmName, vm.getUuid(conn), snapshotMemory, _host.uuid); + revertToSnapshot(conn, vmSnapshot, vmName, vm.getUuid(conn), snapshotMemory, _host.getUuid()); vm = getVM(conn, vmName); final Set vbds = vm.getVBDs(conn); final Map vdiMap = new HashMap(); @@ -875,17 +875,17 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (type == TrafficType.Guest) { - return new XsLocalNetwork(Network.getByUuid(conn, _host.guestNetwork), null, PIF.getByUuid(conn, _host.guestPif), null); + return new XsLocalNetwork(Network.getByUuid(conn, _host.getGuestNetwork()), null, PIF.getByUuid(conn, _host.getGuestPif()), null); } else if (type == TrafficType.Control) { setupLinkLocalNetwork(conn); - return new XsLocalNetwork(Network.getByUuid(conn, _host.linkLocalNetwork)); + return new XsLocalNetwork(Network.getByUuid(conn, _host.getLinkLocalNetwork())); } else if (type == TrafficType.Management) { - return new XsLocalNetwork(Network.getByUuid(conn, _host.privateNetwork), null, PIF.getByUuid(conn, _host.privatePif), null); + return new XsLocalNetwork(Network.getByUuid(conn, _host.getPrivateNetwork()), null, PIF.getByUuid(conn, _host.getPrivatePif()), null); } else if (type == TrafficType.Public) { - return new XsLocalNetwork(Network.getByUuid(conn, _host.publicNetwork), null, PIF.getByUuid(conn, _host.publicPif), null); + return new XsLocalNetwork(Network.getByUuid(conn, _host.getPublicNetwork()), null, PIF.getByUuid(conn, _host.getPublicPif()), null); } else if (type == TrafficType.Storage) { /* TrafficType.Storage is for secondary storage, while storageNetwork1 is for primary storage, we need better name here */ - return new XsLocalNetwork(Network.getByUuid(conn, _host.storageNetwork1), null, PIF.getByUuid(conn, _host.storagePif1), null); + return new XsLocalNetwork(Network.getByUuid(conn, _host.getStorageNetwork1()), null, PIF.getByUuid(conn, _host.getStoragePif1()), null); } throw new CloudRuntimeException("Unsupported network type: " + type); @@ -893,7 +893,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe private synchronized Network setupvSwitchNetwork(final Connection conn) { try { - if (_host.vswitchNetwork == null) { + if (_host.getVswitchNetwork() == null) { Network vswitchNw = null; final Network.Record rec = new Network.Record(); final String nwName = Networks.BroadcastScheme.VSwitch.toString(); @@ -906,9 +906,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } else { vswitchNw = networks.iterator().next(); } - _host.vswitchNetwork = vswitchNw; + _host.setVswitchNetwork(vswitchNw); } - return _host.vswitchNetwork; + return _host.getVswitchNetwork(); } catch (final BadServerResponse e) { s_logger.error("Failed to setup vswitch network", e); } catch (final XenAPIException e) { @@ -1152,12 +1152,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } for (final PBD pbd : pbds) { final PBD.Record pbdr = pbd.getRecord(conn); - if (pbdr.host.getUuid(conn).equals(_host.uuid)) { + if (pbdr.host.getUuid(conn).equals(_host.getUuid())) { return; } } sr.setShared(conn, true); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final PBD.Record pbdr = pbds.iterator().next().getRecord(conn); pbdr.host = host; pbdr.uuid = ""; @@ -1383,14 +1383,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe int utilization = 0; // max CPU cap, default is unlimited // weight based allocation, CPU weight is calculated per VCPU - cpuWeight = (int)(speed * 0.99 / _host.speed * _maxWeight); + cpuWeight = (int)(speed * 0.99 / _host.getSpeed() * _maxWeight); if (cpuWeight > _maxWeight) { cpuWeight = _maxWeight; } if (vmSpec.getLimitCpuUse()) { // CPU cap is per VM, so need to assign cap based on the number of vcpus - utilization = (int)(vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus() / _host.speed * 100); + utilization = (int)(vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus() / _host.getSpeed() * 100); } vcpuParams.put("weight", Integer.toString(cpuWeight)); @@ -1549,7 +1549,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected VBD createPatchVbd(final Connection conn, final String vmName, final VM vm) throws XmlRpcException, XenAPIException { - if (_host.systemvmisouuid == null) { + if (_host.getSystemvmisouuid() == null) { final Set srs = SR.getByNameLabel(conn, "XenServer Tools"); if (srs.size() != 1) { throw new CloudRuntimeException("There are " + srs.size() + " SRs with name XenServer Tools"); @@ -1559,16 +1559,16 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final SR.Record srr = sr.getRecord(conn); - if (_host.systemvmisouuid == null) { + if (_host.getSystemvmisouuid() == null) { for (final VDI vdi : srr.VDIs) { final VDI.Record vdir = vdi.getRecord(conn); if (vdir.nameLabel.contains("systemvm.iso")) { - _host.systemvmisouuid = vdir.uuid; + _host.setSystemvmisouuid(vdir.uuid); break; } } } - if (_host.systemvmisouuid == null) { + if (_host.getSystemvmisouuid() == null) { throw new CloudRuntimeException("can not find systemvmiso"); } } @@ -1581,12 +1581,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; final VBD cdromVBD = VBD.create(conn, cdromVBDR); - cdromVBD.insert(conn, VDI.getByUuid(conn, _host.systemvmisouuid)); + cdromVBD.insert(conn, VDI.getByUuid(conn, _host.getSystemvmisouuid())); return cdromVBD; } - protected void destroyPatchVbd(final Connection conn, final String vmName) throws XmlRpcException, XenAPIException { + public void destroyPatchVbd(final Connection conn, final String vmName) throws XmlRpcException, XenAPIException { try { if (!vmName.startsWith("r-") && !vmName.startsWith("s-") && !vmName.startsWith("v-")) { return; @@ -1763,7 +1763,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } s_logger.debug("1. The VM " + vmName + " is in Starting state."); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); vm = createVmFromTemplate(conn, vmSpec, host); final GPUDeviceTO gpuDevice = vmSpec.getGpuDevice(); @@ -1972,7 +1972,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } private boolean doPingTest(final Connection conn, final String computingHostIp) { - 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())) { @@ -1981,7 +1981,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final String cmd = "ping -c 2 " + computingHostIp; if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) { - throw new CloudRuntimeException("Cannot ping host " + computingHostIp + " from host " + _host.ip); + throw new CloudRuntimeException("Cannot ping host " + computingHostIp + " from host " + _host.getIp()); } return true; } catch (final Exception e) { @@ -2026,7 +2026,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final Connection conn = getConnection(); try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); // remove all tags cloud stack final Host.Record hr = host.getRecord(conn); final Iterator it = hr.tags.iterator(); @@ -2441,7 +2441,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected Document getStatsRawXML(final Connection conn, final boolean host) { final Date currentDate = new Date(); - String urlStr = "http://" + _host.ip + "/rrd_updates?"; + String urlStr = "http://" + _host.getIp() + "/rrd_updates?"; urlStr += "session_id=" + conn.getSessionReference(); urlStr += "&host=" + (host ? "true" : "false"); urlStr += "&cf=" + _consolidationFunction; @@ -2605,7 +2605,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.error("Failed to get host uuid for host " + host.toWireString(), e); } - if (host_uuid.equalsIgnoreCase(_host.uuid)) { + if (host_uuid.equalsIgnoreCase(_host.getUuid())) { vmStates.put( record.nameLabel, new HostVmStateReportEntry(convertToPowerState(ps), host_uuid) @@ -2832,7 +2832,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } return new PrimaryStorageDownloadAnswer(snapshotvdi.getUuid(conn), phySize); } catch (final Exception e) { - final String msg = "Catch Exception " + e.getClass().getName() + " on host:" + _host.uuid + " for template: " + tmplturl + " due to " + e.toString(); + final String msg = "Catch Exception " + e.getClass().getName() + " on host:" + _host.getUuid() + " for template: " + tmplturl + " due to " + e.toString(); s_logger.warn(msg, e); return new PrimaryStorageDownloadAnswer(msg); } @@ -2957,7 +2957,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } if (dsthost == null) { - final String msg = "Migration failed due to unable to find host " + ipaddr + " in XenServer pool " + _host.pool; + final String msg = "Migration failed due to unable to find host " + ipaddr + " in XenServer pool " + _host.getPool(); s_logger.warn(msg); return new MigrateAnswer(cmd, false, msg, null); } @@ -2982,7 +2982,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected Pair getControlDomain(final Connection conn) throws XenAPIException, XmlRpcException { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); Set vms = null; vms = host.getResidentVMs(conn); for (final VM vm : vms) { @@ -2994,7 +2994,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Com'on no control domain? What the crap?!#@!##$@"); } - protected void umountSnapshotDir(final Connection conn, final Long dcId) { + public void umountSnapshotDir(final Connection conn, final Long dcId) { try { callHostPlugin(conn, "vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); } catch (final Exception e) { @@ -3013,7 +3013,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe setupLinkLocalNetwork(conn); // try to destroy CD-ROM device for all system VMs on this host try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Set vms = host.getResidentVMs(conn); for (final VM vm : vms) { destroyPatchVbd(conn, vm.getNameLabel(conn)); @@ -3240,11 +3240,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Reboot VM catch HandleInvalid and VM is not in RUNNING state"); } } catch (final XenAPIException e) { - s_logger.debug("Unable to Clean Reboot VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString() + ", try hard reboot"); + s_logger.debug("Unable to Clean Reboot VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString() + ", try hard reboot"); try { vm.hardReboot(conn); } catch (final Exception e1) { - final String msg = "Unable to hard Reboot VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString(); + final String msg = "Unable to hard Reboot VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString(); s_logger.warn(msg, e1); throw new CloudRuntimeException(msg); } @@ -3253,7 +3253,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -3288,14 +3288,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Shutdown VM catch HandleInvalid and VM is not in HALTED state"); } } catch (final XenAPIException e) { - s_logger.debug("Unable to cleanShutdown VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString()); + s_logger.debug("Unable to cleanShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString()); try { VmPowerState state = vm.getPowerState(conn); if (state == VmPowerState.RUNNING) { try { vm.hardShutdown(conn); } catch (final Exception e1) { - s_logger.debug("Unable to hardShutdown VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString()); + s_logger.debug("Unable to hardShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString()); state = vm.getPowerState(conn); if (state == VmPowerState.RUNNING) { forceShutdownVM(conn, vm); @@ -3310,7 +3310,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException(msg); } } catch (final Exception e1) { - final String msg = "Unable to hardShutdown VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString(); + final String msg = "Unable to hardShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString(); s_logger.warn(msg, e1); throw new CloudRuntimeException(msg); } @@ -3319,7 +3319,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -3349,7 +3349,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Start VM " + vmName + " catch BadAsyncResult and VM is not in RUNNING state"); } } catch (final XenAPIException e) { - final String msg = "Unable to start VM(" + vmName + ") on host(" + _host.uuid + ") due to " + e.toString(); + final String msg = "Unable to start VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg); } finally { @@ -3357,7 +3357,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -3382,7 +3382,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("migrate VM catch HandleInvalid and VM is not running on dest host"); } } catch (final XenAPIException e) { - final String msg = "Unable to migrate VM(" + vmName + ") from host(" + _host.uuid + ")"; + final String msg = "Unable to migrate VM(" + vmName + ") from host(" + _host.getUuid() + ")"; s_logger.warn(msg, e); throw new CloudRuntimeException(msg); } finally { @@ -3390,7 +3390,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -3413,7 +3413,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e.toString()); } } } @@ -3430,7 +3430,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args)); } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); task = host.callPluginAsync(conn, plugin, cmd, args); // poll every 1 seconds waitForTask(conn, task, 1000, timeout); @@ -3452,7 +3452,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { task.destroy(conn); } catch (final Exception e1) { - s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.uuid + ") due to " + e1.toString()); + s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString()); } } } @@ -3477,7 +3477,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (isRefNull(vmr.residentOn)) { continue; } - if (vmr.residentOn.getUuid(conn).equals(_host.uuid)) { + if (vmr.residentOn.getUuid(conn).equals(_host.getUuid())) { continue; } iter.remove(); @@ -3495,8 +3495,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new StopAnswer(cmd, msg, false); } - if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) { - final String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn); + if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.getUuid())) { + final String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.getUuid() + " but host:" + vmr.residentOn.getUuid(conn); s_logger.warn(msg); return new StopAnswer(cmd, msg, platformstring, false); } @@ -3683,7 +3683,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args)); } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final String result = host.callPlugin(conn, plugin, cmd, args); if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin Result: " + result); @@ -3718,14 +3718,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected XsLocalNetwork getManagementNetwork(final Connection conn) throws XmlRpcException, XenAPIException { PIF mgmtPif = null; PIF.Record mgmtPifRec = null; - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Set hostPifs = host.getPIFs(conn); for (final PIF pif : hostPifs) { final PIF.Record rec = pif.getRecord(conn); if (rec.management) { if (rec.VLAN != null && rec.VLAN != -1) { final String msg = - new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) + new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.getUuid()) .append("; pif=") .append(rec.uuid) .append("; vlan=") @@ -3743,14 +3743,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } if (mgmtPif == null) { - final String msg = "Unable to find management network for " + _host.uuid; + final String msg = "Unable to find management network for " + _host.getUuid(); s_logger.warn(msg); throw new CloudRuntimeException(msg); } final Bond bond = mgmtPifRec.bondSlaveOf; if (!isRefNull(bond)) { final String msg = - "Management interface is on slave(" + mgmtPifRec.uuid + ") of bond(" + bond.getUuid(conn) + ") on host(" + _host.uuid + + "Management interface is on slave(" + mgmtPifRec.uuid + ") of bond(" + bond.getUuid(conn) + ") on host(" + _host.getUuid() + "), please move management interface to bond!"; s_logger.warn(msg); throw new CloudRuntimeException(msg); @@ -4020,7 +4020,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (vlanNic == null) { // Can't find it, then create it. if (s_logger.isDebugEnabled()) { - s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.ip); + s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.getIp()); } final Network.Record nwr = new Network.Record(); nwr.nameLabel = newName; @@ -4042,7 +4042,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (s_logger.isDebugEnabled()) { - s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip + " on device " + nPifr.device); + s_logger.debug("Creating VLAN " + tag + " on host " + _host.getIp() + " on device " + nPifr.device); } final VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork); if (vlan != null) { @@ -4072,7 +4072,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } for (final PBD pbd : pbds) { final Host host = pbd.getHost(conn); - if (!isRefNull(host) && host.getUuid(conn).equals(_host.uuid)) { + if (!isRefNull(host) && host.getUuid(conn).equals(_host.getUuid())) { if (!pbd.getCurrentlyAttached(conn)) { pbd.plug(conn); } @@ -4085,10 +4085,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } } catch (final XenAPIException e) { - final String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.toString(); + final String msg = "Unable to get local LVMSR in host:" + _host.getUuid() + e.toString(); s_logger.warn(msg); } catch (final XmlRpcException e) { - final String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.getCause(); + final String msg = "Unable to get local LVMSR in host:" + _host.getUuid() + e.getCause(); s_logger.warn(msg); } return null; @@ -4107,7 +4107,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } for (final PBD pbd : pbds) { final Host host = pbd.getHost(conn); - if (!isRefNull(host) && host.getUuid(conn).equals(_host.uuid)) { + if (!isRefNull(host) && host.getUuid(conn).equals(_host.getUuid())) { if (!pbd.getCurrentlyAttached(conn)) { pbd.plug(conn); } @@ -4120,10 +4120,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } } catch (final XenAPIException e) { - final String msg = "Unable to get local EXTSR in host:" + _host.uuid + e.toString(); + final String msg = "Unable to get local EXTSR in host:" + _host.getUuid() + e.toString(); s_logger.warn(msg); } catch (final XmlRpcException e) { - final String msg = "Unable to get local EXTSR in host:" + _host.uuid + e.getCause(); + final String msg = "Unable to get local EXTSR in host:" + _host.getUuid() + e.getCause(); s_logger.warn(msg); } return null; @@ -4133,30 +4133,30 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final SR lvmsr = getLocalLVMSR(conn); if (lvmsr != null) { try { - _host.localSRuuid = lvmsr.getUuid(conn); + _host.setLocalSRuuid(lvmsr.getUuid(conn)); final String lvmuuid = lvmsr.getUuid(conn); final long cap = lvmsr.getPhysicalSize(conn); if (cap > 0) { final long avail = cap - lvmsr.getPhysicalUtilisation(conn); lvmsr.setNameLabel(conn, lvmuuid); - final String name = "Cloud Stack Local LVM Storage Pool for " + _host.uuid; + final String name = "Cloud Stack Local LVM Storage Pool for " + _host.getUuid(); lvmsr.setNameDescription(conn, name); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final String address = host.getAddress(conn); final StoragePoolInfo pInfo = new StoragePoolInfo(lvmuuid, address, SRType.LVM.toString(), SRType.LVM.toString(), StoragePoolType.LVM, 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 (final XenAPIException e) { - final String msg = "build local LVM info err in host:" + _host.uuid + e.toString(); + final String msg = "build local LVM info err in host:" + _host.getUuid() + e.toString(); s_logger.warn(msg); } catch (final XmlRpcException e) { - final String msg = "build local LVM info err in host:" + _host.uuid + e.getMessage(); + final String msg = "build local LVM info err in host:" + _host.getUuid() + e.getMessage(); s_logger.warn(msg); } } @@ -4165,28 +4165,28 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (extsr != null) { try { final String extuuid = extsr.getUuid(conn); - _host.localSRuuid = extuuid; + _host.setLocalSRuuid(extuuid); final long cap = extsr.getPhysicalSize(conn); if (cap > 0) { final long avail = cap - extsr.getPhysicalUtilisation(conn); extsr.setNameLabel(conn, extuuid); - final String name = "Cloud Stack Local EXT Storage Pool for " + _host.uuid; + final String name = "Cloud Stack Local EXT Storage Pool for " + _host.getUuid(); extsr.setNameDescription(conn, name); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final String address = host.getAddress(conn); final StoragePoolInfo pInfo = new StoragePoolInfo(extuuid, address, SRType.EXT.toString(), SRType.EXT.toString(), 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 (final XenAPIException e) { - final String msg = "build local EXT info err in host:" + _host.uuid + e.toString(); + final String msg = "build local EXT info err in host:" + _host.getUuid() + e.toString(); s_logger.warn(msg); } catch (final XmlRpcException e) { - final String msg = "build local EXT info err in host:" + _host.uuid + e.getMessage(); + final String msg = "build local EXT info err in host:" + _host.getUuid() + e.getMessage(); s_logger.warn(msg); } } @@ -4199,7 +4199,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (!pingXAPI()) { Thread.sleep(1000); if (!pingXAPI()) { - s_logger.warn("can not ping xenserver " + _host.uuid); + s_logger.warn("can not ping xenserver " + _host.getUuid()); return null; } } @@ -4222,7 +4222,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe private HashMap> syncNetworkGroups(final Connection conn, final long id) { final HashMap> states = new HashMap>(); - final String result = callHostPlugin(conn, "vmops", "get_rule_logs_for_vms", "host_uuid", _host.uuid); + final String result = callHostPlugin(conn, "vmops", "get_rule_logs_for_vms", "host_uuid", _host.getUuid()); s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); final String[] rulelogs = result != null ? result.split(";") : new String[0]; for (final String rulesforvm : rulelogs) { @@ -4247,98 +4247,98 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected boolean getHostInfo(final Connection conn) throws IllegalArgumentException { try { - final Host myself = Host.getByUuid(conn, _host.uuid); + final Host myself = Host.getByUuid(conn, _host.getUuid()); Set hcs = null; for (int i = 0; i < 10; i++) { hcs = myself.getHostCPUs(conn); if(hcs != null) { - _host.cpus = hcs.size(); - if (_host.cpus > 0) { + _host.setCpus(hcs.size()); + if (_host.getCpus() > 0) { break; } } Thread.sleep(5000); } - if (_host.cpus <= 0) { - throw new CloudRuntimeException("Cannot get the numbers of cpu from XenServer host " + _host.ip); + if (_host.getCpus() <= 0) { + throw new CloudRuntimeException("Cannot get the numbers of cpu from XenServer host " + _host.getIp()); } final Map cpuInfo = myself.getCpuInfo(conn); if (cpuInfo.get("socket_count") != null) { - _host.cpuSockets = Integer.parseInt(cpuInfo.get("socket_count")); + _host.setCpuSockets(Integer.parseInt(cpuInfo.get("socket_count"))); } - // would hcs be null we would have thrown an exception on condition (_host.cpus <= 0) by now + // would hcs be null we would have thrown an exception on condition (_host.getCpus() <= 0) by now for (final HostCpu hc : hcs) { - _host.speed = hc.getSpeed(conn).intValue(); + _host.setSpeed(hc.getSpeed(conn).intValue()); break; } final Host.Record hr = myself.getRecord(conn); - _host.productVersion = CitrixHelper.getProductVersion(hr); + _host.setProductVersion(CitrixHelper.getProductVersion(hr)); final XsLocalNetwork privateNic = getManagementNetwork(conn); _privateNetworkName = privateNic.getNetworkRecord(conn).nameLabel; - _host.privatePif = privateNic.getPifRecord(conn).uuid; - _host.privateNetwork = privateNic.getNetworkRecord(conn).uuid; - _host.systemvmisouuid = null; + _host.setPrivatePif(privateNic.getPifRecord(conn).uuid); + _host.setPrivateNetwork(privateNic.getNetworkRecord(conn).uuid); + _host.setSystemvmisouuid(null); XsLocalNetwork guestNic = null; if (_guestNetworkName != null && !_guestNetworkName.equals(_privateNetworkName)) { guestNic = getNetworkByName(conn, _guestNetworkName); if (guestNic == null) { s_logger.warn("Unable to find guest network " + _guestNetworkName); - throw new IllegalArgumentException("Unable to find guest network " + _guestNetworkName + " for host " + _host.ip); + throw new IllegalArgumentException("Unable to find guest network " + _guestNetworkName + " for host " + _host.getIp()); } } else { guestNic = privateNic; _guestNetworkName = _privateNetworkName; } - _host.guestNetwork = guestNic.getNetworkRecord(conn).uuid; - _host.guestPif = guestNic.getPifRecord(conn).uuid; + _host.setGuestNetwork(guestNic.getNetworkRecord(conn).uuid); + _host.setGuestPif(guestNic.getPifRecord(conn).uuid); XsLocalNetwork publicNic = null; if (_publicNetworkName != null && !_publicNetworkName.equals(_guestNetworkName)) { publicNic = getNetworkByName(conn, _publicNetworkName); if (publicNic == null) { - s_logger.warn("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); - throw new IllegalArgumentException("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); + s_logger.warn("Unable to find public network " + _publicNetworkName + " for host " + _host.getIp()); + throw new IllegalArgumentException("Unable to find public network " + _publicNetworkName + " for host " + _host.getIp()); } } else { publicNic = guestNic; _publicNetworkName = _guestNetworkName; } - _host.publicPif = publicNic.getPifRecord(conn).uuid; - _host.publicNetwork = publicNic.getNetworkRecord(conn).uuid; + _host.setPublicPif(publicNic.getPifRecord(conn).uuid); + _host.setPublicNetwork(publicNic.getNetworkRecord(conn).uuid); if (_storageNetworkName1 == null) { _storageNetworkName1 = _guestNetworkName; } XsLocalNetwork storageNic1 = null; storageNic1 = getNetworkByName(conn, _storageNetworkName1); if (storageNic1 == null) { - s_logger.warn("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.ip); - throw new IllegalArgumentException("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.ip); + s_logger.warn("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.getIp()); + throw new IllegalArgumentException("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.getIp()); } else { - _host.storageNetwork1 = storageNic1.getNetworkRecord(conn).uuid; - _host.storagePif1 = storageNic1.getPifRecord(conn).uuid; + _host.setStorageNetwork1(storageNic1.getNetworkRecord(conn).uuid); + _host.setStoragePif1(storageNic1.getPifRecord(conn).uuid); } XsLocalNetwork storageNic2 = null; if (_storageNetworkName2 != null) { storageNic2 = getNetworkByName(conn, _storageNetworkName2); if(storageNic2 != null) { - _host.storagePif2 = storageNic2.getPifRecord(conn).uuid; + _host.setStoragePif2(storageNic2.getPifRecord(conn).uuid); } } - s_logger.info("XenServer Version is " + _host.productVersion + " for host " + _host.ip); - s_logger.info("Private Network is " + _privateNetworkName + " for host " + _host.ip); - s_logger.info("Guest Network is " + _guestNetworkName + " for host " + _host.ip); - s_logger.info("Public Network is " + _publicNetworkName + " for host " + _host.ip); + s_logger.info("XenServer Version is " + _host.getProductVersion() + " for host " + _host.getIp()); + s_logger.info("Private Network is " + _privateNetworkName + " for host " + _host.getIp()); + s_logger.info("Guest Network is " + _guestNetworkName + " for host " + _host.getIp()); + s_logger.info("Public Network is " + _publicNetworkName + " for host " + _host.getIp()); return true; } catch (final XenAPIException e) { - s_logger.warn("Unable to get host information for " + _host.ip, e); + s_logger.warn("Unable to get host information for " + _host.getIp(), e); return false; } catch (final Exception e) { - s_logger.warn("Unable to get host information for " + _host.ip, e); + s_logger.warn("Unable to get host information for " + _host.getIp(), e); return false; } } @@ -4349,7 +4349,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - private void setupLinkLocalNetwork(final Connection conn) { + public void setupLinkLocalNetwork(final Connection conn) { try { final Network.Record rec = new Network.Record(); final Set networks = Network.getByNameLabel(conn, _linkLocalPrivateNetworkName); @@ -4416,7 +4416,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final String brName = linkLocal.getBridge(conn); callHostPlugin(conn, "vmops", "setLinkLocalIP", "brName", brName); - _host.linkLocalNetwork = linkLocal.getUuid(conn); + _host.setLinkLocalNetwork(linkLocal.getUuid(conn)); } catch (final XenAPIException e) { s_logger.warn("Unable to create local link network", e); @@ -4461,7 +4461,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe public StartupCommand[] initialize() throws IllegalArgumentException { final Connection conn = getConnection(); if (!getHostInfo(conn)) { - s_logger.warn("Unable to get host information for " + _host.ip); + s_logger.warn("Unable to get host information for " + _host.getIp()); return null; } final StartupRoutingCommand cmd = new StartupRoutingCommand(); @@ -4471,7 +4471,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cmd.setPoolSync(false); try { - final Pool pool = Pool.getByUuid(conn, _host.pool); + final Pool pool = Pool.getByUuid(conn, _host.getPool()); final Pool.Record poolr = pool.getRecord(conn); poolr.master.getRecord(conn); } catch (final Throwable e) { @@ -4487,7 +4487,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe private void cleanupTemplateSR(final Connection conn) { Set pbds = null; try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); pbds = host.getPBDs(conn); } catch (final XenAPIException e) { s_logger.warn("Unable to get the SRs " + e.toString(), e); @@ -4523,11 +4523,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected boolean launchHeartBeat(final Connection conn) { final String result = callHostPluginPremium(conn, "heartbeat", - "host", _host.uuid, + "host", _host.getUuid(), "timeout", Integer.toString(_heartbeatTimeout), "interval", Integer.toString(_heartbeatInterval)); if (result == null || !result.contains("> DONE <")) { - s_logger.warn("Unable to launch the heartbeat process on " + _host.ip); + s_logger.warn("Unable to launch the heartbeat process on " + _host.getIp()); return false; } return true; @@ -4538,11 +4538,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { final Map poolRecs = Pool.getAllRecords(conn); if (poolRecs.size() != 1) { - throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + _host.uuid); + throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + _host.getUuid()); } final Host master = poolRecs.values().iterator().next().master; setupServer(conn, master); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); setupServer(conn, host); if (!setIptables(conn)) { @@ -4555,7 +4555,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (!_canBridgeFirewall) { final String msg = "Failed to configure brige firewall"; s_logger.warn(msg); - s_logger.warn("Check host " + _host.ip +" for CSP is installed or not and check network mode for bridge"); + s_logger.warn("Check host " + _host.getIp() +" for CSP is installed or not and check network mode for bridge"); return new SetupAnswer(cmd, msg); } @@ -4579,7 +4579,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (cmd.needSetup() ) { - final String result = callHostPlugin(conn, "vmops", "setup_iscsi", "uuid", _host.uuid); + final String result = callHostPlugin(conn, "vmops", "setup_iscsi", "uuid", _host.getUuid()); if (!result.contains("> DONE <")) { s_logger.warn("Unable to setup iscsi: " + result); @@ -4593,7 +4593,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (rec.management) { if (rec.VLAN != null && rec.VLAN != -1) { final String msg = - new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) + new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.getUuid()) .append("; pif=") .append(rec.uuid) .append("; vlan=") @@ -4611,14 +4611,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (mgmtPif == null) { - final String msg = "Unable to find management network for " + _host.uuid; + final String msg = "Unable to find management network for " + _host.getUuid(); s_logger.warn(msg); return new SetupAnswer(cmd, msg); } final Map networks = Network.getAllRecords(conn); if(networks == null) { - final String msg = "Unable to setup as there are no networks in the host: " + _host.uuid; + final String msg = "Unable to setup as there are no networks in the host: " + _host.getUuid(); s_logger.warn(msg); return new SetupAnswer(cmd, msg); } @@ -4626,9 +4626,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (network.nameLabel.equals("cloud-private")) { for (final PIF pif : network.PIFs) { final PIF.Record pr = pif.getRecord(conn); - if (_host.uuid.equals(pr.host.getUuid(conn))) { + if (_host.getUuid().equals(pr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Found a network called cloud-private. host=" + _host.uuid + "; Network=" + network.uuid + "; pif=" + pr.uuid); + s_logger.debug("Found a network called cloud-private. host=" + _host.getUuid() + "; Network=" + network.uuid + "; pif=" + pr.uuid); } if (pr.VLAN != null && pr.VLAN != -1) { final String msg = @@ -4657,7 +4657,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (!transferManagementNetwork(conn, host, slave, spr, pif)) { final String msg = new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + - _host.uuid).toString(); + _host.getUuid()).toString(); s_logger.warn(msg); return new SetupAnswer(cmd, msg); } @@ -4849,11 +4849,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } catch (final XenAPIException e) { - final String msg = "CheckNetworkCommand failed with XenAPIException:" + e.toString() + " host:" + _host.uuid; + final String msg = "CheckNetworkCommand failed with XenAPIException:" + e.toString() + " host:" + _host.getUuid(); s_logger.warn(msg, e); return new CheckNetworkAnswer(cmd, false, msg); } catch (final Exception e) { - final String msg = "CheckNetworkCommand failed with Exception:" + e.getMessage() + " host:" + _host.uuid; + final String msg = "CheckNetworkCommand failed with Exception:" + e.getMessage() + " host:" + _host.getUuid(); s_logger.warn(msg, e); return new CheckNetworkAnswer(cmd, false, msg); } @@ -4885,7 +4885,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe pbds = sr.getPBDs(conn); for (final PBD pbd : pbds) { final PBD.Record pbdr = pbd.getRecord(conn); - if (pbdr.host != null && pbdr.host.getUuid(conn).equals(_host.uuid)) { + if (pbdr.host != null && pbdr.host.getUuid(conn).equals(_host.getUuid())) { if (!pbdr.currentlyAttached) { pbd.plug(conn); } @@ -4912,11 +4912,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final long used = sr.getPhysicalUtilisation(conn); return new GetStorageStatsAnswer(cmd, capacity, used); } catch (final XenAPIException e) { - final String msg = "GetStorageStats Exception:" + e.toString() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); + final String msg = "GetStorageStats Exception:" + e.toString() + "host:" + _host.getUuid() + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } catch (final XmlRpcException e) { - final String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); + final String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + _host.getUuid() + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } @@ -4940,7 +4940,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final SR.Record srr = sr.getRecord(conn); final Set pbds = sr.getPBDs(conn); if (pbds.size() == 0) { - final String msg = "There is no PBDs for this SR: " + srr.nameLabel + " on host:" + _host.uuid; + final String msg = "There is no PBDs for this SR: " + srr.nameLabel + " on host:" + _host.getUuid(); s_logger.warn(msg); return false; } @@ -4956,7 +4956,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); boolean found = false; for (final PBD pbd : pbds) { final PBD.Record pbdr = pbd.getRecord(conn); @@ -5007,7 +5007,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd, true, "success"); } catch (final Exception e) { final String msg = - "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + _host.uuid + " pool: " + + "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + _host.getUuid() + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); @@ -5021,7 +5021,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { final Map poolRecs = Pool.getAllRecords(conn); if (poolRecs.size() != 1) { - throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + _host.uuid); + throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + _host.getUuid()); } final Host master = poolRecs.values().iterator().next().master; for (int i = 0; i < params.length; i += 2) { @@ -5058,21 +5058,21 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return srUuid; } String result = null; - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Set tags = host.getTags(conn); if (force || !tags.contains("cloud-heartbeat-" + srUuid)) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Setting up the heartbeat sr for host " + _host.ip + " and sr " + srUuid); + s_logger.debug("Setting up the heartbeat sr for host " + _host.getIp() + " and sr " + srUuid); } final Set pbds = sr.getPBDs(conn); for (final PBD pbd : pbds) { final PBD.Record pbdr = pbd.getRecord(conn); - if (!pbdr.currentlyAttached && pbdr.host.getUuid(conn).equals(_host.uuid)) { + if (!pbdr.currentlyAttached && pbdr.host.getUuid(conn).equals(_host.getUuid())) { pbd.plug(conn); break; } } - result = callHostPluginThroughMaster(conn, "vmopspremium", "setup_heartbeat_sr", "host", _host.uuid, "sr", srUuid); + result = callHostPluginThroughMaster(conn, "vmopspremium", "setup_heartbeat_sr", "host", _host.getUuid(), "sr", srUuid); if (result == null || !result.split("#")[1].equals("0")) { throw new CloudRuntimeException("Unable to setup heartbeat sr on SR " + srUuid + " due to " + result); } @@ -5082,7 +5082,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe host.setTags(conn, tags); } } - result = callHostPluginPremium(conn, "setup_heartbeat_file", "host", _host.uuid, "sr", srUuid, "add", "true"); + result = callHostPluginPremium(conn, "setup_heartbeat_file", "host", _host.getUuid(), "sr", srUuid, "add", "true"); if (result == null || !result.split("#")[1].equals("0")) { throw new CloudRuntimeException("Unable to setup heartbeat file entry on SR " + srUuid + " due to " + result); } @@ -5108,11 +5108,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (final XenAPIException e) { - final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getHost() + pool.getPath(); + final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.toString() + " host:" + _host.getUuid() + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (final Exception e) { - final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getHost() + pool.getPath(); + final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.getMessage() + " host:" + _host.getUuid() + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } @@ -5120,17 +5120,17 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { final SR sr = getStorageRepository(conn, pool.getUuid()); final String srUuid = sr.getUuid(conn); - final String result = callHostPluginPremium(conn, "setup_heartbeat_file", "host", _host.uuid, "sr", srUuid, "add", "false"); + final String result = callHostPluginPremium(conn, "setup_heartbeat_file", "host", _host.getUuid(), "sr", srUuid, "add", "false"); if (result == null || !result.split("#")[1].equals("0")) { throw new CloudRuntimeException("Unable to remove heartbeat file entry for SR " + srUuid + " due to " + result); } return new Answer(cmd, true, "seccuss"); } catch (final XenAPIException e) { - final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getHost() + pool.getPath(); + final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.toString() + " host:" + _host.getUuid() + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (final Exception e) { - final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getHost() + pool.getPath(); + final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.getMessage() + " host:" + _host.getUuid() + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } @@ -5139,7 +5139,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected boolean can_bridge_firewall(final Connection conn) { - return Boolean.valueOf(callHostPlugin(conn, "vmops", "can_bridge_firewall", "host_uuid", _host.uuid, "instance", _instance)); + return Boolean.valueOf(callHostPlugin(conn, "vmops", "can_bridge_firewall", "host_uuid", _host.getUuid(), "instance", _instance)); } private Answer execute(final OvsSetupBridgeCommand cmd) { @@ -5289,7 +5289,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe private List> ovsFullSyncStates() { final Connection conn = getConnection(); - final String result = callHostPlugin(conn, "ovsgre", "ovs_get_vm_log", "host_uuid", _host.uuid); + final String result = callHostPlugin(conn, "ovsgre", "ovs_get_vm_log", "host_uuid", _host.getUuid()); final String[] logs = result != null ? result.split(";") : new String[0]; final List> states = new ArrayList>(); for (final String log : logs) { @@ -5349,12 +5349,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (is_xcp()) { label = getLabel(); } - s_logger.debug("Will look for network with name-label:" + label + " on host " + _host.ip); + s_logger.debug("Will look for network with name-label:" + label + " on host " + _host.getIp()); final Connection conn = getConnection(); try { final XsLocalNetwork nw = getNetworkByName(conn, label); if(nw == null) { - throw new CloudRuntimeException("Unable to locate the network with name-label: " + label + " on host: " + _host.ip); + throw new CloudRuntimeException("Unable to locate the network with name-label: " + label + " on host: " + _host.getIp()); } s_logger.debug("Network object:" + nw.getNetwork().getUuid(conn)); final PIF pif = nw.getPif(conn); @@ -5362,13 +5362,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.debug("PIF object:" + pifRec.uuid + "(" + pifRec.device + ")"); return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + pifRec.device + " retrieved successfully", pifRec.IP, pifRec.netmask, pifRec.MAC); } catch (final BadServerResponse e) { - s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.ip, e); + s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.getIp(), e); return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" + e.getMessage()); } catch (final XenAPIException e) { - s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.ip, e); + s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.getIp(), e); return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" + e.getMessage()); } catch (final XmlRpcException e) { - s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.ip, e); + s_logger.error("An error occurred while fetching the interface for " + label + " on host " + _host.getIp(), e); return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" + e.getMessage()); } } @@ -5387,30 +5387,30 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Long.toString(cmd.getFrom()), "to", Long.toString(cmd.getTo())); final String[] res = result.split(":"); if (res.length != 2 || res.length == 2 && res[1].equalsIgnoreCase("[]")) { - return new OvsCreateGreTunnelAnswer(cmd, false, result, _host.ip, bridge); + return new OvsCreateGreTunnelAnswer(cmd, false, result, _host.getIp(), bridge); } else { - return new OvsCreateGreTunnelAnswer(cmd, true, result, _host.ip, bridge, Integer.parseInt(res[1])); + return new OvsCreateGreTunnelAnswer(cmd, true, result, _host.getIp(), bridge, Integer.parseInt(res[1])); } } catch (final BadServerResponse e) { - s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.ip, e); + s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.getIp(), e); } catch (final XenAPIException e) { - s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.ip, e); + s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.getIp(), e); } catch (final XmlRpcException e) { - s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.ip, e); + s_logger.error("An error occurred while creating a GRE tunnel to " + cmd.getRemoteIp() + " on host " + _host.getIp(), e); } - return new OvsCreateGreTunnelAnswer(cmd, false, "EXCEPTION", _host.ip, bridge); + return new OvsCreateGreTunnelAnswer(cmd, false, "EXCEPTION", _host.getIp(), bridge); } private Answer execute(final SecurityGroupRulesCmd cmd) { final Connection conn = getConnection(); if (s_logger.isTraceEnabled()) { - s_logger.trace("Sending network rules command to " + _host.ip); + s_logger.trace("Sending network rules command to " + _host.getIp()); } if (!_canBridgeFirewall) { - s_logger.warn("Host " + _host.ip + " cannot do bridge firewalling"); - return new SecurityGroupRuleAnswer(cmd, false, "Host " + _host.ip + " cannot do bridge firewalling", + s_logger.warn("Host " + _host.getIp() + " cannot do bridge firewalling"); + return new SecurityGroupRuleAnswer(cmd, false, "Host " + _host.getIp() + " cannot do bridge firewalling", SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); } @@ -5438,7 +5438,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final Answer answer = new Answer(cmd, true, "success"); return answer; } catch (final Exception e) { - final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + poolTO.getHost() + poolTO.getPath(); + final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.getUuid() + " pool: " + poolTO.getHost() + poolTO.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } @@ -5446,7 +5446,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } public Connection getConnection() { - return ConnPool.connect(_host.uuid, _host.pool, _host.ip, _username, _password, _wait); + return ConnPool.connect(_host.getUuid(), _host.getPool(), _host.getIp(), _username, _password, _wait); } @@ -5454,7 +5454,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final StringBuilder caps = new StringBuilder(); try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Host.Record hr = host.getRecord(conn); Map details = cmd.getHostDetails(); @@ -5467,12 +5467,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe productBrand = hr.softwareVersion.get("platform_name"); } details.put("product_brand", productBrand); - details.put("product_version", _host.productVersion); + details.put("product_version", _host.getProductVersion()); if (hr.softwareVersion.get("product_version_text_short") != null) { details.put("product_version_text_short", hr.softwareVersion.get("product_version_text_short")); cmd.setHypervisorVersion(hr.softwareVersion.get("product_version_text_short")); - cmd.setHypervisorVersion(_host.productVersion); + cmd.setHypervisorVersion(_host.getProductVersion()); } if (_privateNetworkName != null) { details.put("private.network.device", _privateNetworkName); @@ -5480,8 +5480,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cmd.setHostDetails(details); cmd.setName(hr.nameLabel); - cmd.setGuid(_host.uuid); - cmd.setPool(_host.pool); + cmd.setGuid(_host.getUuid()); + cmd.setPool(_host.getPool()); cmd.setDataCenter(Long.toString(_dcId)); for (final String cap : hr.capabilities) { if (cap.length() > 0) { @@ -5493,9 +5493,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } cmd.setCaps(caps.toString()); - cmd.setSpeed(_host.speed); - cmd.setCpuSockets(_host.cpuSockets); - cmd.setCpus(_host.cpus); + cmd.setSpeed(_host.getSpeed()); + cmd.setCpuSockets(_host.getCpuSockets()); + cmd.setCpus(_host.getCpus()); final HostMetrics hm = host.getMetrics(conn); @@ -5518,19 +5518,19 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.debug("Total Ram: " + ram + " dom0 Ram: " + dom0Ram); } - PIF pif = PIF.getByUuid(conn, _host.privatePif); + PIF pif = PIF.getByUuid(conn, _host.getPrivatePif()); PIF.Record pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setPrivateIpAddress(pifr.IP); cmd.setPrivateMacAddress(pifr.MAC); cmd.setPrivateNetmask(pifr.netmask); } else { - cmd.setPrivateIpAddress(_host.ip); + cmd.setPrivateIpAddress(_host.getIp()); cmd.setPrivateMacAddress(pifr.MAC); cmd.setPrivateNetmask("255.255.255.0"); } - pif = PIF.getByUuid(conn, _host.publicPif); + pif = PIF.getByUuid(conn, _host.getPublicPif()); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setPublicIpAddress(pifr.IP); @@ -5538,8 +5538,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cmd.setPublicNetmask(pifr.netmask); } - if (_host.storagePif1 != null) { - pif = PIF.getByUuid(conn, _host.storagePif1); + if (_host.getStoragePif1() != null) { + pif = PIF.getByUuid(conn, _host.getStoragePif1()); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddress(pifr.IP); @@ -5548,8 +5548,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - if (_host.storagePif2 != null) { - pif = PIF.getByUuid(conn, _host.storagePif2); + if (_host.getStoragePif2() != null) { + pif = PIF.getByUuid(conn, _host.getStoragePif2()); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddressDeux(pifr.IP); @@ -5584,10 +5584,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new ConfigurationException("Unable to get the zone " + params.get("zone")); } - _host.uuid = (String)params.get("guid"); + _host.setUuid((String)params.get("guid")); - _name = _host.uuid; - _host.ip = (String)params.get("ipaddress"); + _name = _host.getUuid(); + _host.setIp((String)params.get("ipaddress")); _username = (String)params.get("username"); _password.add((String)params.get("password")); @@ -5622,7 +5622,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new ConfigurationException("Unable to get the pod"); } - if (_host.ip == null) { + if (_host.getIp() == null) { throw new ConfigurationException("Unable to get the host address"); } @@ -5634,7 +5634,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new ConfigurationException("Unable to get the password"); } - if (_host.uuid == null) { + if (_host.getUuid() == null) { throw new ConfigurationException("Unable to get the uuid"); } @@ -5655,23 +5655,23 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } private void CheckXenHostInfo() throws ConfigurationException { - final Connection conn = ConnPool.getConnect(_host.ip, _username, _password); + final Connection conn = ConnPool.getConnect(_host.getIp(), _username, _password); if( conn == null ) { - throw new ConfigurationException("Can not create connection to " + _host.ip); + throw new ConfigurationException("Can not create connection to " + _host.getIp()); } try { Host.Record hostRec = null; try { - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); hostRec = host.getRecord(conn); final Pool.Record poolRec = Pool.getAllRecords(conn).values().iterator().next(); - _host.pool = poolRec.uuid; + _host.setPool(poolRec.uuid); } catch (final Exception e) { - throw new ConfigurationException("Can not get host information from " + _host.ip); + throw new ConfigurationException("Can not get host information from " + _host.getIp()); } - if (!hostRec.address.equals(_host.ip)) { - final String msg = "Host " + _host.ip + " seems be reinstalled, please remove this host and readd"; + if (!hostRec.address.equals(_host.getIp())) { + final String msg = "Host " + _host.getIp() + " seems be reinstalled, please remove this host and readd"; s_logger.error(msg); throw new ConfigurationException(msg); } @@ -5779,7 +5779,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Map smConfig = new HashMap(); smConfig.put("nosubdir", "true"); final SR sr = SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, smConfig); @@ -5809,7 +5809,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String path = uri.getPath(); path = path.replace("//", "/"); deviceConfig.put("location", uri.getHost() + ":" + path); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final SR sr = SR.create(conn, host, deviceConfig, new Long(0), uri.getHost() + path, "iso", "iso", "iso", shared, new HashMap()); sr.setNameLabel(conn, vmName + "-ISO"); sr.setNameDescription(conn, deviceConfig.get("location")); @@ -5915,7 +5915,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { throw new CloudRuntimeException("There is a SR using the same configuration target:" + dc.get("target") + ", targetIQN:" + dc.get("targetIQN") + - ", lunid:" + dc.get("lunid") + " for pool " + srNameLabel + "on host:" + _host.uuid); + ", lunid:" + dc.get("lunid") + " for pool " + srNameLabel + "on host:" + _host.getUuid()); } } deviceConfig.put("target", target); @@ -5926,7 +5926,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe deviceConfig.put("chappassword", chapInitiatorPassword); } - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Map smConfig = new HashMap(); final String type = SRType.LVMOISCSI.toString(); SR sr = null; @@ -6049,14 +6049,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { throw new CloudRuntimeException("There is a SR using the same configuration server:" + dc.get("server") + ", serverpath:" + dc.get("serverpath") + - " for pool " + uuid + " on host:" + _host.uuid); + " for pool " + uuid + " on host:" + _host.getUuid()); } } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); - final Host host = Host.getByUuid(conn, _host.uuid); + final Host host = Host.getByUuid(conn, _host.getUuid()); final Map smConfig = new HashMap(); smConfig.put("nosubdir", "true"); final SR sr = SR.create(conn, host, deviceConfig, new Long(0), uuid, poolid, SRType.NFS.toString(), "user", true, smConfig); @@ -6355,7 +6355,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe task = vm.snapshotAsync(conn, vmSnapshotName); } else { final Set vbds = vm.getVBDs(conn); - final Pool pool = Pool.getByUuid(conn, _host.pool); + final Pool pool = Pool.getByUuid(conn, _host.getPool()); for (final VBD vbd : vbds) { final VBD.Record vbdr = vbd.getRecord(conn); if (vbdr.userdevice.equals("0")) { @@ -6763,9 +6763,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (checkSR(conn, sr)) { return sr; } - throw new CloudRuntimeException("SR check failed for storage pool: " + srNameLabel + "on host:" + _host.uuid); + throw new CloudRuntimeException("SR check failed for storage pool: " + srNameLabel + "on host:" + _host.getUuid()); } else { - throw new CloudRuntimeException("Can not see storage pool: " + srNameLabel + " from on host:" + _host.uuid); + throw new CloudRuntimeException("Can not see storage pool: " + srNameLabel + " from on host:" + _host.getUuid()); } } @@ -6917,11 +6917,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final String result = callHostPlugin(conn, "vmops", "cleanup_rules", "instance", _instance); final int numCleaned = Integer.parseInt(result); if (result == null || result.isEmpty() || numCleaned < 0) { - s_logger.warn("Failed to cleanup rules for host " + _host.ip); + s_logger.warn("Failed to cleanup rules for host " + _host.getIp()); return new Answer(cmd, false, result); } if (numCleaned > 0) { - s_logger.info("Cleaned up rules for " + result + " vms on host " + _host.ip); + s_logger.info("Cleaned up rules for " + result + " vms on host " + _host.getIp()); } return new Answer(cmd, true, result); } @@ -6963,9 +6963,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe final Network.Record nr = getNetworkRecord(conn); for (final PIF pif : nr.PIFs) { final PIF.Record pr = pif.getRecord(conn); - if (_host.uuid.equals(pr.host.getUuid(conn))) { + if (_host.getUuid().equals(pr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Found a network called " + nr.nameLabel + " on host=" + _host.ip + "; Network=" + nr.uuid + "; pif=" + pr.uuid); + s_logger.debug("Found a network called " + nr.nameLabel + " on host=" + _host.getIp() + "; Network=" + nr.uuid + "; pif=" + pr.uuid); } _p = pif; _pr = pr; @@ -6987,38 +6987,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - // A list of UUIDs that are gathered from the XenServer when - // the resource first connects to XenServer. These UUIDs do - // not change over time. - protected class XsHost { - public String systemvmisouuid; - public String uuid; - public String ip; - public String publicNetwork; - public String privateNetwork; - public String linkLocalNetwork; - public Network vswitchNetwork; - public String storageNetwork1; - public String guestNetwork; - public String guestPif; - public String publicPif; - public String privatePif; - public String storagePif1; - public String storagePif2; - public String pool; - public int speed; - public Integer cpuSockets; - public int cpus; - public String productVersion; - public String localSRuuid; - - @Override - public String toString() { - return new StringBuilder("XS[").append(uuid).append("-").append(ip).append("]").toString(); - } - } - - protected String getGuestOsType(final String stdType, String platformEmulator, final boolean bootFromCD) { if (platformEmulator == null) { s_logger.debug("no guest OS type, start it as HVM guest"); @@ -7059,10 +7027,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe //check if this is master Pool pool; try { - pool = Pool.getByUuid(conn, _host.pool); + pool = Pool.getByUuid(conn, _host.getPool()); final Pool.Record poolr = pool.getRecord(conn); final Host.Record hostr = poolr.master.getRecord(conn); - if (!_host.uuid.equals(hostr.uuid)) { + if (!_host.getUuid().equals(hostr.uuid)) { return new ClusterVMMetaDataSyncAnswer(cmd.getClusterId(), null); } } catch (final Throwable e) { @@ -7086,7 +7054,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } } catch (final Throwable e) { - final String msg = "Unable to get vms through host " + _host.uuid + " due to to " + e.toString(); + final String msg = "Unable to get vms through host " + _host.getUuid() + " due to to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg); } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XcpOssResource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XcpOssResource.java index 1a6de1f2daa..b5eef7eeee1 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XcpOssResource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XcpOssResource.java @@ -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 getPatchFiles() { - List files = new ArrayList(); - String patch = "scripts/vm/hypervisor/xenserver/xcposs/patch"; - String patchfilePath = Script.findScript("", patch); + final List files = new ArrayList(); + 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 vdis = VDI.getByNameLabel(conn, "systemvm-vdi"); + final Set 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); } } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer56Resource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer56Resource.java index a8e9efac9aa..1de7b963be2 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer56Resource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer56Resource.java @@ -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())) { diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer610Resource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer610Resource.java index 2283477eac3..3c5caf03ce3 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer610Resource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer610Resource.java @@ -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 getUpdatedVolumePathsOfMigratedVm(Connection connection, VM migratedVm, DiskTO[] volumes) throws CloudRuntimeException { - List volumeToList = new ArrayList(); + private List getUpdatedVolumePathsOfMigratedVm(final Connection connection, final VM migratedVm, final DiskTO[] volumes) throws CloudRuntimeException { + final List volumeToList = new ArrayList(); try { // Volume paths would have changed. Return that information. - Set vbds = migratedVm.getVBDs(connection); - Map deviceIdToVdiMap = new HashMap(); + final Set vbds = migratedVm.getVBDs(connection); + final Map deviceIdToVdiMap = new HashMap(); // 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 volumeToFiler = cmd.getVolumeToFiler(); + protected MigrateWithStorageAnswer execute(final MigrateWithStorageCommand cmd) { + final Connection connection = getConnection(); + final VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + final Map 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 other = new HashMap(); + final Map other = new HashMap(); other.put("live", "true"); - Network networkForSm = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork(); - Host host = Host.getByUuid(connection, _host.uuid); - Map 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 token = host.migrateReceive(connection, networkForSm, other); // Get the vm to migrate. - Set vms = VM.getByNameLabel(connection, vmSpec.getName()); - VM vmToMigrate = vms.iterator().next(); + final Set 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 vifMap = new HashMap(); - Map vdiMap = new HashMap(); - for (Map.Entry entry : volumeToFiler.entrySet()) { + final Map vifMap = new HashMap(); + final Map vdiMap = new HashMap(); + for (final Map.Entry 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 volumeToList = getUpdatedVolumePathsOfMigratedVm(connection, vmToMigrate, vmSpec.getDisks()); + final List 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 volumeToFiler = cmd.getVolumeToFiler(); + protected MigrateWithStorageReceiveAnswer execute(final MigrateWithStorageReceiveCommand cmd) { + final Connection connection = getConnection(); + final VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + final Map volumeToFiler = cmd.getVolumeToFiler(); try { // Get a map of all the SRs to which the vdis will be migrated. - Map volumeToSr = new HashMap(); - for (Map.Entry entry : volumeToFiler.entrySet()) { - SR sr = getStorageRepository(connection, entry.getValue().getUuid()); + final Map volumeToSr = new HashMap(); + for (final Map.Entry 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 nicToNetwork = new HashMap(); - for (NicTO nicTo : vmSpec.getNics()) { - Network network = getNetwork(connection, nicTo); + final Map nicToNetwork = new HashMap(); + for (final NicTO nicTo : vmSpec.getNics()) { + final Network network = getNetwork(connection, nicTo); nicToNetwork.put(nicTo, network); } - Map other = new HashMap(); + final Map other = new HashMap(); other.put("live", "true"); - Network network = getNativeNetworkForTraffic(connection, TrafficType.Storage, null).getNetwork(); - Host host = Host.getByUuid(connection, _host.uuid); - Map 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 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 volumeToSr = cmd.getVolumeToSr(); - Map nicToNetwork = cmd.getNicToNetwork(); - Map token = cmd.getToken(); + protected MigrateWithStorageSendAnswer execute(final MigrateWithStorageSendCommand cmd) { + final Connection connection = getConnection(); + final VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + final Map volumeToSr = cmd.getVolumeToSr(); + final Map nicToNetwork = cmd.getNicToNetwork(); + final Map token = cmd.getToken(); final String vmName = vmSpec.getName(); - Set volumeToSet = null; + final Set volumeToSet = null; boolean migrated = false; Task task = null; try { - Set vms = VM.getByNameLabel(connection, vmSpec.getName()); - VM vmToMigrate = vms.iterator().next(); - Map other = new HashMap(); + final Set vms = VM.getByNameLabel(connection, vmSpec.getName()); + final VM vmToMigrate = vms.iterator().next(); + final Map other = new HashMap(); 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 vdiMap = new HashMap(); - for (Map.Entry entry : volumeToSr.entrySet()) { + final Map vdiMap = new HashMap(); + for (final Map.Entry 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 vifMap = new HashMap(); - for (Map.Entry entry : nicToNetwork.entrySet()) { + final Map vifMap = new HashMap(); + for (final Map.Entry 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 vms = VM.getByNameLabel(connection, vmSpec.getName()); - VM migratedVm = vms.iterator().next(); + final Host host = Host.getByUuid(connection, _host.getUuid()); + final Set 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 volumeToSet = getUpdatedVolumePathsOfMigratedVm(connection, migratedVm, vmSpec.getDisks()); + final List 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 other = new HashMap(); + final SR destinationPool = getStorageRepository(connection, poolTO.getUuid()); + final VDI srcVolume = getVDIbyUuid(connection, volumeUUID); + final Map other = new HashMap(); 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. } } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620Resource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620Resource.java index ecc30895232..858fc154957 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620Resource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620Resource.java @@ -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 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 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 details = cmd.getHostDetails(); - Boolean hotFix62ESP1004 = hostHasHotFix(conn, XenserverConfigs.XSHotFix62ESP1004); + final Map 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); } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620SP1Resource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620SP1Resource.java index 5553553d49a..ac2b2a62f9d 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620SP1Resource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServer620SP1Resource.java @@ -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 clazz = cmd.getClass(); + public Answer executeRequest(final Command cmd) { + final Class 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> groupDetails = new HashMap>(); 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> groupDetails = getGPUGroupDetails(conn); + final HashMap> 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> getGPUGroupDetails(Connection conn) throws XenAPIException, XmlRpcException { - HashMap> groupDetails = new HashMap>(); - Host host = Host.getByUuid(conn, _host.uuid); - Set pgpus = host.getPGPUs(conn); - Iterator iter = pgpus.iterator(); + protected HashMap> getGPUGroupDetails(final Connection conn) throws XenAPIException, XmlRpcException { + final HashMap> groupDetails = new HashMap>(); + final Host host = Host.getByUuid(conn, _host.getUuid()); + final Set pgpus = host.getPGPUs(conn); + final Iterator iter = pgpus.iterator(); while (iter.hasNext()) { - PGPU pgpu = iter.next(); - GPUGroup gpuGroup = pgpu.getGPUGroup(conn); - Set enabledVGPUTypes = gpuGroup.getEnabledVGPUTypes(conn); - String groupName = gpuGroup.getNameLabel(conn); + final PGPU pgpu = iter.next(); + final GPUGroup gpuGroup = pgpu.getGPUGroup(conn); + final Set enabledVGPUTypes = gpuGroup.getEnabledVGPUTypes(conn); + final String groupName = gpuGroup.getNameLabel(conn); HashMap gpuCapacity = new HashMap(); if (groupDetails.get(groupName) != null) { gpuCapacity = groupDetails.get(groupName); } // Get remaining capacity of all the enabled VGPU in a PGPU if(enabledVGPUTypes != null) { - Iterator it = enabledVGPUTypes.iterator(); + final Iterator 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 groups = GPUGroup.getByNameLabel(conn, gpuDevice.getGpuGroup()); + final Set 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 vgpuTypes = gpuGroup.getEnabledVGPUTypes(conn); - Iterator iter = vgpuTypes.iterator(); + final Set vgpuTypes = gpuGroup.getEnabledVGPUTypes(conn); + final Iterator 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 other_config = new HashMap(); + final String device = "0"; // Only allow device = "0" for now, as XenServer supports just a single vGPU per VM. + final Map other_config = new HashMap(); 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)); } - -} +} \ No newline at end of file diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServerStorageProcessor.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServerStorageProcessor.java index 10a97a21c12..0cf40f58d63 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServerStorageProcessor.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XenServerStorageProcessor.java @@ -92,7 +92,7 @@ public class XenServerStorageProcessor implements StorageProcessor { protected CitrixResourceBase hypervisorResource; protected String BaseMountPointOnHost = "/var/run/cloud_mount"; - public XenServerStorageProcessor(CitrixResourceBase resource) { + public XenServerStorageProcessor(final CitrixResourceBase resource) { hypervisorResource = resource; } @@ -104,39 +104,39 @@ public class XenServerStorageProcessor implements StorageProcessor { // detach the new SR // if we needed to perform an attach to the source SR, detach from it @Override - public SnapshotAndCopyAnswer snapshotAndCopy(SnapshotAndCopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); + public SnapshotAndCopyAnswer snapshotAndCopy(final SnapshotAndCopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); try { SR sourceSr = null; - Map sourceDetails = cmd.getSourceDetails(); + final Map sourceDetails = cmd.getSourceDetails(); if (sourceDetails != null && sourceDetails.keySet().size() > 0) { - String iScsiName = sourceDetails.get(DiskTO.IQN); - String storageHost = sourceDetails.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = sourceDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = sourceDetails.get(DiskTO.CHAP_INITIATOR_SECRET); + final String iScsiName = sourceDetails.get(DiskTO.IQN); + final String storageHost = sourceDetails.get(DiskTO.STORAGE_HOST); + final String chapInitiatorUsername = sourceDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String chapInitiatorSecret = sourceDetails.get(DiskTO.CHAP_INITIATOR_SECRET); sourceSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, false); } - VDI vdiToSnapshot = VDI.getByUuid(conn, cmd.getUuidOfSourceVdi()); + final VDI vdiToSnapshot = VDI.getByUuid(conn, cmd.getUuidOfSourceVdi()); - VDI vdiSnapshot = vdiToSnapshot.snapshot(conn, new HashMap()); + final VDI vdiSnapshot = vdiToSnapshot.snapshot(conn, new HashMap()); - Map destDetails = cmd.getDestDetails(); + final Map destDetails = cmd.getDestDetails(); - String iScsiName = destDetails.get(DiskTO.IQN); - String storageHost = destDetails.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = destDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = destDetails.get(DiskTO.CHAP_INITIATOR_SECRET); + final String iScsiName = destDetails.get(DiskTO.IQN); + final String storageHost = destDetails.get(DiskTO.STORAGE_HOST); + final String chapInitiatorUsername = destDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String chapInitiatorSecret = destDetails.get(DiskTO.CHAP_INITIATOR_SECRET); - SR newSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, false); + final SR newSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, false); - VDI vdiCopy = vdiSnapshot.copy(conn, newSr); + final VDI vdiCopy = vdiSnapshot.copy(conn, newSr); - String vdiUuid = vdiCopy.getUuid(conn); + final String vdiUuid = vdiCopy.getUuid(conn); vdiSnapshot.destroy(conn); @@ -146,13 +146,13 @@ public class XenServerStorageProcessor implements StorageProcessor { hypervisorResource.removeSR(conn, newSr); - SnapshotAndCopyAnswer snapshotAndCopyAnswer = new SnapshotAndCopyAnswer(); + final SnapshotAndCopyAnswer snapshotAndCopyAnswer = new SnapshotAndCopyAnswer(); snapshotAndCopyAnswer.setPath(vdiUuid); return snapshotAndCopyAnswer; } - catch (Exception ex) { + catch (final Exception ex) { s_logger.warn("Failed to take and copy snapshot: " + ex.toString(), ex); return new SnapshotAndCopyAnswer(ex.getMessage()); @@ -160,40 +160,40 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public AttachAnswer attachIso(AttachCommand cmd) { - DiskTO disk = cmd.getDisk(); - DataTO data = disk.getData(); - DataStoreTO store = data.getDataStore(); + public AttachAnswer attachIso(final AttachCommand cmd) { + final DiskTO disk = cmd.getDisk(); + final DataTO data = disk.getData(); + final DataStoreTO store = data.getDataStore(); String isoURL = null; if (store == null) { - TemplateObjectTO iso = (TemplateObjectTO) disk.getData(); + final TemplateObjectTO iso = (TemplateObjectTO) disk.getData(); isoURL = iso.getName(); } else { if (!(store instanceof NfsTO)) { s_logger.debug("Can't attach a iso which is not created on nfs: "); return new AttachAnswer("Can't attach a iso which is not created on nfs: "); } - NfsTO nfsStore = (NfsTO) store; + final NfsTO nfsStore = (NfsTO) store; isoURL = nfsStore.getUrl() + nfsStore.getPathSeparator() + data.getPath(); } - String vmName = cmd.getVmName(); + final String vmName = cmd.getVmName(); try { - Connection conn = hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); VBD isoVBD = null; // Find the VM - VM vm = hypervisorResource.getVM(conn, vmName); + final VM vm = hypervisorResource.getVM(conn, vmName); // Find the ISO VDI - VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL); + final VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL); // Find the VM's CD-ROM VBD - Set vbds = vm.getVBDs(conn); - for (VBD vbd : vbds) { - String userDevice = vbd.getUserdevice(conn); - Types.VbdType type = vbd.getType(conn); + final Set vbds = vm.getVBDs(conn); + for (final VBD vbd : vbds) { + final String userDevice = vbd.getUserdevice(conn); + final Types.VbdType type = vbd.getType(conn); if (userDevice.equals("3") && type == Types.VbdType.CD) { isoVBD = vbd; @@ -215,39 +215,39 @@ public class XenServerStorageProcessor implements StorageProcessor { return new AttachAnswer(disk); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { s_logger.warn("Failed to attach iso" + ": " + e.toString(), e); return new AttachAnswer(e.toString()); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Failed to attach iso" + ": " + e.toString(), e); return new AttachAnswer(e.toString()); } } @Override - public AttachAnswer attachVolume(AttachCommand cmd) { - DiskTO disk = cmd.getDisk(); - DataTO data = disk.getData(); + public AttachAnswer attachVolume(final AttachCommand cmd) { + final DiskTO disk = cmd.getDisk(); + final DataTO data = disk.getData(); try { - String vmName = cmd.getVmName(); - String vdiNameLabel = vmName + "-DATA"; + final String vmName = cmd.getVmName(); + final String vdiNameLabel = vmName + "-DATA"; - Connection conn = this.hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); VM vm = null; boolean vmNotRunning = true; try { - vm = this.hypervisorResource.getVM(conn, vmName); + vm = hypervisorResource.getVM(conn, vmName); - VM.Record vmr = vm.getRecord(conn); + final VM.Record vmr = vm.getRecord(conn); vmNotRunning = vmr.powerState != VmPowerState.RUNNING; - } catch (CloudRuntimeException ex) { + } catch (final CloudRuntimeException ex) { } - Map details = disk.getDetails(); - boolean isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + final Map details = disk.getDetails(); + final boolean isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); // if the VM is not running and we're not dealing with managed storage, just return success (nothing to do here) // this should probably never actually happen @@ -261,7 +261,7 @@ public class XenServerStorageProcessor implements StorageProcessor { vdi = hypervisorResource.prepareManagedStorage(conn, details, data.getPath(), vdiNameLabel); if (vmNotRunning) { - DiskTO newDisk = new DiskTO(disk.getData(), disk.getDiskSeq(), vdi.getUuid(conn), disk.getType()); + final DiskTO newDisk = new DiskTO(disk.getData(), disk.getDiskSeq(), vdi.getUuid(conn), disk.getType()); return new AttachAnswer(newDisk); } @@ -271,17 +271,17 @@ public class XenServerStorageProcessor implements StorageProcessor { // Figure out the disk number to attach the VM to String diskNumber = null; - Long deviceId = disk.getDiskSeq(); + final Long deviceId = disk.getDiskSeq(); if (deviceId != null) { if (deviceId.longValue() == 3) { - String msg = "Device 3 is reserved for CD-ROM, choose other device"; + final String msg = "Device 3 is reserved for CD-ROM, choose other device"; return new AttachAnswer(msg); } if (hypervisorResource.isDeviceUsed(conn, vm, deviceId)) { - String msg = "Device " + deviceId + " is used in VM " + vmName; + final String msg = "Device " + deviceId + " is used in VM " + vmName; return new AttachAnswer(msg); } @@ -291,7 +291,7 @@ public class XenServerStorageProcessor implements StorageProcessor { diskNumber = hypervisorResource.getUnusedDeviceNum(conn, vm); } - VBD.Record vbdr = new VBD.Record(); + final VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; @@ -301,66 +301,66 @@ public class XenServerStorageProcessor implements StorageProcessor { vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; - VBD vbd = VBD.create(conn, vbdr); + final VBD vbd = VBD.create(conn, vbdr); // Attach the VBD to the VM try { vbd.plug(conn); - } catch (Exception e) { + } catch (final Exception e) { vbd.destroy(conn); throw e; } // Update the VDI's label to include the VM name vdi.setNameLabel(conn, vdiNameLabel); - DiskTO newDisk = new DiskTO(disk.getData(), Long.parseLong(diskNumber), vdi.getUuid(conn), disk.getType()); + final DiskTO newDisk = new DiskTO(disk.getData(), Long.parseLong(diskNumber), vdi.getUuid(conn), disk.getType()); return new AttachAnswer(newDisk); - } catch (Exception e) { - String msg = "Failed to attach volume" + " for uuid: " + data.getPath() + " due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Failed to attach volume" + " for uuid: " + data.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); return new AttachAnswer(msg); } } @Override - public Answer dettachIso(DettachCommand cmd) { - DiskTO disk = cmd.getDisk(); - DataTO data = disk.getData(); - DataStoreTO store = data.getDataStore(); + public Answer dettachIso(final DettachCommand cmd) { + final DiskTO disk = cmd.getDisk(); + final DataTO data = disk.getData(); + final DataStoreTO store = data.getDataStore(); String isoURL = null; if (store == null) { - TemplateObjectTO iso = (TemplateObjectTO) disk.getData(); + final TemplateObjectTO iso = (TemplateObjectTO) disk.getData(); isoURL = iso.getName(); } else { if (!(store instanceof NfsTO)) { s_logger.debug("Can't attach a iso which is not created on nfs: "); return new AttachAnswer("Can't attach a iso which is not created on nfs: "); } - NfsTO nfsStore = (NfsTO) store; + final NfsTO nfsStore = (NfsTO) store; isoURL = nfsStore.getUrl() + nfsStore.getPathSeparator() + data.getPath(); } try { - Connection conn = hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); // Find the VM - VM vm = hypervisorResource.getVM(conn, cmd.getVmName()); - String vmUUID = vm.getUuid(conn); + final VM vm = hypervisorResource.getVM(conn, cmd.getVmName()); + final String vmUUID = vm.getUuid(conn); // Find the ISO VDI - VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, cmd.getVmName(), isoURL); + final VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, cmd.getVmName(), isoURL); - SR sr = isoVDI.getSR(conn); + final SR sr = isoVDI.getSR(conn); // Look up all VBDs for this VDI - Set vbds = isoVDI.getVBDs(conn); + final Set vbds = isoVDI.getVBDs(conn); // Iterate through VBDs, and if the VBD belongs the VM, eject // the ISO from it - for (VBD vbd : vbds) { - VM vbdVM = vbd.getVM(conn); - String vbdVmUUID = vbdVM.getUuid(conn); + for (final VBD vbd : vbds) { + final VM vbdVM = vbd.getVM(conn); + final String vbdVmUUID = vbdVM.getUuid(conn); if (vbdVmUUID.equals(vmUUID)) { // If an ISO is already inserted, eject it @@ -376,37 +376,37 @@ public class XenServerStorageProcessor implements StorageProcessor { } return new DettachAnswer(disk); - } catch (XenAPIException e) { - String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + " due to " + e.toString(); + } catch (final XenAPIException e) { + final String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); return new DettachAnswer(msg); - } catch (Exception e) { - String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + " due to " + e.getMessage(); + } catch (final Exception e) { + final String msg = "Failed to dettach volume" + " for uuid: " + data.getPath() + " due to " + e.getMessage(); s_logger.warn(msg, e); return new DettachAnswer(msg); } } @Override - public Answer dettachVolume(DettachCommand cmd) { - DiskTO disk = cmd.getDisk(); - DataTO data = disk.getData(); + public Answer dettachVolume(final DettachCommand cmd) { + final DiskTO disk = cmd.getDisk(); + final DataTO data = disk.getData(); try { - Connection conn = this.hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); - String vmName = cmd.getVmName(); + final String vmName = cmd.getVmName(); VM vm = null; boolean vmNotRunning = true; try { - vm = this.hypervisorResource.getVM(conn, vmName); + vm = hypervisorResource.getVM(conn, vmName); - VM.Record vmr = vm.getRecord(conn); + final VM.Record vmr = vm.getRecord(conn); vmNotRunning = vmr.powerState != VmPowerState.RUNNING; - } catch (CloudRuntimeException ex) { + } catch (final CloudRuntimeException ex) { } // if the VM is not running and we're not dealing with managed storage, just return success (nothing to do here) @@ -416,14 +416,14 @@ public class XenServerStorageProcessor implements StorageProcessor { } if (!vmNotRunning) { - VDI vdi = this.hypervisorResource.mount(conn, null, null, data.getPath()); + final VDI vdi = hypervisorResource.mount(conn, null, null, data.getPath()); // Look up all VBDs for this VDI - Set vbds = vdi.getVBDs(conn); + final Set vbds = vdi.getVBDs(conn); // Detach each VBD from its VM, and then destroy it - for (VBD vbd : vbds) { - VBD.Record vbdr = vbd.getRecord(conn); + for (final VBD vbd : vbds) { + final VBD.Record vbdr = vbd.getRecord(conn); if (vbdr.currentlyAttached) { vbd.unplug(conn); @@ -435,7 +435,7 @@ public class XenServerStorageProcessor implements StorageProcessor { // Update the VDI's label to be "detached" vdi.setNameLabel(conn, "detached"); - this.hypervisorResource.umount(conn, vdi); + hypervisorResource.umount(conn, vdi); } if (cmd.isManaged()) { @@ -443,83 +443,83 @@ public class XenServerStorageProcessor implements StorageProcessor { } return new DettachAnswer(disk); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Failed dettach volume: " + data.getPath()); return new DettachAnswer("Failed dettach volume: " + data.getPath() + ", due to " + e.toString()); } } - protected SR getSRByNameLabel(Connection conn, String nameLabel) throws BadServerResponse, XenAPIException, XmlRpcException { - Set srs = SR.getByNameLabel(conn, nameLabel); + protected SR getSRByNameLabel(final Connection conn, final String nameLabel) throws BadServerResponse, XenAPIException, XmlRpcException { + final Set srs = SR.getByNameLabel(conn, nameLabel); if (srs.size() != 1) { throw new CloudRuntimeException("storage uuid: " + nameLabel + " is not unique"); } - SR poolsr = srs.iterator().next(); + final SR poolsr = srs.iterator().next(); return poolsr; } - protected VDI createVdi(Connection conn, String vdiName, SR sr, long size) throws BadServerResponse, XenAPIException, XmlRpcException { - VDI.Record vdir = new VDI.Record(); + protected VDI createVdi(final Connection conn, final String vdiName, final SR sr, final long size) throws BadServerResponse, XenAPIException, XmlRpcException { + final VDI.Record vdir = new VDI.Record(); vdir.nameLabel = vdiName; vdir.SR = sr; vdir.type = Types.VdiType.USER; vdir.virtualSize = size; - VDI vdi = VDI.create(conn, vdir); + final VDI vdi = VDI.create(conn, vdir); return vdi; } - protected void deleteVDI(Connection conn, VDI vdi) throws BadServerResponse, XenAPIException, XmlRpcException { + protected void deleteVDI(final Connection conn, final VDI vdi) throws BadServerResponse, XenAPIException, XmlRpcException { vdi.destroy(conn); } @Override - public Answer createSnapshot(CreateObjectCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - SnapshotObjectTO snapshotTO = (SnapshotObjectTO) cmd.getData(); - long snapshotId = snapshotTO.getId(); - String snapshotName = snapshotTO.getName(); + public Answer createSnapshot(final CreateObjectCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) cmd.getData(); + final long snapshotId = snapshotTO.getId(); + final String snapshotName = snapshotTO.getName(); String details = "create snapshot operation Failed for snapshotId: " + snapshotId; String snapshotUUID = null; try { - String volumeUUID = snapshotTO.getVolume().getPath(); - VDI volume = VDI.getByUuid(conn, volumeUUID); + final String volumeUUID = snapshotTO.getVolume().getPath(); + final VDI volume = VDI.getByUuid(conn, volumeUUID); - VDI snapshot = volume.snapshot(conn, new HashMap()); + final VDI snapshot = volume.snapshot(conn, new HashMap()); if (snapshotName != null) { snapshot.setNameLabel(conn, snapshotName); } snapshotUUID = snapshot.getUuid(conn); - String preSnapshotUUID = snapshotTO.getParentSnapshotPath(); + final String preSnapshotUUID = snapshotTO.getParentSnapshotPath(); //check if it is a empty snapshot if (preSnapshotUUID != null) { - SR sr = volume.getSR(conn); - String srUUID = sr.getUuid(conn); - String type = sr.getType(conn); - Boolean isISCSI = IsISCSI(type); - String snapshotParentUUID = getVhdParent(conn, srUUID, snapshotUUID, isISCSI); + final SR sr = volume.getSR(conn); + final String srUUID = sr.getUuid(conn); + final String type = sr.getType(conn); + final Boolean isISCSI = IsISCSI(type); + final String snapshotParentUUID = getVhdParent(conn, srUUID, snapshotUUID, isISCSI); try { - String preSnapshotParentUUID = getVhdParent(conn, srUUID, preSnapshotUUID, isISCSI); + final String preSnapshotParentUUID = getVhdParent(conn, srUUID, preSnapshotUUID, isISCSI); if (snapshotParentUUID != null && snapshotParentUUID.equals(preSnapshotParentUUID)) { // this is empty snapshot, remove it snapshot.destroy(conn); snapshotUUID = preSnapshotUUID; } - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to get parent snapshot", e); } } - SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); + final SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(snapshotUUID); return new CreateObjectAnswer(newSnapshot); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); - } catch (Exception e) { + } catch (final Exception e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); } @@ -528,47 +528,47 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer deleteVolume(DeleteCommand cmd) { - DataTO volume = cmd.getData(); - Connection conn = hypervisorResource.getConnection(); + public Answer deleteVolume(final DeleteCommand cmd) { + final DataTO volume = cmd.getData(); + final Connection conn = hypervisorResource.getConnection(); String errorMsg = null; try { - VDI vdi = VDI.getByUuid(conn, volume.getPath()); + final VDI vdi = VDI.getByUuid(conn, volume.getPath()); deleteVDI(conn, vdi); return new Answer(null); - } catch (BadServerResponse e) { + } catch (final BadServerResponse e) { s_logger.debug("Failed to delete volume", e); errorMsg = e.toString(); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { s_logger.debug("Failed to delete volume", e); errorMsg = e.toString(); - } catch (XmlRpcException e) { + } catch (final XmlRpcException e) { s_logger.debug("Failed to delete volume", e); errorMsg = e.toString(); } return new Answer(null, false, errorMsg); } - protected SR getNfsSR(Connection conn, StorageFilerTO pool) { - Map deviceConfig = new HashMap(); + protected SR getNfsSR(final Connection conn, final StorageFilerTO pool) { + final Map deviceConfig = new HashMap(); try { - String server = pool.getHost(); + final String server = pool.getHost(); String serverpath = pool.getPath(); serverpath = serverpath.replace("//", "/"); - Set srs = SR.getAll(conn); - for (SR sr : srs) { + final Set srs = SR.getAll(conn); + for (final SR sr : srs) { if (!SRType.NFS.equals(sr.getType(conn))) { continue; } - Set pbds = sr.getPBDs(conn); + final Set pbds = sr.getPBDs(conn); if (pbds.isEmpty()) { continue; } - PBD pbd = pbds.iterator().next(); + final PBD pbd = pbds.iterator().next(); - Map dc = pbd.getDeviceConfig(conn); + final Map dc = pbd.getDeviceConfig(conn); if (dc == null) { continue; @@ -584,27 +584,27 @@ public class XenServerStorageProcessor implements StorageProcessor { if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { throw new CloudRuntimeException("There is a SR using the same configuration server:" + dc.get("server") + ", serverpath:" + dc.get("serverpath") + - " for pool " + pool.getUuid() + "on host:" + hypervisorResource.getHost().uuid); + " for pool " + pool.getUuid() + "on host:" + hypervisorResource.getHost().getUuid()); } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); - Host host = Host.getByUuid(conn, hypervisorResource.getHost().uuid); - Map smConfig = new HashMap(); + final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); + final Map smConfig = new HashMap(); smConfig.put("nosubdir", "true"); - SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, smConfig); + final SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, smConfig); sr.scan(conn); return sr; - } catch (XenAPIException e) { + } catch (final XenAPIException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); - } catch (XmlRpcException e) { + } catch (final XmlRpcException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); } } - protected Answer directDownloadHttpTemplate(CopyCommand cmd, DecodedDataObject srcObj, DecodedDataObject destObj) { - Connection conn = hypervisorResource.getConnection(); + protected Answer directDownloadHttpTemplate(final CopyCommand cmd, final DecodedDataObject srcObj, final DecodedDataObject destObj) { + final Connection conn = hypervisorResource.getConnection(); SR poolsr = null; VDI vdi = null; boolean result = false; @@ -617,53 +617,53 @@ public class XenServerStorageProcessor implements StorageProcessor { if (vdi == null) { throw new CloudRuntimeException("can't find volume: " + destObj.getPath()); } - String destStoreUuid = destObj.getStore().getUuid(); - Set srs = SR.getByNameLabel(conn, destStoreUuid); + final String destStoreUuid = destObj.getStore().getUuid(); + final Set srs = SR.getByNameLabel(conn, destStoreUuid); if (srs.size() != 1) { throw new CloudRuntimeException("storage uuid: " + destStoreUuid + " is not unique"); } poolsr = srs.iterator().next(); - VDI.Record vdir = vdi.getRecord(conn); - String vdiLocation = vdir.location; + final VDI.Record vdir = vdi.getRecord(conn); + final String vdiLocation = vdir.location; String pbdLocation = null; if (destObj.getStore().getScheme().equalsIgnoreCase(DataStoreProtocol.NFS.toString())) { pbdLocation = "/run/sr-mount/" + poolsr.getUuid(conn); } else { - Set pbds = poolsr.getPBDs(conn); + final Set pbds = poolsr.getPBDs(conn); if (pbds.size() != 1) { throw new CloudRuntimeException("Don't how to handle multiple pbds:" + pbds.size() + " for sr: " + poolsr.getUuid(conn)); } - PBD pbd = pbds.iterator().next(); - Map deviceCfg = pbd.getDeviceConfig(conn); + final PBD pbd = pbds.iterator().next(); + final Map deviceCfg = pbd.getDeviceConfig(conn); pbdLocation = deviceCfg.get("location"); } if (pbdLocation == null) { throw new CloudRuntimeException("Can't get pbd location"); } - String vdiPath = pbdLocation + "/" + vdiLocation + ".vhd"; + final String vdiPath = pbdLocation + "/" + vdiLocation + ".vhd"; //download a url into vdipath //downloadHttpToLocalFile(vdiPath, template.getPath()); hypervisorResource.callHostPlugin(conn, "storagePlugin", "downloadTemplateFromUrl", "destPath", vdiPath, "srcUrl", srcObj.getPath()); result = true; //return new CopyCmdAnswer(cmd, vdi.getUuid(conn)); - } catch (BadServerResponse e) { + } catch (final BadServerResponse e) { s_logger.debug("Failed to download template", e); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { s_logger.debug("Failed to download template", e); - } catch (XmlRpcException e) { + } catch (final XmlRpcException e) { s_logger.debug("Failed to download template", e); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to download template", e); } finally { if (!result && vdi != null) { try { vdi.destroy(conn); - } catch (BadServerResponse e) { + } catch (final BadServerResponse e) { s_logger.debug("Failed to cleanup newly created vdi"); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { s_logger.debug("Failed to cleanup newly created vdi"); - } catch (XmlRpcException e) { + } catch (final XmlRpcException e) { s_logger.debug("Failed to cleanup newly created vdi"); } } @@ -671,61 +671,61 @@ public class XenServerStorageProcessor implements StorageProcessor { return new Answer(cmd, false, "Failed to download template"); } - protected Answer execute(AttachPrimaryDataStoreCmd cmd) { - String dataStoreUri = cmd.getDataStore(); - Connection conn = hypervisorResource.getConnection(); + protected Answer execute(final AttachPrimaryDataStoreCmd cmd) { + final String dataStoreUri = cmd.getDataStore(); + final Connection conn = hypervisorResource.getConnection(); try { - DecodedDataObject obj = Decoder.decode(dataStoreUri); + final DecodedDataObject obj = Decoder.decode(dataStoreUri); - DecodedDataStore store = obj.getStore(); + final DecodedDataStore store = obj.getStore(); - SR sr = hypervisorResource.getStorageRepository(conn, store.getUuid()); + final SR sr = hypervisorResource.getStorageRepository(conn, store.getUuid()); hypervisorResource.setupHeartbeatSr(conn, sr, false); - long capacity = sr.getPhysicalSize(conn); - long available = capacity - sr.getPhysicalUtilisation(conn); + final long capacity = sr.getPhysicalSize(conn); + final long available = capacity - sr.getPhysicalUtilisation(conn); if (capacity == -1) { - String msg = "Pool capacity is -1! pool: "; + final String msg = "Pool capacity is -1! pool: "; s_logger.warn(msg); return new Answer(cmd, false, msg); } - AttachPrimaryDataStoreAnswer answer = new AttachPrimaryDataStoreAnswer(cmd); + final AttachPrimaryDataStoreAnswer answer = new AttachPrimaryDataStoreAnswer(cmd); answer.setCapacity(capacity); answer.setUuid(sr.getUuid(conn)); answer.setAvailable(available); return answer; - } catch (XenAPIException e) { - String msg = "AttachPrimaryDataStoreCmd add XenAPIException:" + e.toString(); + } catch (final XenAPIException e) { + final String msg = "AttachPrimaryDataStoreCmd add XenAPIException:" + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); - } catch (Exception e) { - String msg = "AttachPrimaryDataStoreCmd failed:" + e.getMessage(); + } catch (final Exception e) { + final String msg = "AttachPrimaryDataStoreCmd failed:" + e.getMessage(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } - protected boolean IsISCSI(String type) { + protected boolean IsISCSI(final String type) { return SRType.LVMOHBA.equals(type) || SRType.LVMOISCSI.equals(type) || SRType.LVM.equals(type); } - private String copy_vhd_from_secondarystorage(Connection conn, String mountpoint, String sruuid, int wait) { - String nameLabel = "cloud-" + UUID.randomUUID().toString(); - String results = + private String copy_vhd_from_secondarystorage(final Connection conn, final String mountpoint, final String sruuid, final int wait) { + final String nameLabel = "cloud-" + UUID.randomUUID().toString(); + final String results = hypervisorResource.callHostPluginAsync(conn, "vmopspremium", "copy_vhd_from_secondarystorage", wait, "mountpoint", mountpoint, "sruuid", sruuid, "namelabel", nameLabel); String errMsg = null; if (results == null || results.isEmpty()) { errMsg = "copy_vhd_from_secondarystorage return null"; } else { - String[] tmp = results.split("#"); - String status = tmp[0]; + final String[] tmp = results.split("#"); + final String status = tmp[0]; if (status.equals("0")) { return tmp[1]; } else { errMsg = tmp[1]; } } - String source = mountpoint.substring(mountpoint.lastIndexOf('/') + 1); + final String source = mountpoint.substring(mountpoint.lastIndexOf('/') + 1); if (hypervisorResource.killCopyProcess(conn, source)) { destroyVDIbyNameLabel(conn, nameLabel); } @@ -733,35 +733,35 @@ public class XenServerStorageProcessor implements StorageProcessor { throw new CloudRuntimeException(errMsg); } - private void destroyVDIbyNameLabel(Connection conn, String nameLabel) { + private void destroyVDIbyNameLabel(final Connection conn, final String nameLabel) { try { - Set vdis = VDI.getByNameLabel(conn, nameLabel); + final Set vdis = VDI.getByNameLabel(conn, nameLabel); if (vdis.size() != 1) { s_logger.warn("destoryVDIbyNameLabel failed due to there are " + vdis.size() + " VDIs with name " + nameLabel); return; } - for (VDI vdi : vdis) { + for (final VDI vdi : vdis) { try { vdi.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { } } - } catch (Exception e) { + } catch (final Exception e) { } } - protected VDI getVDIbyUuid(Connection conn, String uuid) { + protected VDI getVDIbyUuid(final Connection conn, final String uuid) { try { return VDI.getByUuid(conn, uuid); - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() + " :VDI getByUuid for uuid: " + uuid + " failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Catch Exception " + e.getClass().getName() + " :VDI getByUuid for uuid: " + uuid + " failed due to " + e.toString(); s_logger.debug(msg); throw new CloudRuntimeException(msg, e); } } - protected String getVhdParent(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI) { - String parentUuid = + protected String getVhdParent(final Connection conn, final String primaryStorageSRUuid, final String snapshotUuid, final Boolean isISCSI) { + final String parentUuid = hypervisorResource.callHostPlugin(conn, "vmopsSnapshot", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", snapshotUuid, "isISCSI", isISCSI.toString()); @@ -774,20 +774,20 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer copyTemplateToPrimaryStorage(CopyCommand cmd) { - DataTO srcDataTo = cmd.getSrcTO(); - DataTO destDataTo = cmd.getDestTO(); - int wait = cmd.getWait(); - DataStoreTO srcDataStoreTo = srcDataTo.getDataStore(); + public Answer copyTemplateToPrimaryStorage(final CopyCommand cmd) { + final DataTO srcDataTo = cmd.getSrcTO(); + final DataTO destDataTo = cmd.getDestTO(); + final int wait = cmd.getWait(); + final DataStoreTO srcDataStoreTo = srcDataTo.getDataStore(); try { - if ((srcDataStoreTo instanceof NfsTO) && (srcDataTo.getObjectType() == DataObjectType.TEMPLATE)) { - NfsTO srcImageStore = (NfsTO) srcDataStoreTo; - TemplateObjectTO srcTemplateObjectTo = (TemplateObjectTO) srcDataTo; - String storeUrl = srcImageStore.getUrl(); - URI uri = new URI(storeUrl); - String tmplPath = uri.getHost() + ":" + uri.getPath() + "/" + srcDataTo.getPath(); - DataStoreTO destDataStoreTo = destDataTo.getDataStore(); + if (srcDataStoreTo instanceof NfsTO && srcDataTo.getObjectType() == DataObjectType.TEMPLATE) { + final NfsTO srcImageStore = (NfsTO) srcDataStoreTo; + final TemplateObjectTO srcTemplateObjectTo = (TemplateObjectTO) srcDataTo; + final String storeUrl = srcImageStore.getUrl(); + final URI uri = new URI(storeUrl); + final String tmplPath = uri.getHost() + ":" + uri.getPath() + "/" + srcDataTo.getPath(); + final DataStoreTO destDataStoreTo = destDataTo.getDataStore(); boolean managed = false; String storageHost = null; @@ -798,9 +798,9 @@ public class XenServerStorageProcessor implements StorageProcessor { String chapInitiatorSecret = null; if (destDataStoreTo instanceof PrimaryDataStoreTO) { - PrimaryDataStoreTO destPrimaryDataStoreTo = (PrimaryDataStoreTO)destDataStoreTo; + final PrimaryDataStoreTO destPrimaryDataStoreTo = (PrimaryDataStoreTO)destDataStoreTo; - Map details = destPrimaryDataStoreTo.getDetails(); + final Map details = destPrimaryDataStoreTo.getDetails(); if (details != null) { managed = Boolean.parseBoolean(details.get(PrimaryDataStoreTO.MANAGED)); @@ -816,12 +816,12 @@ public class XenServerStorageProcessor implements StorageProcessor { } } - Connection conn = hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); final SR sr; if (managed) { - Map details = new HashMap(); + final Map details = new HashMap(); details.put(DiskTO.STORAGE_HOST, storageHost); details.put(DiskTO.IQN, managedStoragePoolName); @@ -831,11 +831,11 @@ public class XenServerStorageProcessor implements StorageProcessor { sr = hypervisorResource.prepareManagedSr(conn, details); } else { - String srName = destDataStoreTo.getUuid(); - Set srs = SR.getByNameLabel(conn, srName); + final String srName = destDataStoreTo.getUuid(); + final Set srs = SR.getByNameLabel(conn, srName); if (srs.size() != 1) { - String msg = "There are " + srs.size() + " SRs with same name: " + srName; + final String msg = "There are " + srs.size() + " SRs with same name: " + srName; s_logger.warn(msg); @@ -845,19 +845,19 @@ public class XenServerStorageProcessor implements StorageProcessor { } } - String srUuid = sr.getUuid(conn); - String tmplUuid = copy_vhd_from_secondarystorage(conn, tmplPath, srUuid, wait); - VDI tmplVdi = getVDIbyUuid(conn, tmplUuid); + final String srUuid = sr.getUuid(conn); + final String tmplUuid = copy_vhd_from_secondarystorage(conn, tmplPath, srUuid, wait); + final VDI tmplVdi = getVDIbyUuid(conn, tmplUuid); final String uuidToReturn; - Long physicalSize = tmplVdi.getPhysicalUtilisation(conn); + final Long physicalSize = tmplVdi.getPhysicalUtilisation(conn); if (managed) { uuidToReturn = tmplUuid; tmplVdi.setNameLabel(conn, managedStoragePoolRootVolumeName); } else { - VDI snapshotVdi = tmplVdi.snapshot(conn, new HashMap()); + final VDI snapshotVdi = tmplVdi.snapshot(conn, new HashMap()); uuidToReturn = snapshotVdi.getUuid(conn); @@ -870,10 +870,10 @@ public class XenServerStorageProcessor implements StorageProcessor { try { Thread.sleep(5000); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { } - TemplateObjectTO newVol = new TemplateObjectTO(); + final TemplateObjectTO newVol = new TemplateObjectTO(); newVol.setUuid(uuidToReturn); newVol.setPath(uuidToReturn); @@ -884,8 +884,8 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(newVol); } - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() + " for template + " + " due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Catch Exception " + e.getClass().getName() + " for template + " + " due to " + e.toString(); s_logger.warn(msg, e); @@ -896,13 +896,13 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer createVolume(CreateObjectCommand cmd) { - DataTO data = cmd.getData(); - VolumeObjectTO volume = (VolumeObjectTO) data; + public Answer createVolume(final CreateObjectCommand cmd) { + final DataTO data = cmd.getData(); + final VolumeObjectTO volume = (VolumeObjectTO) data; try { - Connection conn = hypervisorResource.getConnection(); - SR poolSr = hypervisorResource.getStorageRepository(conn, data.getDataStore().getUuid()); + final Connection conn = hypervisorResource.getConnection(); + final SR poolSr = hypervisorResource.getStorageRepository(conn, data.getDataStore().getUuid()); VDI.Record vdir = new VDI.Record(); vdir.nameLabel = volume.getName(); vdir.SR = poolSr; @@ -913,24 +913,24 @@ public class XenServerStorageProcessor implements StorageProcessor { vdi = VDI.create(conn, vdir); vdir = vdi.getRecord(conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setName(vdir.nameLabel); newVol.setSize(vdir.virtualSize); newVol.setPath(vdir.uuid); return new CreateObjectAnswer(newVol); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("create volume failed: " + e.toString()); return new CreateObjectAnswer(e.toString()); } } @Override - public Answer cloneVolumeFromBaseTemplate(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); - VolumeObjectTO volume = (VolumeObjectTO) destData; + public Answer cloneVolumeFromBaseTemplate(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO destData = cmd.getDestTO(); + final VolumeObjectTO volume = (VolumeObjectTO) destData; VDI vdi = null; try { VDI tmpltvdi = null; @@ -943,43 +943,43 @@ public class XenServerStorageProcessor implements StorageProcessor { vdir = vdi.getRecord(conn); s_logger.debug("Succesfully created VDI: Uuid = " + vdir.uuid); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setName(vdir.nameLabel); newVol.setSize(vdir.virtualSize); newVol.setPath(vdir.uuid); return new CopyCmdAnswer(newVol); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to create volume; Pool=" + destData + "; Disk: ", e); return new CopyCmdAnswer(e.toString()); } } @Override - public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); - int wait = cmd.getWait(); - VolumeObjectTO srcVolume = (VolumeObjectTO) srcData; - VolumeObjectTO destVolume = (VolumeObjectTO) destData; - DataStoreTO srcStore = srcVolume.getDataStore(); + public Answer copyVolumeFromImageCacheToPrimary(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO destData = cmd.getDestTO(); + final int wait = cmd.getWait(); + final VolumeObjectTO srcVolume = (VolumeObjectTO) srcData; + final VolumeObjectTO destVolume = (VolumeObjectTO) destData; + final DataStoreTO srcStore = srcVolume.getDataStore(); if (srcStore instanceof NfsTO) { - NfsTO nfsStore = (NfsTO) srcStore; + final NfsTO nfsStore = (NfsTO) srcStore; try { - SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, destVolume.getDataStore().getUuid()); - String srUuid = primaryStoragePool.getUuid(conn); - URI uri = new URI(nfsStore.getUrl()); - String volumePath = uri.getHost() + ":" + uri.getPath() + nfsStore.getPathSeparator() + srcVolume.getPath(); - String uuid = copy_vhd_from_secondarystorage(conn, volumePath, srUuid, wait); - VolumeObjectTO newVol = new VolumeObjectTO(); + final SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, destVolume.getDataStore().getUuid()); + final String srUuid = primaryStoragePool.getUuid(conn); + final URI uri = new URI(nfsStore.getUrl()); + final String volumePath = uri.getHost() + ":" + uri.getPath() + nfsStore.getPathSeparator() + srcVolume.getPath(); + final String uuid = copy_vhd_from_secondarystorage(conn, volumePath, srUuid, wait); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(uuid); newVol.setSize(srcVolume.getSize()); return new CopyCmdAnswer(newVol); - } 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.warn(msg, e); return new CopyCmdAnswer(e.toString()); } @@ -990,18 +990,18 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer copyVolumeFromPrimaryToSecondary(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - VolumeObjectTO srcVolume = (VolumeObjectTO) cmd.getSrcTO(); - VolumeObjectTO destVolume = (VolumeObjectTO) cmd.getDestTO(); - int wait = cmd.getWait(); - DataStoreTO destStore = destVolume.getDataStore(); + public Answer copyVolumeFromPrimaryToSecondary(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final VolumeObjectTO srcVolume = (VolumeObjectTO) cmd.getSrcTO(); + final VolumeObjectTO destVolume = (VolumeObjectTO) cmd.getDestTO(); + final int wait = cmd.getWait(); + final DataStoreTO destStore = destVolume.getDataStore(); if (destStore instanceof NfsTO) { SR secondaryStorage = null; try { - NfsTO nfsStore = (NfsTO) destStore; - URI uri = new URI(nfsStore.getUrl()); + final NfsTO nfsStore = (NfsTO) destStore; + final URI uri = new URI(nfsStore.getUrl()); // Create the volume folder if (!hypervisorResource.createSecondaryStorageFolder(conn, uri.getHost() + ":" + uri.getPath(), destVolume.getPath())) { throw new InternalErrorException("Failed to create the volume folder."); @@ -1010,16 +1010,16 @@ public class XenServerStorageProcessor implements StorageProcessor { // Create a SR for the volume UUID folder secondaryStorage = hypervisorResource.createNfsSRbyURI(conn, new URI(nfsStore.getUrl() + nfsStore.getPathSeparator() + destVolume.getPath()), false); // Look up the volume on the source primary storage pool - VDI srcVdi = getVDIbyUuid(conn, srcVolume.getPath()); + final VDI srcVdi = getVDIbyUuid(conn, srcVolume.getPath()); // Copy the volume to secondary storage - VDI destVdi = hypervisorResource.cloudVDIcopy(conn, srcVdi, secondaryStorage, wait); - String destVolumeUUID = destVdi.getUuid(conn); + final VDI destVdi = hypervisorResource.cloudVDIcopy(conn, srcVdi, secondaryStorage, wait); + final String destVolumeUUID = destVdi.getUuid(conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(destVolume.getPath() + nfsStore.getPathSeparator() + destVolumeUUID + ".vhd"); newVol.setSize(srcVolume.getSize()); return new CopyCmdAnswer(newVol); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to copy volume to secondary: " + e.toString()); return new CopyCmdAnswer("Failed to copy volume to secondary: " + e.toString()); } finally { @@ -1029,7 +1029,7 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer("unsupported protocol"); } - boolean swiftUpload(Connection conn, SwiftTO swift, String container, String ldir, String lfilename, Boolean isISCSI, int wait) { + boolean swiftUpload(final Connection conn, final SwiftTO swift, final String container, final String ldir, final String lfilename, final Boolean isISCSI, final int wait) { String result = null; try { result = @@ -1038,23 +1038,23 @@ public class XenServerStorageProcessor implements StorageProcessor { if (result != null && result.equals("true")) { return true; } - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("swift upload failed due to " + e.toString(), e); } return false; } - protected String deleteSnapshotBackup(Connection conn, String localMountPoint, String path, String secondaryStorageMountPath, String backupUUID) { + protected String deleteSnapshotBackup(final Connection conn, final String localMountPoint, final String path, final String secondaryStorageMountPath, final String backupUUID) { // If anybody modifies the formatting below again, I'll skin them - String result = + final String result = hypervisorResource.callHostPlugin(conn, "vmopsSnapshot", "deleteSnapshotBackup", "backupUUID", backupUUID, "path", path, "secondaryStorageMountPath", secondaryStorageMountPath, "localMountPoint", localMountPoint); return result; } - public String swiftBackupSnapshot(Connection conn, SwiftTO swift, String srUuid, String snapshotUuid, String container, Boolean isISCSI, int wait) { + public String swiftBackupSnapshot(final Connection conn, final SwiftTO swift, final String srUuid, final String snapshotUuid, final String container, final Boolean isISCSI, final int wait) { String lfilename; String ldir; if (isISCSI) { @@ -1069,7 +1069,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } protected String backupSnapshotToS3(final Connection connection, final S3TO s3, final String srUuid, final String folder, final String snapshotUuid, - final Boolean iSCSIFlag, final int wait) { + final Boolean iSCSIFlag, final int wait) { final String filename = iSCSIFlag ? "VHD-" + snapshotUuid : snapshotUuid + ".vhd"; final String dir = (iSCSIFlag ? "/dev/VG_XenStorage-" : "/var/run/sr-mount/") + srUuid; @@ -1090,7 +1090,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } return null; - } catch (Exception e) { + } catch (final Exception e) { s_logger.error(String.format("S3 upload failed of snapshot %1$s due to %2$s.", snapshotUuid, e.toString()), e); } @@ -1098,8 +1098,8 @@ public class XenServerStorageProcessor implements StorageProcessor { } - protected Long getSnapshotSize(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI, int wait) { - String physicalSize = hypervisorResource.callHostPluginAsync(conn, "vmopsSnapshot", "getSnapshotSize", wait, + protected Long getSnapshotSize(final Connection conn, final String primaryStorageSRUuid, final String snapshotUuid, final Boolean isISCSI, final int wait) { + final String physicalSize = hypervisorResource.callHostPluginAsync(conn, "vmopsSnapshot", "getSnapshotSize", wait, "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", snapshotUuid, "isISCSI", isISCSI.toString()); if (physicalSize == null || physicalSize.isEmpty()) { return (long) 0; @@ -1108,8 +1108,8 @@ public class XenServerStorageProcessor implements StorageProcessor { } } - protected String backupSnapshot(Connection conn, String primaryStorageSRUuid, String localMountPoint, String path, String secondaryStorageMountPath, - String snapshotUuid, String prevBackupUuid, Boolean isISCSI, int wait) { + protected String backupSnapshot(final Connection conn, final String primaryStorageSRUuid, final String localMountPoint, final String path, final String secondaryStorageMountPath, + final String snapshotUuid, String prevBackupUuid, final Boolean isISCSI, final int wait) { String backupSnapshotUuid = null; if (prevBackupUuid == null) { @@ -1118,8 +1118,8 @@ public class XenServerStorageProcessor implements StorageProcessor { // Each argument is put in a separate line for readability. // Using more lines does not harm the environment. - String backupUuid = UUID.randomUUID().toString(); - String results = + final String backupUuid = UUID.randomUUID().toString(); + final String results = hypervisorResource.callHostPluginAsync(conn, "vmopsSnapshot", "backupSnapshot", wait, "primaryStorageSRUuid", primaryStorageSRUuid, "path", path, "secondaryStorageMountPath", secondaryStorageMountPath, "snapshotUuid", snapshotUuid, "prevBackupUuid", prevBackupUuid, "backupUuid", backupUuid, "isISCSI", isISCSI.toString(), "localMountPoint", localMountPoint); @@ -1130,8 +1130,8 @@ public class XenServerStorageProcessor implements StorageProcessor { secondaryStorageMountPath + " due to null"; } else { - String[] tmp = results.split("#"); - String status = tmp[0]; + final String[] tmp = results.split("#"); + final String status = tmp[0]; backupSnapshotUuid = tmp[1]; // status == "1" if and only if backupSnapshotUuid != null // So we don't rely on status value but return backupSnapshotUuid as an @@ -1145,45 +1145,45 @@ public class XenServerStorageProcessor implements StorageProcessor { secondaryStorageMountPath + " due to " + tmp[1]; } } - String source = backupUuid + ".vhd"; + final String source = backupUuid + ".vhd"; hypervisorResource.killCopyProcess(conn, source); s_logger.warn(errMsg); throw new CloudRuntimeException(errMsg); } - protected boolean destroySnapshotOnPrimaryStorageExceptThis(Connection conn, String volumeUuid, String avoidSnapshotUuid) { + protected boolean destroySnapshotOnPrimaryStorageExceptThis(final Connection conn, final String volumeUuid, final String avoidSnapshotUuid) { try { - VDI volume = getVDIbyUuid(conn, volumeUuid); + final VDI volume = getVDIbyUuid(conn, volumeUuid); if (volume == null) { throw new InternalErrorException("Could not destroy snapshot on volume " + volumeUuid + " due to can not find it"); } - Set snapshots = volume.getSnapshots(conn); - for (VDI snapshot : snapshots) { + final Set snapshots = volume.getSnapshots(conn); + for (final VDI snapshot : snapshots) { try { if (!snapshot.getUuid(conn).equals(avoidSnapshotUuid)) { snapshot.destroy(conn); } - } catch (Exception e) { - String msg = "Destroying snapshot: " + snapshot + " on primary storage failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Destroying snapshot: " + snapshot + " on primary storage failed due to " + e.toString(); s_logger.warn(msg, e); } } s_logger.debug("Successfully destroyed snapshot on volume: " + volumeUuid + " execept this current snapshot " + avoidSnapshotUuid); return true; - } catch (XenAPIException e) { - String msg = "Destroying snapshot on volume: " + volumeUuid + " execept this current snapshot " + avoidSnapshotUuid + " failed due to " + e.toString(); + } catch (final XenAPIException e) { + final String msg = "Destroying snapshot on volume: " + volumeUuid + " execept this current snapshot " + avoidSnapshotUuid + " failed due to " + e.toString(); s_logger.error(msg, e); - } catch (Exception e) { - String msg = "Destroying snapshot on volume: " + volumeUuid + " execept this current snapshot " + avoidSnapshotUuid + " failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Destroying snapshot on volume: " + volumeUuid + " execept this current snapshot " + avoidSnapshotUuid + " failed due to " + e.toString(); s_logger.warn(msg, e); } return false; } - private boolean destroySnapshotOnPrimaryStorage(Connection conn, String lastSnapshotUuid) { + private boolean destroySnapshotOnPrimaryStorage(final Connection conn, final String lastSnapshotUuid) { try { - VDI snapshot = getVDIbyUuid(conn, lastSnapshotUuid); + final VDI snapshot = getVDIbyUuid(conn, lastSnapshotUuid); if (snapshot == null) { // since this is just used to cleanup leftover bad snapshots, no need to throw exception s_logger.warn("Could not destroy snapshot " + lastSnapshotUuid + " due to can not find it"); @@ -1191,24 +1191,24 @@ public class XenServerStorageProcessor implements StorageProcessor { } snapshot.destroy(conn); return true; - } catch (XenAPIException e) { - String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); + } catch (final XenAPIException e) { + final String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); s_logger.error(msg, e); - } catch (Exception e) { - String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); s_logger.warn(msg, e); } return false; } @Override - public Answer backupSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO cacheData = cmd.getCacheTO(); - DataTO destData = cmd.getDestTO(); - int wait = cmd.getWait(); - String primaryStorageNameLabel = srcData.getDataStore().getUuid(); + public Answer backupSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO cacheData = cmd.getCacheTO(); + final DataTO destData = cmd.getDestTO(); + final int wait = cmd.getWait(); + final String primaryStorageNameLabel = srcData.getDataStore().getUuid(); String secondaryStorageUrl = null; NfsTO cacheStore = null; String destPath = null; @@ -1222,58 +1222,58 @@ public class XenServerStorageProcessor implements StorageProcessor { destPath = destData.getPath(); } - SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData; - SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData; - String snapshotUuid = snapshotTO.getPath(); - String volumeUuid = snapshotTO.getVolume().getPath(); + final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData; + final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData; + final String snapshotUuid = snapshotTO.getPath(); + final String volumeUuid = snapshotTO.getVolume().getPath(); - String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); - String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); + final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); + final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); // By default assume failure String details = null; String snapshotBackupUuid = null; Long physicalSize = null; - Map options = cmd.getOptions(); + final Map options = cmd.getOptions(); boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot")); boolean result = false; try { - SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } - String psUuid = primaryStorageSR.getUuid(conn); - Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); + final String psUuid = primaryStorageSR.getUuid(conn); + final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); - VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); + final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); String snapshotPaUuid = null; if (prevSnapshotUuid != null && !fullbackup) { try { snapshotPaUuid = getVhdParent(conn, psUuid, snapshotUuid, isISCSI); if (snapshotPaUuid != null) { - String snashotPaPaPaUuid = getVhdParent(conn, psUuid, snapshotPaUuid, isISCSI); - String prevSnashotPaUuid = getVhdParent(conn, psUuid, prevSnapshotUuid, isISCSI); + final String snashotPaPaPaUuid = getVhdParent(conn, psUuid, snapshotPaUuid, isISCSI); + final String prevSnashotPaUuid = getVhdParent(conn, psUuid, prevSnapshotUuid, isISCSI); if (snashotPaPaPaUuid != null && prevSnashotPaUuid != null && prevSnashotPaUuid.equals(snashotPaPaPaUuid)) { fullbackup = false; } else { fullbackup = true; } } - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to get parent snapshots, take full snapshot", e); fullbackup = true; } } - URI uri = new URI(secondaryStorageUrl); - String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - DataStoreTO destStore = destData.getDataStore(); - String folder = destPath; + final URI uri = new URI(secondaryStorageUrl); + final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); + final DataStoreTO destStore = destData.getDataStore(); + final String folder = destPath; String finalPath = null; - String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); + final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); if (fullbackup) { // the first snapshot is always a full snapshot @@ -1282,25 +1282,25 @@ public class XenServerStorageProcessor implements StorageProcessor { s_logger.warn(details); return new CopyCmdAnswer(details); } - String snapshotMountpoint = secondaryStorageUrl + "/" + folder; + final String snapshotMountpoint = secondaryStorageUrl + "/" + folder; SR snapshotSr = null; try { snapshotSr = hypervisorResource.createNfsSRbyURI(conn, new URI(snapshotMountpoint), false); - VDI backedVdi = hypervisorResource.cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait); + final VDI backedVdi = hypervisorResource.cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait); snapshotBackupUuid = backedVdi.getUuid(conn); - String primarySRuuid = snapshotSr.getUuid(conn); + final String primarySRuuid = snapshotSr.getUuid(conn); physicalSize = getSnapshotSize(conn, primarySRuuid, snapshotBackupUuid, isISCSI, wait); if (destStore instanceof SwiftTO) { try { - String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); - String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); - String swiftPath = container + File.separator + destSnapshotName; + final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); + final String swiftPath = container + File.separator + destSnapshotName; finalPath = swiftPath; } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to delete snapshot on cache storages", e); } } @@ -1314,7 +1314,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to delete snapshot on cache storages", e); } } @@ -1329,9 +1329,9 @@ public class XenServerStorageProcessor implements StorageProcessor { } } } else { - String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); + final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); if (destStore instanceof SwiftTO) { - String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait); @@ -1342,10 +1342,10 @@ public class XenServerStorageProcessor implements StorageProcessor { throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed"); } } else { - String results = + final String results = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait); - String[] tmp = results.split("#"); + final String[] tmp = results.split("#"); snapshotBackupUuid = tmp[1]; physicalSize = Long.parseLong(tmp[2]); finalPath = folder + cacheStore.getPathSeparator() + snapshotBackupUuid; @@ -1354,7 +1354,7 @@ public class XenServerStorageProcessor implements StorageProcessor { // delete primary snapshots with only the last one left destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); - SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); + final SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(finalPath); newSnapshot.setPhysicalSize(physicalSize); if (fullbackup) { @@ -1364,10 +1364,10 @@ public class XenServerStorageProcessor implements StorageProcessor { } result = true; return new CopyCmdAnswer(newSnapshot); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); - } catch (Exception e) { + } catch (final Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); } finally { @@ -1375,7 +1375,7 @@ public class XenServerStorageProcessor implements StorageProcessor { // remove last bad primary snapshot when exception happens try { destroySnapshotOnPrimaryStorage(conn, snapshotUuid); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("clean up snapshot failed", e); } } @@ -1385,17 +1385,17 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer createTemplateFromVolume(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - VolumeObjectTO volume = (VolumeObjectTO) cmd.getSrcTO(); - TemplateObjectTO template = (TemplateObjectTO) cmd.getDestTO(); - NfsTO destStore = (NfsTO) cmd.getDestTO().getDataStore(); - int wait = cmd.getWait(); + public Answer createTemplateFromVolume(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final VolumeObjectTO volume = (VolumeObjectTO) cmd.getSrcTO(); + final TemplateObjectTO template = (TemplateObjectTO) cmd.getDestTO(); + final NfsTO destStore = (NfsTO) cmd.getDestTO().getDataStore(); + final int wait = cmd.getWait(); - String secondaryStoragePoolURL = destStore.getUrl(); - String volumeUUID = volume.getPath(); + final String secondaryStoragePoolURL = destStore.getUrl(); + final String volumeUUID = volume.getPath(); - String userSpecifiedName = template.getName(); + final String userSpecifiedName = template.getName(); String details = null; SR tmpltSR = null; @@ -1403,7 +1403,7 @@ public class XenServerStorageProcessor implements StorageProcessor { String secondaryStorageMountPath = null; String installPath = null; try { - URI uri = new URI(secondaryStoragePoolURL); + final URI uri = new URI(secondaryStoragePoolURL); secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); installPath = template.getPath(); if (!hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { @@ -1412,25 +1412,25 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(details); } - VDI vol = getVDIbyUuid(conn, volumeUUID); + final VDI vol = getVDIbyUuid(conn, volumeUUID); // create template SR - URI tmpltURI = new URI(secondaryStoragePoolURL + "/" + installPath); + final URI tmpltURI = new URI(secondaryStoragePoolURL + "/" + installPath); tmpltSR = hypervisorResource.createNfsSRbyURI(conn, tmpltURI, false); // copy volume to template SR - VDI tmpltVDI = hypervisorResource.cloudVDIcopy(conn, vol, tmpltSR, wait); + final VDI tmpltVDI = hypervisorResource.cloudVDIcopy(conn, vol, tmpltSR, wait); // scan makes XenServer pick up VDI physicalSize tmpltSR.scan(conn); if (userSpecifiedName != null) { tmpltVDI.setNameLabel(conn, userSpecifiedName); } - String tmpltUUID = tmpltVDI.getUuid(conn); - String tmpltFilename = tmpltUUID + ".vhd"; - long virtualSize = tmpltVDI.getVirtualSize(conn); - long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); + final String tmpltUUID = tmpltVDI.getUuid(conn); + final String tmpltFilename = tmpltUUID + ".vhd"; + final long virtualSize = tmpltVDI.getVirtualSize(conn); + final long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); // create the template.properties file - String templatePath = secondaryStorageMountPath + "/" + installPath; + final String templatePath = secondaryStorageMountPath + "/" + installPath; result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, template.getId()); @@ -1440,15 +1440,15 @@ public class XenServerStorageProcessor implements StorageProcessor { installPath = installPath + "/" + tmpltFilename; hypervisorResource.removeSR(conn, tmpltSR); tmpltSR = null; - TemplateObjectTO newTemplate = new TemplateObjectTO(); + final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(installPath); newTemplate.setFormat(ImageFormat.VHD); newTemplate.setSize(virtualSize); newTemplate.setPhysicalSize(physicalSize); newTemplate.setName(tmpltUUID); - CopyCmdAnswer answer = new CopyCmdAnswer(newTemplate); + final CopyCmdAnswer answer = new CopyCmdAnswer(newTemplate); return answer; - } catch (Exception e) { + } catch (final Exception e) { if (tmpltSR != null) { hypervisorResource.removeSR(conn, tmpltSR); } @@ -1462,17 +1462,17 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer createTemplateFromSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); + public Answer createTemplateFromSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); - SnapshotObjectTO snapshotObjTO = (SnapshotObjectTO)cmd.getSrcTO(); - TemplateObjectTO templateObjTO = (TemplateObjectTO)cmd.getDestTO(); + final SnapshotObjectTO snapshotObjTO = (SnapshotObjectTO)cmd.getSrcTO(); + final TemplateObjectTO templateObjTO = (TemplateObjectTO)cmd.getDestTO(); if (!(snapshotObjTO.getDataStore() instanceof PrimaryDataStoreTO) || !(templateObjTO.getDataStore() instanceof NfsTO)) { return null; } - String userSpecifiedTemplateName = templateObjTO.getName(); + final String userSpecifiedTemplateName = templateObjTO.getName(); NfsTO destStore = null; URI destUri = null; @@ -1481,7 +1481,7 @@ public class XenServerStorageProcessor implements StorageProcessor { destStore = (NfsTO)templateObjTO.getDataStore(); destUri = new URI(destStore.getUrl()); - } catch (Exception ex) { + } catch (final Exception ex) { s_logger.debug("Invalid URI", ex); return new CopyCmdAnswer("Invalid URI: " + ex.toString()); @@ -1490,37 +1490,37 @@ public class XenServerStorageProcessor implements StorageProcessor { SR srcSr = null; SR destSr = null; - String destDir = templateObjTO.getPath(); + final String destDir = templateObjTO.getPath(); VDI destVdi = null; boolean result = false; try { - Map srcDetails = cmd.getOptions(); + final Map srcDetails = cmd.getOptions(); - String iScsiName = srcDetails.get(DiskTO.IQN); - String storageHost = srcDetails.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET); + final String iScsiName = srcDetails.get(DiskTO.IQN); + final String storageHost = srcDetails.get(DiskTO.STORAGE_HOST); + final String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET); srcSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true); - String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); + final String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); if (!hypervisorResource.createSecondaryStorageFolder(conn, destNfsPath, destDir)) { - String details = " Failed to create folder " + destDir + " in secondary storage"; + final String details = " Failed to create folder " + destDir + " in secondary storage"; s_logger.warn(details); return new CopyCmdAnswer(details); } - URI templateUri = new URI(destStore.getUrl() + "/" + destDir); + final URI templateUri = new URI(destStore.getUrl() + "/" + destDir); destSr = hypervisorResource.createNfsSRbyURI(conn, templateUri, false); // there should only be one VDI in this SR - VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); + final VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); destVdi = srcVdi.copy(conn, destSr); @@ -1531,10 +1531,10 @@ public class XenServerStorageProcessor implements StorageProcessor { destVdi.setNameLabel(conn, userSpecifiedTemplateName); } - String templateUuid = destVdi.getUuid(conn); - String templateFilename = templateUuid + ".vhd"; - long virtualSize = destVdi.getVirtualSize(conn); - long physicalSize = destVdi.getPhysicalUtilisation(conn); + final String templateUuid = destVdi.getUuid(conn); + final String templateFilename = templateUuid + ".vhd"; + final long virtualSize = destVdi.getVirtualSize(conn); + final long physicalSize = destVdi.getPhysicalUtilisation(conn); // create the template.properties file String templatePath = destNfsPath + "/" + destDir; @@ -1548,7 +1548,7 @@ public class XenServerStorageProcessor implements StorageProcessor { throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir: " + templateUri); } - TemplateObjectTO newTemplate = new TemplateObjectTO(); + final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(destDir + "/" + templateFilename); newTemplate.setFormat(Storage.ImageFormat.VHD); @@ -1560,7 +1560,7 @@ public class XenServerStorageProcessor implements StorageProcessor { result = true; return new CopyCmdAnswer(newTemplate); - } catch (Exception ex) { + } catch (final Exception ex) { s_logger.error("Failed to create a template from a snapshot", ex); return new CopyCmdAnswer("Failed to create a template from a snapshot: " + ex.toString()); @@ -1569,7 +1569,7 @@ public class XenServerStorageProcessor implements StorageProcessor { if (destVdi != null) { try { destVdi.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Cleaned up leftover VDI on destination storage due to failure: ", e); } } @@ -1586,12 +1586,12 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer createVolumeFromSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - SnapshotObjectTO snapshot = (SnapshotObjectTO) srcData; - DataTO destData = cmd.getDestTO(); - DataStoreTO imageStore = srcData.getDataStore(); + public Answer createVolumeFromSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final SnapshotObjectTO snapshot = (SnapshotObjectTO) srcData; + final DataTO destData = cmd.getDestTO(); + final DataStoreTO imageStore = srcData.getDataStore(); if (srcData.getDataStore() instanceof PrimaryDataStoreTO && destData.getDataStore() instanceof PrimaryDataStoreTO) { return createVolumeFromSnapshot2(cmd); @@ -1601,10 +1601,10 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer("unsupported protocol"); } - NfsTO nfsImageStore = (NfsTO) imageStore; - String primaryStorageNameLabel = destData.getDataStore().getUuid(); - String secondaryStorageUrl = nfsImageStore.getUrl(); - int wait = cmd.getWait(); + final NfsTO nfsImageStore = (NfsTO) imageStore; + final String primaryStorageNameLabel = destData.getDataStore().getUuid(); + final String secondaryStorageUrl = nfsImageStore.getUrl(); + final int wait = cmd.getWait(); boolean result = false; // Generic error message. String details = null; @@ -1615,34 +1615,34 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(details); } try { - SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } // Get the absolute path of the snapshot on the secondary storage. String snapshotInstallPath = snapshot.getPath(); - int index = snapshotInstallPath.lastIndexOf(nfsImageStore.getPathSeparator()); - String snapshotName = snapshotInstallPath.substring(index + 1); + final int index = snapshotInstallPath.lastIndexOf(nfsImageStore.getPathSeparator()); + final String snapshotName = snapshotInstallPath.substring(index + 1); if (!snapshotName.startsWith("VHD-") && !snapshotName.endsWith(".vhd")) { snapshotInstallPath = snapshotInstallPath + ".vhd"; } - URI snapshotURI = new URI(secondaryStorageUrl + nfsImageStore.getPathSeparator() + snapshotInstallPath); - String snapshotPath = snapshotURI.getHost() + ":" + snapshotURI.getPath(); - String srUuid = primaryStorageSR.getUuid(conn); + final URI snapshotURI = new URI(secondaryStorageUrl + nfsImageStore.getPathSeparator() + snapshotInstallPath); + final String snapshotPath = snapshotURI.getHost() + ":" + snapshotURI.getPath(); + final String srUuid = primaryStorageSR.getUuid(conn); volumeUUID = copy_vhd_from_secondarystorage(conn, snapshotPath, srUuid, wait); result = true; - VDI volume = VDI.getByUuid(conn, volumeUUID); - VDI.Record vdir = volume.getRecord(conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VDI volume = VDI.getByUuid(conn, volumeUUID); + final VDI.Record vdir = volume.getRecord(conn); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(volumeUUID); newVol.setSize(vdir.virtualSize); return new CopyCmdAnswer(newVol); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { details += " due to " + e.toString(); s_logger.warn(details, e); - } catch (Exception e) { + } catch (final Exception e) { details += " due to " + e.getMessage(); s_logger.warn(details, e); } @@ -1655,34 +1655,34 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(details); } - protected Answer createVolumeFromSnapshot2(CopyCommand cmd) { + protected Answer createVolumeFromSnapshot2(final CopyCommand cmd) { try { - Connection conn = hypervisorResource.getConnection(); + final Connection conn = hypervisorResource.getConnection(); - Map srcOptions = cmd.getOptions(); + final Map srcOptions = cmd.getOptions(); - String src_iScsiName = srcOptions.get(DiskTO.IQN); - String srcStorageHost = srcOptions.get(DiskTO.STORAGE_HOST); - String srcChapInitiatorUsername = srcOptions.get(DiskTO.CHAP_INITIATOR_USERNAME); - String srcChapInitiatorSecret = srcOptions.get(DiskTO.CHAP_INITIATOR_SECRET); + final String src_iScsiName = srcOptions.get(DiskTO.IQN); + final String srcStorageHost = srcOptions.get(DiskTO.STORAGE_HOST); + final String srcChapInitiatorUsername = srcOptions.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String srcChapInitiatorSecret = srcOptions.get(DiskTO.CHAP_INITIATOR_SECRET); - SR srcSr = hypervisorResource.getIscsiSR(conn, src_iScsiName, srcStorageHost, src_iScsiName, srcChapInitiatorUsername, srcChapInitiatorSecret, false); + final SR srcSr = hypervisorResource.getIscsiSR(conn, src_iScsiName, srcStorageHost, src_iScsiName, srcChapInitiatorUsername, srcChapInitiatorSecret, false); - Map destOptions = cmd.getOptions2(); + final Map destOptions = cmd.getOptions2(); - String dest_iScsiName = destOptions.get(DiskTO.IQN); - String destStorageHost = destOptions.get(DiskTO.STORAGE_HOST); - String destChapInitiatorUsername = destOptions.get(DiskTO.CHAP_INITIATOR_USERNAME); - String destChapInitiatorSecret = destOptions.get(DiskTO.CHAP_INITIATOR_SECRET); + final String dest_iScsiName = destOptions.get(DiskTO.IQN); + final String destStorageHost = destOptions.get(DiskTO.STORAGE_HOST); + final String destChapInitiatorUsername = destOptions.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String destChapInitiatorSecret = destOptions.get(DiskTO.CHAP_INITIATOR_SECRET); - SR destSr = hypervisorResource.getIscsiSR(conn, dest_iScsiName, destStorageHost, dest_iScsiName, destChapInitiatorUsername, destChapInitiatorSecret, false); + final SR destSr = hypervisorResource.getIscsiSR(conn, dest_iScsiName, destStorageHost, dest_iScsiName, destChapInitiatorUsername, destChapInitiatorSecret, false); // there should only be one VDI in this SR - VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); + final VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); - VDI vdiCopy = srcVdi.copy(conn, destSr); + final VDI vdiCopy = srcVdi.copy(conn, destSr); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setSize(vdiCopy.getVirtualSize(conn)); newVol.setPath(vdiCopy.getUuid(conn)); @@ -1693,7 +1693,7 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(newVol); } - catch (Exception ex) { + catch (final Exception ex) { s_logger.warn("Failed to copy snapshot to volume: " + ex.toString(), ex); return new CopyCmdAnswer(ex.getMessage()); @@ -1701,25 +1701,25 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer deleteSnapshot(DeleteCommand cmd) { - SnapshotObjectTO snapshot = (SnapshotObjectTO) cmd.getData(); - DataStoreTO store = snapshot.getDataStore(); + public Answer deleteSnapshot(final DeleteCommand cmd) { + final SnapshotObjectTO snapshot = (SnapshotObjectTO) cmd.getData(); + final DataStoreTO store = snapshot.getDataStore(); if (store.getRole() == DataStoreRole.Primary) { - Connection conn = hypervisorResource.getConnection(); - VDI snapshotVdi = getVDIbyUuid(conn, snapshot.getPath()); + final Connection conn = hypervisorResource.getConnection(); + final VDI snapshotVdi = getVDIbyUuid(conn, snapshot.getPath()); if (snapshotVdi == null) { return new Answer(null); } String errMsg = null; try { deleteVDI(conn, snapshotVdi); - } catch (BadServerResponse e) { + } catch (final BadServerResponse e) { s_logger.debug("delete snapshot failed:" + e.toString()); errMsg = e.toString(); - } catch (XenAPIException e) { + } catch (final XenAPIException e) { s_logger.debug("delete snapshot failed:" + e.toString()); errMsg = e.toString(); - } catch (XmlRpcException e) { + } catch (final XmlRpcException e) { s_logger.debug("delete snapshot failed:" + e.toString()); errMsg = e.toString(); } @@ -1729,28 +1729,28 @@ public class XenServerStorageProcessor implements StorageProcessor { } @Override - public Answer introduceObject(IntroduceObjectCmd cmd) { + public Answer introduceObject(final IntroduceObjectCmd cmd) { try { - Connection conn = hypervisorResource.getConnection(); - DataStoreTO store = cmd.getDataTO().getDataStore(); - SR poolSr = hypervisorResource.getStorageRepository(conn, store.getUuid()); + final Connection conn = hypervisorResource.getConnection(); + final DataStoreTO store = cmd.getDataTO().getDataStore(); + final SR poolSr = hypervisorResource.getStorageRepository(conn, store.getUuid()); poolSr.scan(conn); return new IntroduceObjectAnswer(cmd.getDataTO()); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to introduce object", e); return new Answer(cmd, false, e.toString()); } } @Override - public Answer forgetObject(ForgetObjectCmd cmd) { + public Answer forgetObject(final ForgetObjectCmd cmd) { try { - Connection conn = hypervisorResource.getConnection(); - DataTO data = cmd.getDataTO(); - VDI vdi = VDI.getByUuid(conn, data.getPath()); + final Connection conn = hypervisorResource.getConnection(); + final DataTO data = cmd.getDataTO(); + final VDI vdi = VDI.getByUuid(conn, data.getPath()); vdi.forget(conn); return new IntroduceObjectAnswer(cmd.getDataTO()); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to introduce object", e); return new Answer(cmd, false, e.toString()); } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625Resource.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625Resource.java index c10844e0f67..a01e1927d1d 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625Resource.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625Resource.java @@ -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 getPatchFiles() { - List files = new ArrayList(); - String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch"; - String patchfilePath = Script.findScript("", patch); + final List files = new ArrayList(); + 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); diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625StorageProcessor.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625StorageProcessor.java index c4f2dc916ea..37c311a6759 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625StorageProcessor.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/Xenserver625StorageProcessor.java @@ -62,20 +62,20 @@ import com.xensource.xenapi.VDI; public class Xenserver625StorageProcessor extends XenServerStorageProcessor { private static final Logger s_logger = Logger.getLogger(XenServerStorageProcessor.class); - public Xenserver625StorageProcessor(CitrixResourceBase resource) { + public Xenserver625StorageProcessor(final CitrixResourceBase resource) { super(resource); } - protected boolean mountNfs(Connection conn, String remoteDir, String localDir) { + protected boolean mountNfs(final Connection conn, final String remoteDir, String localDir) { if (localDir == null) { localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(remoteDir.getBytes()); } - String results = hypervisorResource.callHostPluginAsync(conn, "cloud-plugin-storage", "mountNfsSecondaryStorage", 100 * 1000, - "localDir", localDir, "remoteDir", remoteDir); + final String results = hypervisorResource.callHostPluginAsync(conn, "cloud-plugin-storage", "mountNfsSecondaryStorage", 100 * 1000, "localDir", localDir, "remoteDir", + remoteDir); if (results == null || results.isEmpty()) { - String errMsg = "Could not mount secondary storage " + remoteDir + " on host " + localDir; + final String errMsg = "Could not mount secondary storage " + remoteDir + " on host " + localDir; s_logger.warn(errMsg); @@ -85,8 +85,8 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { return true; } - protected boolean makeDirectory(Connection conn, String path) { - String result = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "makeDirectory", "path", path); + protected boolean makeDirectory(final Connection conn, final String path) { + final String result = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "makeDirectory", "path", path); if (result == null || result.isEmpty()) { return false; @@ -95,27 +95,27 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { return true; } - protected SR createFileSR(Connection conn, String path) { + protected SR createFileSR(final Connection conn, final String path) { SR sr = null; PBD pbd = null; try { - String srname = hypervisorResource.getHost().uuid + path.trim(); + final String srname = hypervisorResource.getHost().getUuid() + path.trim(); - Set srs = SR.getByNameLabel(conn, srname); + final Set srs = SR.getByNameLabel(conn, srname); if (srs != null && !srs.isEmpty()) { return srs.iterator().next(); } - Map smConfig = new HashMap(); + final Map smConfig = new HashMap(); - Host host = Host.getByUuid(conn, hypervisorResource.getHost().uuid); - String uuid = UUID.randomUUID().toString(); + final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); + final String uuid = UUID.randomUUID().toString(); sr = SR.introduce(conn, uuid, srname, srname, "file", "file", false, smConfig); - PBD.Record record = new PBD.Record(); + final PBD.Record record = new PBD.Record(); record.host = host; record.SR = sr; @@ -131,12 +131,12 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { sr.scan(conn); return sr; - } catch (Exception ex) { + } catch (final Exception ex) { try { if (pbd != null) { pbd.destroy(conn); } - } catch (Exception e1) { + } catch (final Exception e1) { s_logger.debug("Failed to destroy PBD", ex); } @@ -144,11 +144,11 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (sr != null) { sr.forget(conn); } - } catch (Exception e2) { + } catch (final Exception e2) { s_logger.error("Failed to forget SR", ex); } - String msg = "createFileSR failed! due to the following: " + ex.toString(); + final String msg = "createFileSR failed! due to the following: " + ex.toString(); s_logger.warn(msg, ex); @@ -156,52 +156,52 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } } - protected SR createFileSr(Connection conn, String remotePath, String dir) { - String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(remotePath.getBytes()); + protected SR createFileSr(final Connection conn, final String remotePath, final String dir) { + final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(remotePath.getBytes()); mountNfs(conn, remotePath, localDir); - SR sr = createFileSR(conn, localDir + "/" + dir); + final SR sr = createFileSR(conn, localDir + "/" + dir); return sr; } @Override - public Answer copyTemplateToPrimaryStorage(CopyCommand cmd) { - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); - int wait = cmd.getWait(); - DataStoreTO srcStore = srcData.getDataStore(); - Connection conn = hypervisorResource.getConnection(); + public Answer copyTemplateToPrimaryStorage(final CopyCommand cmd) { + final DataTO srcData = cmd.getSrcTO(); + final DataTO destData = cmd.getDestTO(); + final int wait = cmd.getWait(); + final DataStoreTO srcStore = srcData.getDataStore(); + final Connection conn = hypervisorResource.getConnection(); SR srcSr = null; Task task = null; try { - if ((srcStore instanceof NfsTO) && (srcData.getObjectType() == DataObjectType.TEMPLATE)) { - NfsTO srcImageStore = (NfsTO)srcStore; - TemplateObjectTO srcTemplate = (TemplateObjectTO)srcData; - String storeUrl = srcImageStore.getUrl(); - URI uri = new URI(storeUrl); + if (srcStore instanceof NfsTO && srcData.getObjectType() == DataObjectType.TEMPLATE) { + final NfsTO srcImageStore = (NfsTO) srcStore; + final TemplateObjectTO srcTemplate = (TemplateObjectTO) srcData; + final String storeUrl = srcImageStore.getUrl(); + final URI uri = new URI(storeUrl); String volumePath = srcData.getPath(); volumePath = StringUtils.stripEnd(volumePath, "/"); - String[] splits = volumePath.split("/"); + final String[] splits = volumePath.split("/"); String volumeDirectory = volumePath; if (splits.length > 4) { - //"template/tmpl/dcid/templateId/templatename" - int index = volumePath.lastIndexOf("/"); + // "template/tmpl/dcid/templateId/templatename" + final int index = volumePath.lastIndexOf("/"); volumeDirectory = volumePath.substring(0, index); } srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory); - Set setVdis = srcSr.getVDIs(conn); + final Set setVdis = srcSr.getVDIs(conn); if (setVdis.size() != 1) { return new CopyCmdAnswer("Can't find template VDI under: " + uri.getHost() + ":" + uri.getPath() + "/" + volumeDirectory); } - VDI srcVdi = setVdis.iterator().next(); + final VDI srcVdi = setVdis.iterator().next(); boolean managed = false; String storageHost = null; @@ -211,7 +211,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { String chapInitiatorUsername = null; String chapInitiatorSecret = null; - PrimaryDataStoreTO destStore = (PrimaryDataStoreTO)destData.getDataStore(); + final PrimaryDataStoreTO destStore = (PrimaryDataStoreTO) destData.getDataStore(); Map details = destStore.getDetails(); @@ -240,13 +240,12 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { details.put(DiskTO.CHAP_INITIATOR_SECRET, chapInitiatorSecret); destSr = hypervisorResource.prepareManagedSr(conn, details); - } - else { - String srName = destStore.getUuid(); - Set srs = SR.getByNameLabel(conn, srName); + } else { + final String srName = destStore.getUuid(); + final Set srs = SR.getByNameLabel(conn, srName); if (srs.size() != 1) { - String msg = "There are " + srs.size() + " SRs with same name: " + srName; + final String msg = "There are " + srs.size() + " SRs with same name: " + srName; s_logger.warn(msg); @@ -262,17 +261,17 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); - VDI tmplVdi = Types.toVDI(task, conn); + final VDI tmplVdi = Types.toVDI(task, conn); final String uuidToReturn; - Long physicalSize = tmplVdi.getPhysicalUtilisation(conn); + final Long physicalSize = tmplVdi.getPhysicalUtilisation(conn); if (managed) { uuidToReturn = tmplVdi.getUuid(conn); tmplVdi.setNameLabel(conn, managedStoragePoolRootVolumeName); } else { - VDI snapshotVdi = tmplVdi.snapshot(conn, new HashMap()); + final VDI snapshotVdi = tmplVdi.snapshot(conn, new HashMap()); uuidToReturn = snapshotVdi.getUuid(conn); @@ -283,12 +282,12 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { destSr.scan(conn); - try{ + try { Thread.sleep(5000); - } catch (Exception e) { + } catch (final Exception e) { } - TemplateObjectTO newVol = new TemplateObjectTO(); + final TemplateObjectTO newVol = new TemplateObjectTO(); newVol.setUuid(uuidToReturn); newVol.setPath(uuidToReturn); @@ -299,8 +298,8 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { return new CopyCmdAnswer(newVol); } - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() + " for template due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Catch Exception " + e.getClass().getName() + " for template due to " + e.toString(); s_logger.warn(msg, e); @@ -309,7 +308,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("unable to destroy task (" + task.toWireString() + ") due to " + e.toString()); } } @@ -322,7 +321,8 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { return new CopyCmdAnswer("not implemented yet"); } - protected String backupSnapshot(Connection conn, String primaryStorageSRUuid, String localMountPoint, String path, String secondaryStorageMountPath, String snapshotUuid, String prevBackupUuid, String prevSnapshotUuid, Boolean isISCSI, int wait) { + protected String backupSnapshot(final Connection conn, final String primaryStorageSRUuid, final String localMountPoint, final String path, + final String secondaryStorageMountPath, final String snapshotUuid, String prevBackupUuid, final String prevSnapshotUuid, final Boolean isISCSI, int wait) { boolean filesrcreated = false; // boolean copied = false; @@ -331,12 +331,12 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } SR ssSR = null; - String remoteDir = secondaryStorageMountPath; + final String remoteDir = secondaryStorageMountPath; try { ssSR = createFileSr(conn, remoteDir, path); filesrcreated = true; - VDI snapshotvdi = VDI.getByUuid(conn, snapshotUuid); + final VDI snapshotvdi = VDI.getByUuid(conn, snapshotUuid); if (wait == 0) { wait = 2 * 60 * 60; } @@ -345,7 +345,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { try { VDI previousSnapshotVdi = null; if (prevSnapshotUuid != null) { - previousSnapshotVdi = VDI.getByUuid(conn,prevSnapshotUuid); + previousSnapshotVdi = VDI.getByUuid(conn, prevSnapshotUuid); } task = snapshotvdi.copyAsync(conn, ssSR, previousSnapshotVdi, null); // poll every 1 seconds , @@ -357,15 +357,15 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString()); } } } - String result = dvdi.getUuid(conn).concat("#").concat(dvdi.getPhysicalUtilisation(conn).toString()); + final String result = dvdi.getUuid(conn).concat("#").concat(dvdi.getPhysicalUtilisation(conn).toString()); return result; - } catch (Exception e) { - String msg = "Exception in backupsnapshot stage due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Exception in backupsnapshot stage due to " + e.toString(); s_logger.debug(msg); throw new CloudRuntimeException(msg, e); } finally { @@ -373,16 +373,16 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (filesrcreated && ssSR != null) { hypervisorResource.removeSR(conn, ssSR); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Exception in backupsnapshot cleanup stage due to " + e.toString()); } } } @Override - protected String getVhdParent(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI) { - String parentUuid = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, - "snapshotUuid", snapshotUuid, "isISCSI", isISCSI.toString()); + protected String getVhdParent(final Connection conn, final String primaryStorageSRUuid, final String snapshotUuid, final Boolean isISCSI) { + final String parentUuid = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", + snapshotUuid, "isISCSI", isISCSI.toString()); if (parentUuid == null || parentUuid.isEmpty() || parentUuid.equalsIgnoreCase("None")) { s_logger.debug("Unable to get parent of VHD " + snapshotUuid + " in SR " + primaryStorageSRUuid); @@ -393,64 +393,64 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer backupSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO cacheData = cmd.getCacheTO(); - DataTO destData = cmd.getDestTO(); - int wait = cmd.getWait(); - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)srcData.getDataStore(); - String primaryStorageNameLabel = primaryStore.getUuid(); + public Answer backupSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO cacheData = cmd.getCacheTO(); + final DataTO destData = cmd.getDestTO(); + final int wait = cmd.getWait(); + final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore(); + final String primaryStorageNameLabel = primaryStore.getUuid(); String secondaryStorageUrl = null; NfsTO cacheStore = null; String destPath = null; if (cacheData != null) { - cacheStore = (NfsTO)cacheData.getDataStore(); + cacheStore = (NfsTO) cacheData.getDataStore(); secondaryStorageUrl = cacheStore.getUrl(); destPath = cacheData.getPath(); } else { - cacheStore = (NfsTO)destData.getDataStore(); + cacheStore = (NfsTO) destData.getDataStore(); secondaryStorageUrl = cacheStore.getUrl(); destPath = destData.getPath(); } - SnapshotObjectTO snapshotTO = (SnapshotObjectTO)srcData; - SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO)destData; - String snapshotUuid = snapshotTO.getPath(); + final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData; + final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData; + final String snapshotUuid = snapshotTO.getPath(); - String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); - String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); - Map options = cmd.getOptions(); + final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); + final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); + final Map options = cmd.getOptions(); // By default assume failure String details = null; String snapshotBackupUuid = null; - boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot")); + final boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot")); Long physicalSize = null; try { - SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } // String psUuid = primaryStorageSR.getUuid(conn); - Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); + final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); - VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); - String snapshotPaUuid = null; + final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); + final String snapshotPaUuid = null; - URI uri = new URI(secondaryStorageUrl); - String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - DataStoreTO destStore = destData.getDataStore(); - String folder = destPath; + final URI uri = new URI(secondaryStorageUrl); + final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); + final DataStoreTO destStore = destData.getDataStore(); + final String folder = destPath; String finalPath = null; - String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); + final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); if (fullbackup) { SR snapshotSr = null; Task task = null; try { - String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes()); + final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes()); mountNfs(conn, secondaryStorageMountPath, localDir); - boolean result = makeDirectory(conn, localDir + "/" + folder); + final boolean result = makeDirectory(conn, localDir + "/" + folder); if (!result) { details = " Filed to create folder " + folder + " in secondary storage"; s_logger.warn(details); @@ -463,21 +463,21 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); - VDI backedVdi = Types.toVDI(task, conn); + final VDI backedVdi = Types.toVDI(task, conn); snapshotBackupUuid = backedVdi.getUuid(conn); physicalSize = backedVdi.getPhysicalUtilisation(conn); - if( destStore instanceof SwiftTO) { + if (destStore instanceof SwiftTO) { try { - String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); - String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO)destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); - String swiftPath = container + File.separator + destSnapshotName; + final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); + final String swiftPath = container + File.separator + destSnapshotName; finalPath = swiftPath; } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); - } catch (Exception e) { - s_logger.debug("Failed to delete snapshot on cache storages" ,e); + } catch (final Exception e) { + s_logger.debug("Failed to delete snapshot on cache storages", e); } } @@ -490,11 +490,12 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); - } catch (Exception e) { - s_logger.debug("Failed to delete snapshot on cache storages" ,e); + } catch (final Exception e) { + s_logger.debug("Failed to delete snapshot on cache storages", e); } } - // finalPath = folder + File.separator + snapshotBackupUuid; + // finalPath = folder + File.separator + + // snapshotBackupUuid; } else { finalPath = folder + File.separator + snapshotBackupUuid; } @@ -503,38 +504,39 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString()); } } - if( snapshotSr != null) { + if (snapshotSr != null) { hypervisorResource.removeSR(conn, snapshotSr); } } } else { - String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); - if( destStore instanceof SwiftTO ) { - String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); - snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO)destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait); + final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); + if (destStore instanceof SwiftTO) { + final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait); finalPath = container + File.separator + snapshotBackupUuid; - } else if (destStore instanceof S3TO ) { + } else if (destStore instanceof S3TO) { finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder, snapshotPaUuid, isISCSI, wait); if (finalPath == null) { throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed"); } } else { - String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, - secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait); - String[] tmp = result.split("#"); + final String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, + prevSnapshotUuid, isISCSI, wait); + final String[] tmp = result.split("#"); snapshotBackupUuid = tmp[0]; physicalSize = Long.parseLong(tmp[1]); finalPath = folder + File.separator + snapshotBackupUuid; } } - String volumeUuid = snapshotTO.getVolume().getPath(); + final String volumeUuid = snapshotTO.getVolume().getPath(); destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); - SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); + final SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(finalPath); newSnapshot.setPhysicalSize(physicalSize); if (fullbackup) { @@ -543,10 +545,10 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { newSnapshot.setParentSnapshotPath(prevBackupUuid); } return new CopyCmdAnswer(newSnapshot); - } catch (Types.XenAPIException e) { + } catch (final Types.XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); - } catch (Exception e) { + } catch (final Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); } @@ -555,18 +557,17 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer createTemplateFromVolume(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - VolumeObjectTO volume = (VolumeObjectTO)cmd.getSrcTO(); - TemplateObjectTO template = (TemplateObjectTO)cmd.getDestTO(); - NfsTO destStore = (NfsTO)cmd.getDestTO().getDataStore(); - int wait = cmd.getWait(); + public Answer createTemplateFromVolume(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final VolumeObjectTO volume = (VolumeObjectTO) cmd.getSrcTO(); + final TemplateObjectTO template = (TemplateObjectTO) cmd.getDestTO(); + final NfsTO destStore = (NfsTO) cmd.getDestTO().getDataStore(); + final int wait = cmd.getWait(); - String secondaryStoragePoolURL = destStore.getUrl(); - String volumeUUID = volume.getPath(); - - String userSpecifiedName = template.getName(); + final String secondaryStoragePoolURL = destStore.getUrl(); + final String volumeUUID = volume.getPath(); + final String userSpecifiedName = template.getName(); String details = null; SR tmpltSR = null; @@ -575,16 +576,16 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { String installPath = null; Task task = null; try { - URI uri = new URI(secondaryStoragePoolURL); + final URI uri = new URI(secondaryStoragePoolURL); secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); installPath = template.getPath(); - if( !hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { + if (!hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { details = " Filed to create folder " + installPath + " in secondary storage"; s_logger.warn(details); return new CopyCmdAnswer(details); } - VDI vol = getVDIbyUuid(conn, volumeUUID); + final VDI vol = getVDIbyUuid(conn, volumeUUID); // create template SR tmpltSR = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), installPath); @@ -593,39 +594,40 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); - VDI tmpltVDI = Types.toVDI(task, conn); + final VDI tmpltVDI = Types.toVDI(task, conn); // scan makes XenServer pick up VDI physicalSize tmpltSR.scan(conn); if (userSpecifiedName != null) { tmpltVDI.setNameLabel(conn, userSpecifiedName); } - String tmpltUUID = tmpltVDI.getUuid(conn); - String tmpltFilename = tmpltUUID + ".vhd"; - long virtualSize = tmpltVDI.getVirtualSize(conn); - long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); + final String tmpltUUID = tmpltVDI.getUuid(conn); + final String tmpltFilename = tmpltUUID + ".vhd"; + final long virtualSize = tmpltVDI.getVirtualSize(conn); + final long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); // create the template.properties file - String templatePath = secondaryStorageMountPath + "/" + installPath; - result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, template.getId()); + final String templatePath = secondaryStorageMountPath + "/" + installPath; + result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, + template.getId()); if (!result) { throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir"); } installPath = installPath + "/" + tmpltFilename; hypervisorResource.removeSR(conn, tmpltSR); tmpltSR = null; - TemplateObjectTO newTemplate = new TemplateObjectTO(); + final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(installPath); newTemplate.setFormat(Storage.ImageFormat.VHD); newTemplate.setSize(virtualSize); newTemplate.setPhysicalSize(physicalSize); newTemplate.setName(tmpltUUID); - CopyCmdAnswer answer = new CopyCmdAnswer(newTemplate); + final CopyCmdAnswer answer = new CopyCmdAnswer(newTemplate); return answer; - } catch (Exception e) { + } catch (final Exception e) { if (tmpltSR != null) { hypervisorResource.removeSR(conn, tmpltSR); } - if ( secondaryStorageMountPath != null) { + if (secondaryStorageMountPath != null) { hypervisorResource.deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); } details = "Creating template from volume " + volumeUUID + " failed due to " + e.toString(); @@ -634,15 +636,15 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { - s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString()); + } catch (final Exception e) { + s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString()); } } } return new CopyCmdAnswer(details); } - protected String getSnapshotUuid(String snapshotPath) { + protected String getSnapshotUuid(final String snapshotPath) { int index = snapshotPath.lastIndexOf(File.separator); String snapshotUuid = snapshotPath.substring(index + 1); index = snapshotUuid.lastIndexOf("."); @@ -653,14 +655,14 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer createVolumeFromSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData; - DataTO destData = cmd.getDestTO(); - PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore(); - VolumeObjectTO volume = (VolumeObjectTO)destData; - DataStoreTO imageStore = srcData.getDataStore(); + public Answer createVolumeFromSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final SnapshotObjectTO snapshot = (SnapshotObjectTO) srcData; + final DataTO destData = cmd.getDestTO(); + final PrimaryDataStoreTO pool = (PrimaryDataStoreTO) destData.getDataStore(); + final VolumeObjectTO volume = (VolumeObjectTO) destData; + final DataStoreTO imageStore = srcData.getDataStore(); if (srcData.getDataStore() instanceof PrimaryDataStoreTO && destData.getDataStore() instanceof PrimaryDataStoreTO) { return createVolumeFromSnapshot2(cmd); @@ -670,10 +672,10 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { return new CopyCmdAnswer("unsupported protocol"); } - NfsTO nfsImageStore = (NfsTO)imageStore; - String primaryStorageNameLabel = pool.getUuid(); - String secondaryStorageUrl = nfsImageStore.getUrl(); - int wait = cmd.getWait(); + final NfsTO nfsImageStore = (NfsTO) imageStore; + final String primaryStorageNameLabel = pool.getUuid(); + final String secondaryStorageUrl = nfsImageStore.getUrl(); + final int wait = cmd.getWait(); boolean result = false; // Generic error message. String details = null; @@ -686,38 +688,38 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { SR srcSr = null; VDI destVdi = null; try { - SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } - String nameLabel = "cloud-" + UUID.randomUUID().toString(); + final String nameLabel = "cloud-" + UUID.randomUUID().toString(); destVdi = createVdi(conn, nameLabel, primaryStorageSR, volume.getSize()); volumeUUID = destVdi.getUuid(conn); - String snapshotInstallPath = snapshot.getPath(); - int index = snapshotInstallPath.lastIndexOf(File.separator); - String snapshotDirectory = snapshotInstallPath.substring(0, index); - String snapshotUuid = getSnapshotUuid(snapshotInstallPath); + final String snapshotInstallPath = snapshot.getPath(); + final int index = snapshotInstallPath.lastIndexOf(File.separator); + final String snapshotDirectory = snapshotInstallPath.substring(0, index); + final String snapshotUuid = getSnapshotUuid(snapshotInstallPath); - URI uri = new URI(secondaryStorageUrl); + final URI uri = new URI(secondaryStorageUrl); srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), snapshotDirectory); - String[] parents = snapshot.getParents(); - List snapshotChains = new ArrayList(); + final String[] parents = snapshot.getParents(); + final List snapshotChains = new ArrayList(); if (parents != null) { - for(int i = 0; i < parents.length; i++) { - String snChainPath = parents[i]; - String uuid = getSnapshotUuid(snChainPath); - VDI chain = VDI.getByUuid(conn, uuid); + for (int i = 0; i < parents.length; i++) { + final String snChainPath = parents[i]; + final String uuid = getSnapshotUuid(snChainPath); + final VDI chain = VDI.getByUuid(conn, uuid); snapshotChains.add(chain); } } - VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); + final VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); snapshotChains.add(snapshotVdi); - for(VDI snapChain : snapshotChains) { - Task task = snapChain.copyAsync(conn, null, null, destVdi); + for (final VDI snapChain : snapshotChains) { + final Task task = snapChain.copyAsync(conn, null, null, destVdi); // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); @@ -726,15 +728,15 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { result = true; destVdi = VDI.getByUuid(conn, volumeUUID); - VDI.Record vdir = destVdi.getRecord(conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VDI.Record vdir = destVdi.getRecord(conn); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(volumeUUID); newVol.setSize(vdir.virtualSize); return new CopyCmdAnswer(newVol); - } catch (Types.XenAPIException e) { + } catch (final Types.XenAPIException e) { details += " due to " + e.toString(); s_logger.warn(details, e); - } catch (Exception e) { + } catch (final Exception e) { details += " due to " + e.getMessage(); s_logger.warn(details, e); } finally { @@ -744,7 +746,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (!result && destVdi != null) { try { destVdi.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("destroy dest vdi failed", e); } } @@ -759,19 +761,19 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer copyVolumeFromPrimaryToSecondary(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - VolumeObjectTO srcVolume = (VolumeObjectTO)cmd.getSrcTO(); - VolumeObjectTO destVolume = (VolumeObjectTO)cmd.getDestTO(); - int wait = cmd.getWait(); - DataStoreTO destStore = destVolume.getDataStore(); + public Answer copyVolumeFromPrimaryToSecondary(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final VolumeObjectTO srcVolume = (VolumeObjectTO) cmd.getSrcTO(); + final VolumeObjectTO destVolume = (VolumeObjectTO) cmd.getDestTO(); + final int wait = cmd.getWait(); + final DataStoreTO destStore = destVolume.getDataStore(); if (destStore instanceof NfsTO) { SR secondaryStorage = null; Task task = null; try { - NfsTO nfsStore = (NfsTO)destStore; - URI uri = new URI(nfsStore.getUrl()); + final NfsTO nfsStore = (NfsTO) destStore; + final URI uri = new URI(nfsStore.getUrl()); // Create the volume folder if (!hypervisorResource.createSecondaryStorageFolder(conn, uri.getHost() + ":" + uri.getPath(), destVolume.getPath())) { throw new InternalErrorException("Failed to create the volume folder."); @@ -780,27 +782,27 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { // Create a SR for the volume UUID folder secondaryStorage = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), destVolume.getPath()); // Look up the volume on the source primary storage pool - VDI srcVdi = getVDIbyUuid(conn, srcVolume.getPath()); + final VDI srcVdi = getVDIbyUuid(conn, srcVolume.getPath()); // Copy the volume to secondary storage task = srcVdi.copyAsync(conn, secondaryStorage, null, null); // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); - VDI destVdi = Types.toVDI(task, conn); - String destVolumeUUID = destVdi.getUuid(conn); + final VDI destVdi = Types.toVDI(task, conn); + final String destVolumeUUID = destVdi.getUuid(conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(destVolume.getPath() + File.separator + destVolumeUUID + ".vhd"); newVol.setSize(srcVolume.getSize()); return new CopyCmdAnswer(newVol); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to copy volume to secondary: " + e.toString()); return new CopyCmdAnswer("Failed to copy volume to secondary: " + e.toString()); } finally { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString()); } } @@ -811,21 +813,21 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); - int wait = cmd.getWait(); - VolumeObjectTO srcVolume = (VolumeObjectTO)srcData; - VolumeObjectTO destVolume = (VolumeObjectTO)destData; - PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)destVolume.getDataStore(); - DataStoreTO srcStore = srcVolume.getDataStore(); + public Answer copyVolumeFromImageCacheToPrimary(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO destData = cmd.getDestTO(); + final int wait = cmd.getWait(); + final VolumeObjectTO srcVolume = (VolumeObjectTO) srcData; + final VolumeObjectTO destVolume = (VolumeObjectTO) destData; + final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) destVolume.getDataStore(); + final DataStoreTO srcStore = srcVolume.getDataStore(); if (srcStore instanceof NfsTO) { - NfsTO nfsStore = (NfsTO)srcStore; - String volumePath = srcVolume.getPath(); + final NfsTO nfsStore = (NfsTO) srcStore; + final String volumePath = srcVolume.getPath(); int index = volumePath.lastIndexOf("/"); - String volumeDirectory = volumePath.substring(0, index); + final String volumeDirectory = volumePath.substring(0, index); String volumeUuid = volumePath.substring(index + 1); index = volumeUuid.indexOf("."); if (index != -1) { @@ -834,33 +836,33 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { URI uri = null; try { uri = new URI(nfsStore.getUrl()); - } catch (Exception e) { + } catch (final Exception e) { return new CopyCmdAnswer(e.toString()); } - SR srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory); + final SR srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory); Task task = null; try { - SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, primaryStore.getUuid()); - VDI srcVdi = VDI.getByUuid(conn, volumeUuid); + final SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, primaryStore.getUuid()); + final VDI srcVdi = VDI.getByUuid(conn, volumeUuid); task = srcVdi.copyAsync(conn, primaryStoragePool, null, null); // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); - VDI destVdi = Types.toVDI(task, conn); - VolumeObjectTO newVol = new VolumeObjectTO(); + final VDI destVdi = Types.toVDI(task, conn); + final VolumeObjectTO newVol = new VolumeObjectTO(); newVol.setPath(destVdi.getUuid(conn)); newVol.setSize(srcVolume.getSize()); return new CopyCmdAnswer(newVol); - } 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.warn(msg, e); return new CopyCmdAnswer(e.toString()); } finally { if (task != null) { try { task.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("unable to destroy task(" + task.toString() + ") due to " + e.toString()); } } @@ -875,23 +877,23 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } @Override - public Answer createTemplateFromSnapshot(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); + public Answer createTemplateFromSnapshot(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); + final DataTO srcData = cmd.getSrcTO(); + final DataTO destData = cmd.getDestTO(); if (srcData.getDataStore() instanceof PrimaryDataStoreTO && destData.getDataStore() instanceof NfsTO) { return createTemplateFromSnapshot2(cmd); } - int wait = cmd.getWait(); + final int wait = cmd.getWait(); - SnapshotObjectTO srcObj = (SnapshotObjectTO)srcData; - TemplateObjectTO destObj = (TemplateObjectTO)destData; + final SnapshotObjectTO srcObj = (SnapshotObjectTO) srcData; + final TemplateObjectTO destObj = (TemplateObjectTO) destData; - NfsTO srcStore = (NfsTO)srcObj.getDataStore(); - NfsTO destStore = (NfsTO)destObj.getDataStore(); + final NfsTO srcStore = (NfsTO) srcObj.getDataStore(); + final NfsTO destStore = (NfsTO) destObj.getDataStore(); URI srcUri = null; URI destUri = null; @@ -899,16 +901,16 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { try { srcUri = new URI(srcStore.getUrl()); destUri = new URI(destStore.getUrl()); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("incorrect url", e); return new CopyCmdAnswer("incorrect url" + e.toString()); } - String srcPath = srcObj.getPath(); - int index = srcPath.lastIndexOf("/"); - String srcDir = srcPath.substring(0, index); - String destDir = destObj.getPath(); + final String srcPath = srcObj.getPath(); + final int index = srcPath.lastIndexOf("/"); + final String srcDir = srcPath.substring(0, index); + final String destDir = destObj.getPath(); SR srcSr = null; SR destSr = null; @@ -920,42 +922,42 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { try { srcSr = createFileSr(conn, srcUri.getHost() + ":" + srcUri.getPath(), srcDir); - String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); - String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes()); + final String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); + final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes()); mountNfs(conn, destUri.getHost() + ":" + destUri.getPath(), localDir); makeDirectory(conn, localDir + "/" + destDir); destSr = createFileSR(conn, localDir + "/" + destDir); - String nameLabel = "cloud-" + UUID.randomUUID().toString(); + final String nameLabel = "cloud-" + UUID.randomUUID().toString(); - String[] parents = srcObj.getParents(); - List snapshotChains = new ArrayList(); + final String[] parents = srcObj.getParents(); + final List snapshotChains = new ArrayList(); if (parents != null) { for (int i = 0; i < parents.length; i++) { - String snChainPath = parents[i]; - String uuid = getSnapshotUuid(snChainPath); - VDI chain = VDI.getByUuid(conn, uuid); + final String snChainPath = parents[i]; + final String uuid = getSnapshotUuid(snChainPath); + final VDI chain = VDI.getByUuid(conn, uuid); snapshotChains.add(chain); } } - String snapshotUuid = getSnapshotUuid(srcPath); - VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); + final String snapshotUuid = getSnapshotUuid(srcPath); + final VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); snapshotChains.add(snapshotVdi); - long templateVirtualSize = snapshotChains.get(0).getVirtualSize(conn); + final long templateVirtualSize = snapshotChains.get(0).getVirtualSize(conn); destVdi = createVdi(conn, nameLabel, destSr, templateVirtualSize); - String destVdiUuid = destVdi.getUuid(conn); + final String destVdiUuid = destVdi.getUuid(conn); - for (VDI snapChain : snapshotChains) { - Task task = snapChain.copyAsync(conn, null, null, destVdi); + for (final VDI snapChain : snapshotChains) { + final Task task = snapChain.copyAsync(conn, null, null, destVdi); // poll every 1 seconds , hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); hypervisorResource.checkForSuccess(conn, task); @@ -968,23 +970,22 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { // scan makes XenServer pick up VDI physicalSize destSr.scan(conn); - String templateUuid = destVdi.getUuid(conn); - String templateFilename = templateUuid + ".vhd"; - long virtualSize = destVdi.getVirtualSize(conn); - long physicalSize = destVdi.getPhysicalUtilisation(conn); + final String templateUuid = destVdi.getUuid(conn); + final String templateFilename = templateUuid + ".vhd"; + final long virtualSize = destVdi.getVirtualSize(conn); + final long physicalSize = destVdi.getPhysicalUtilisation(conn); String templatePath = destNfsPath + "/" + destDir; - templatePath = templatePath.replaceAll("//","/"); + templatePath = templatePath.replaceAll("//", "/"); - result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, nameLabel, null, - physicalSize, virtualSize, destObj.getId()); + result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, nameLabel, null, physicalSize, virtualSize, destObj.getId()); if (!result) { throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir"); } - TemplateObjectTO newTemplate = new TemplateObjectTO(); + final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(destDir + "/" + templateFilename); newTemplate.setFormat(Storage.ImageFormat.VHD); @@ -995,7 +996,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { result = true; return new CopyCmdAnswer(newTemplate); - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Failed create template from snapshot", e); return new CopyCmdAnswer("Failed create template from snapshot " + e.toString()); @@ -1004,7 +1005,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (destVdi != null) { try { destVdi.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Clean up left over on dest storage failed: ", e); } } @@ -1020,11 +1021,11 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { } } - public Answer createTemplateFromSnapshot2(CopyCommand cmd) { - Connection conn = hypervisorResource.getConnection(); + public Answer createTemplateFromSnapshot2(final CopyCommand cmd) { + final Connection conn = hypervisorResource.getConnection(); - SnapshotObjectTO snapshotObjTO = (SnapshotObjectTO)cmd.getSrcTO(); - TemplateObjectTO templateObjTO = (TemplateObjectTO)cmd.getDestTO(); + final SnapshotObjectTO snapshotObjTO = (SnapshotObjectTO) cmd.getSrcTO(); + final TemplateObjectTO templateObjTO = (TemplateObjectTO) cmd.getDestTO(); if (!(snapshotObjTO.getDataStore() instanceof PrimaryDataStoreTO) || !(templateObjTO.getDataStore() instanceof NfsTO)) { return null; @@ -1034,10 +1035,10 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { URI destUri = null; try { - destStore = (NfsTO)templateObjTO.getDataStore(); + destStore = (NfsTO) templateObjTO.getDataStore(); destUri = new URI(destStore.getUrl()); - } catch (Exception ex) { + } catch (final Exception ex) { s_logger.debug("Invalid URI", ex); return new CopyCmdAnswer("Invalid URI: " + ex.toString()); @@ -1046,23 +1047,23 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { SR srcSr = null; SR destSr = null; - String destDir = templateObjTO.getPath(); + final String destDir = templateObjTO.getPath(); VDI destVdi = null; boolean result = false; try { - Map srcDetails = cmd.getOptions(); + final Map srcDetails = cmd.getOptions(); - String iScsiName = srcDetails.get(DiskTO.IQN); - String storageHost = srcDetails.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET); + final String iScsiName = srcDetails.get(DiskTO.IQN); + final String storageHost = srcDetails.get(DiskTO.STORAGE_HOST); + final String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME); + final String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET); srcSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true); - String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); - String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes()); + final String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); + final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes()); mountNfs(conn, destNfsPath, localDir); makeDirectory(conn, localDir + "/" + destDir); @@ -1070,35 +1071,35 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { destSr = createFileSR(conn, localDir + "/" + destDir); // there should only be one VDI in this SR - VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); + final VDI srcVdi = srcSr.getVDIs(conn).iterator().next(); destVdi = srcVdi.copy(conn, destSr); - String nameLabel = "cloud-" + UUID.randomUUID().toString(); + final String nameLabel = "cloud-" + UUID.randomUUID().toString(); destVdi.setNameLabel(conn, nameLabel); // scan makes XenServer pick up VDI physicalSize destSr.scan(conn); - String templateUuid = destVdi.getUuid(conn); - String templateFilename = templateUuid + ".vhd"; - long virtualSize = destVdi.getVirtualSize(conn); - long physicalSize = destVdi.getPhysicalUtilisation(conn); + final String templateUuid = destVdi.getUuid(conn); + final String templateFilename = templateUuid + ".vhd"; + final long virtualSize = destVdi.getVirtualSize(conn); + final long physicalSize = destVdi.getPhysicalUtilisation(conn); // create the template.properties file String templatePath = destNfsPath + "/" + destDir; templatePath = templatePath.replaceAll("//", "/"); - result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, nameLabel, null, - physicalSize, virtualSize, templateObjTO.getId()); + result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, nameLabel, null, physicalSize, virtualSize, + templateObjTO.getId()); if (!result) { throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir"); } - TemplateObjectTO newTemplate = new TemplateObjectTO(); + final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(destDir + "/" + templateFilename); newTemplate.setFormat(Storage.ImageFormat.VHD); @@ -1110,19 +1111,22 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { result = true; return new CopyCmdAnswer(newTemplate); -// } catch (Exception ex) { -// s_logger.error("Failed to create a template from a snapshot", ex); -// -// return new CopyCmdAnswer("Failed to create a template from a snapshot: " + ex.toString()); - } catch (BadServerResponse e) { - s_logger.error("Failed to create a template from a snapshot due to incomprehensible server response", e); + // } catch (Exception ex) { + // s_logger.error("Failed to create a template from a snapshot", + // ex); + // + // return new + // CopyCmdAnswer("Failed to create a template from a snapshot: " + + // ex.toString()); + } catch (final BadServerResponse e) { + s_logger.error("Failed to create a template from a snapshot due to incomprehensible server response", e); - return new CopyCmdAnswer("Failed to create a template from a snapshot: " + e.toString()); - } catch (XenAPIException e) { - s_logger.error("Failed to create a template from a snapshot due to xenapi error", e); + return new CopyCmdAnswer("Failed to create a template from a snapshot: " + e.toString()); + } catch (final XenAPIException e) { + s_logger.error("Failed to create a template from a snapshot due to xenapi error", e); - return new CopyCmdAnswer("Failed to create a template from a snapshot: " + e.toString()); - } catch (XmlRpcException e) { + return new CopyCmdAnswer("Failed to create a template from a snapshot: " + e.toString()); + } catch (final XmlRpcException e) { s_logger.error("Failed to create a template from a snapshot due to rpc error", e); return new CopyCmdAnswer("Failed to create a template from a snapshot: " + e.toString()); @@ -1131,7 +1135,7 @@ public class Xenserver625StorageProcessor extends XenServerStorageProcessor { if (destVdi != null) { try { destVdi.destroy(conn); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Cleaned up leftover VDI on destination storage due to failure: ", e); } } diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XsHost.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XsHost.java new file mode 100644 index 00000000000..e17a017e6f4 --- /dev/null +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/XsHost.java @@ -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(); + } +} \ No newline at end of file diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixReadyCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixReadyCommandWrapper.java new file mode 100644 index 00000000000..d4c73ebb272 --- /dev/null +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixReadyCommandWrapper.java @@ -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 { + + 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 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); + } +} \ No newline at end of file diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapper.java index 5495f60c7a6..f2a921c0f72 100644 --- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapper.java +++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapper.java @@ -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() { diff --git a/plugins/hypervisors/xenserver/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java b/plugins/hypervisors/xenserver/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java index 161a7b22abf..4971eb38593 100644 --- a/plugins/hypervisors/xenserver/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java +++ b/plugins/hypervisors/xenserver/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java @@ -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 classes = new HashSet(); + final Set classes = new HashSet(); 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 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 _classes; String _token = ""; - public VmEventListener(boolean isMaster) { + public VmEventListener(final boolean isMaster) { _isMaster = isMaster; _classes = new HashSet(); _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 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> diff = _changes; + final HashMap> diff = _changes; _changes = new HashMap>(); return diff; } diff --git a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/CitrixResourceBaseTest.java b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/CitrixResourceBaseTest.java index 0c2944c8d8f..e79e8af5039 100644 --- a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/CitrixResourceBaseTest.java +++ b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/CitrixResourceBaseTest.java @@ -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 vms = mock(Set.class); + final Set 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 args = mock(HashMap.class); + final Map 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 args = mock(HashMap.class); + final Map 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"); } } diff --git a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapperTest.java b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapperTest.java index f8af54336e7..3e7fb574bcc 100644 --- a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapperTest.java +++ b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixRequestWrapperTest.java @@ -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()); + } } \ No newline at end of file