Merge remote-tracking branch 'sbp/refactor/citrix_resource_base-REBASE'

This closes #137

Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com>
This commit is contained in:
Rohit Yadav 2015-04-02 23:51:50 +05:30
commit 3e28747881
93 changed files with 12298 additions and 7728 deletions

View File

@ -26,16 +26,16 @@ public class Answer extends Command {
this(null);
}
public Answer(Command command) {
public Answer(final Command command) {
this(command, true, null);
}
public Answer(Command command, boolean success, String details) {
public Answer(final Command command, final boolean success, final String details) {
result = success;
this.details = details;
}
public Answer(Command command, Exception e) {
public Answer(final Command command, final Exception e) {
this(command, false, ExceptionUtil.toString(e));
}
@ -52,11 +52,11 @@ public class Answer extends Command {
return false;
}
public static UnsupportedAnswer createUnsupportedCommandAnswer(Command cmd) {
return new UnsupportedAnswer(cmd, "Unsupported command issued:" + cmd.toString() + ". Are you sure you got the right type of server?");
public static UnsupportedAnswer createUnsupportedCommandAnswer(final Command cmd) {
return new UnsupportedAnswer(cmd, "Unsupported command issued: " + cmd.toString() + ". Are you sure you got the right type of server?");
}
public static UnsupportedAnswer createUnsupportedVersionAnswer(Command cmd) {
public static UnsupportedAnswer createUnsupportedVersionAnswer(final Command cmd) {
return new UnsupportedAnswer(cmd, "Unsuppored Version.");
}
}
}

View File

@ -31,8 +31,8 @@ public abstract class AbstractDownloadCommand extends SsCommand {
protected AbstractDownloadCommand() {
}
protected AbstractDownloadCommand(String name, String url, ImageFormat format, Long accountId) {
assert (url != null);
protected AbstractDownloadCommand(final String name, String url, final ImageFormat format, final Long accountId) {
assert url != null;
url = url.replace('\\', '/');
this.url = url;
@ -41,14 +41,14 @@ public abstract class AbstractDownloadCommand extends SsCommand {
this.name = name;
}
protected AbstractDownloadCommand(AbstractDownloadCommand that) {
protected AbstractDownloadCommand(final AbstractDownloadCommand that) {
super(that);
assert (that.url != null);
assert that.url != null;
this.url = that.url.replace('\\', '/');
this.format = that.format;
this.accountId = that.accountId;
this.name = that.name;
url = that.url.replace('\\', '/');
format = that.format;
accountId = that.accountId;
name = that.name;
}
public String getUrl() {
@ -73,7 +73,7 @@ public abstract class AbstractDownloadCommand extends SsCommand {
}
public void setUrl(String url) {
assert (url != null);
assert url != null;
url = url.replace('\\', '/');
this.url = url;
}

View File

@ -37,22 +37,13 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand {
String primaryStorageUrl;
protected PrimaryStorageDownloadCommand() {
}
public PrimaryStorageDownloadCommand(String url, StoragePool pool, int wait) {
super(null, url, null, null);
this.poolId = pool.getId();
this.poolUuid = pool.getUuid();
this.primaryPool = new StorageFilerTO(pool);
setWait(wait);
}
public PrimaryStorageDownloadCommand(String name, String url, ImageFormat format, long accountId, StoragePool pool, int wait) {
public PrimaryStorageDownloadCommand(final String name, final String url, final ImageFormat format, final long accountId, final StoragePool pool, final int wait) {
super(name, url, format, accountId);
this.poolId = pool.getId();
this.poolUuid = pool.getUuid();
this.primaryPool = new StorageFilerTO(pool);
poolId = pool.getId();
poolUuid = pool.getUuid();
primaryPool = new StorageFilerTO(pool);
setWait(wait);
}
@ -68,15 +59,15 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand {
return primaryPool;
}
public void setLocalPath(String path) {
this.localPath = path;
public void setLocalPath(final String path) {
localPath = path;
}
public String getLocalPath() {
return localPath;
}
public void setSecondaryStorageUrl(String url) {
public void setSecondaryStorageUrl(final String url) {
secondaryStorageUrl = url;
}
@ -84,7 +75,7 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand {
return secondaryStorageUrl;
}
public void setPrimaryStorageUrl(String url) {
public void setPrimaryStorageUrl(final String url) {
primaryStorageUrl = url;
}

View File

@ -0,0 +1,98 @@
//
// 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.resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
public abstract class CommandWrapper<T extends Command, A extends Answer, R extends ServerResource> {
private static final Logger s_logger = Logger.getLogger(CommandWrapper.class);
/**
* @param T is the command to be used.
* @param R is the resource base to be used.
* @return A and the Answer from the command.
*/
public abstract A execute(T command, R serverResource);
/**
* Common method so we added it here.
*
* @param cmd
* @param proxyVmId
* @param proxyVmName
* @param proxyManagementIp
* @param cmdPort
* @return
*/
protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) {
String result = null;
final StringBuffer sb = new StringBuffer();
sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus");
boolean success = true;
try {
final URL url = new URL(sb.toString());
final URLConnection conn = url.openConnection();
// setting TIMEOUTs to avoid possible waiting until death situations
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
final InputStream is = conn.getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb2.append(line + "\n");
}
result = sb2.toString();
} catch (final IOException e) {
success = false;
} finally {
try {
is.close();
} catch (final IOException e) {
s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp);
success = false;
}
}
} catch (final IOException e) {
s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp);
success = false;
}
return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result);
}
}

View File

@ -1,3 +1,4 @@
//
// 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
@ -14,26 +15,18 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.ha;
package com.cloud.resource;
import static org.junit.Assert.assertEquals;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import org.junit.Test;
public abstract class RequestWrapper {
public class XenServerFencerTest {
@Test
public void testSetAndGetName() throws Exception {
XenServerFencer xenServerFencer = new XenServerFencer();
String name = "name";
xenServerFencer.setName(name);
String actual = xenServerFencer.getName();
assertEquals(name, actual);
}
}
/**
* @param command to be executed.
* @return an Answer for the executed command.
*/
public abstract Answer execute(Command command, ServerResource serverResource);
}

View File

@ -34,19 +34,19 @@ public class AnswerTest {
@Test
public void testExecuteInSequence() {
boolean b = a.executeInSequence();
final boolean b = a.executeInSequence();
assertFalse(b);
}
@Test
public void testGetResult() {
boolean b = a.getResult();
final boolean b = a.getResult();
assertTrue(b);
}
@Test
public void testGetDetails() {
String d = a.getDetails();
final String d = a.getDetails();
assertTrue(d.equals("details"));
}
@ -60,7 +60,7 @@ public class AnswerTest {
assertFalse(b);
String d = usa.getDetails();
assertTrue(d.equals("Unsupported command issued:" + acc.toString() + ". Are you sure you got the right type of server?"));
assertTrue(d.contains("Unsupported command issued: " + acc.toString() + ". Are you sure you got the right type of server?"));
usa = Answer.createUnsupportedVersionAnswer(acc);
b = usa.executeInSequence();

View File

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

View File

@ -27,15 +27,6 @@ import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.NetworkUsageAnswer;
@ -49,6 +40,14 @@ import com.cloud.resource.ServerResource;
import com.cloud.storage.Storage;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
@Local(value = ServerResource.class)
public class XcpOssResource extends CitrixResourceBase {
@ -57,55 +56,55 @@ public class XcpOssResource extends CitrixResourceBase {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xcposs/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xcposs/patch";
final String patchfilePath = Script.findScript("", patch);
if (patchfilePath == null) {
throw new CloudRuntimeException("Unable to find patch file " + patch);
}
File file = new File(patchfilePath);
final File file = new File(patchfilePath);
files.add(file);
return files;
}
@Override
protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) {
protected void fillHostInfo(final Connection conn, final StartupRoutingCommand cmd) {
super.fillHostInfo(conn, cmd);
cmd.setCaps(cmd.getCapabilities() + " , hvm");
}
@Override
protected boolean launchHeartBeat(Connection conn) {
public 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) {
public synchronized VBD createPatchVbd(final Connection conn, final String vmName, final VM vm) throws XmlRpcException, XenAPIException {
if (_host.getLocalSRuuid() != null) {
//create an iso vdi on it
String result = callHostPlugin(conn, "vmops", "createISOVHD", "uuid", _host.localSRuuid);
final String result = callHostPlugin(conn, "vmops", "createISOVHD", "uuid", _host.getLocalSRuuid());
if (result == null || result.equalsIgnoreCase("Failed")) {
throw new CloudRuntimeException("can not create systemvm vdi");
}
Set<VDI> vdis = VDI.getByNameLabel(conn, "systemvm-vdi");
final Set<VDI> vdis = VDI.getByNameLabel(conn, "systemvm-vdi");
if (vdis.size() != 1) {
throw new CloudRuntimeException("can not find systemvmiso");
}
VDI systemvmVDI = vdis.iterator().next();
final VDI systemvmVDI = vdis.iterator().next();
VBD.Record cdromVBDR = new VBD.Record();
final VBD.Record cdromVBDR = new VBD.Record();
cdromVBDR.VM = vm;
cdromVBDR.empty = false;
cdromVBDR.bootable = false;
@ -146,32 +145,32 @@ public class XcpOssResource extends CitrixResourceBase {
cdromVBDR.mode = Types.VbdMode.RO;
cdromVBDR.type = Types.VbdType.DISK;
cdromVBDR.VDI = systemvmVDI;
VBD cdromVBD = VBD.create(conn, cdromVBDR);
final VBD cdromVBD = VBD.create(conn, cdromVBDR);
return cdromVBD;
} else {
throw new CloudRuntimeException("can not find local sr");
}
}
protected NetworkUsageAnswer execute(NetworkUsageCommand cmd) {
protected NetworkUsageAnswer execute(final NetworkUsageCommand cmd) {
try {
Connection conn = getConnection();
final Connection conn = getConnection();
if (cmd.getOption() != null && cmd.getOption().equals("create")) {
String result = networkUsage(conn, cmd.getPrivateIP(), "create", null);
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
final String result = networkUsage(conn, cmd.getPrivateIP(), "create", null);
final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
return answer;
}
long[] stats = getNetworkStats(conn, cmd.getPrivateIP());
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
final long[] stats = getNetworkStats(conn, cmd.getPrivateIP());
final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
return answer;
} catch (Exception ex) {
} catch (final Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(cmd, ex);
}
}
@Override
public Answer executeRequest(Command cmd) {
public Answer executeRequest(final Command cmd) {
if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand) cmd);
} else {
@ -180,18 +179,18 @@ public class XcpOssResource extends CitrixResourceBase {
}
@Override
public StopAnswer execute(StopCommand cmd) {
StopAnswer answer = super.execute(cmd);
String vmName = cmd.getVmName();
public StopAnswer execute(final StopCommand cmd) {
final StopAnswer answer = super.execute(cmd);
final String vmName = cmd.getVmName();
if (vmName.startsWith("v-")) {
Connection conn = getConnection();
final Connection conn = getConnection();
callHostPlugin(conn, "vmops", "setDNATRule", "add", "false");
}
return answer;
}
@Override
protected void setMemory(Connection conn, VM vm, long minMemsize, long maxMemsize) throws XmlRpcException, XenAPIException {
protected void setMemory(final Connection conn, final VM vm, final long minMemsize, final long maxMemsize) throws XmlRpcException, XenAPIException {
vm.setMemoryLimits(conn, mem_32m, maxMemsize, minMemsize, maxMemsize);
}
}

View File

@ -25,11 +25,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.Types.XenAPIException;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.NetworkUsageAnswer;
@ -37,19 +32,22 @@ import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.resource.ServerResource;
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.Types.XenAPIException;
import com.xensource.xenapi.VM;
@Local(value = ServerResource.class)
public class XcpServerResource extends CitrixResourceBase {
private final static Logger s_logger = Logger.getLogger(XcpServerResource.class);
private static final long mem_32m = 33554432L;
private String version;
public XcpServerResource() {
super();
}
@Override
public Answer executeRequest(Command cmd) {
public Answer executeRequest(final Command cmd) {
if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand)cmd);
} else {
@ -59,29 +57,29 @@ public class XcpServerResource extends CitrixResourceBase {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xcpserver/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xcpserver/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;
}
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);
}
@ -137,17 +135,17 @@ public class XcpServerResource extends CitrixResourceBase {
cf: https://wiki.xenserver.org/index.php?title=XCP_FAQ_Dynamic_Memory_Control
*/
@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 {
//setMemoryLimits(staticMin, staticMax, dynamicMin, dynamicMax)
if (s_logger.isDebugEnabled()) {
s_logger.debug("Memory Limits for VM [" + vm.getNameLabel(conn) + "[staticMin:" + mem_32m + ", staticMax:" + maxMemsize + ", dynamicMin: " + minMemsize +
", dynamicMax:" + maxMemsize + "]]");
", dynamicMax:" + maxMemsize + "]]");
}
vm.setMemoryLimits(conn, mem_32m, maxMemsize, minMemsize, maxMemsize);
}
@Override
protected boolean isDmcEnabled(Connection conn, Host host) {
public boolean isDmcEnabled(final Connection conn, final Host host) {
//Dynamic Memory Control (DMC) is a technology provided by Xen Cloud Platform (XCP), starting from the 0.5 release
//For the supported XCPs dmc is default enabled, XCP 1.0.0, 1.1.0, 1.4.x, 1.5 beta, 1.6.x;
return true;

View File

@ -18,33 +18,22 @@ package com.cloud.hypervisor.xenserver.resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.resource.ServerResource;
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.Types.XenAPIException;
@Local(value = ServerResource.class)
public class XenServer56FP1Resource extends XenServer56Resource {
private static final long mem_128m = 134217728L;
private static final Logger s_logger = Logger.getLogger(XenServer56FP1Resource.class);
public XenServer56FP1Resource() {
super();
@ -52,63 +41,17 @@ public class XenServer56FP1Resource extends XenServer56Resource {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver56fp1/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver56fp1/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 FenceAnswer execute(FenceCommand cmd) {
Connection conn = getConnection();
try {
Boolean alive = check_heartbeat(cmd.getHostGuid());
if ( alive == null ) {
s_logger.debug("Failed to check heartbeat, so unable to fence");
return new FenceAnswer(cmd, false, "Failed to check heartbeat, so unable to fence");
}
if ( alive ) {
s_logger.debug("Heart beat is still going so unable to fence");
return new FenceAnswer(cmd, false, "Heartbeat is still going on unable to fence");
}
Set<VM> vms = VM.getByNameLabel(conn, cmd.getVmName());
for (VM vm : vms) {
Set<VDI> vdis = new HashSet<VDI>();
Set<VBD> vbds = vm.getVBDs(conn);
for (VBD vbd : vbds) {
VDI vdi = vbd.getVDI(conn);
if (!isRefNull(vdi)) {
vdis.add(vdi);
}
}
s_logger.info("Fence command for VM " + cmd.getVmName());
vm.powerStateReset(conn);
vm.destroy(conn);
for (VDI vdi : vdis) {
Map<String, String> smConfig = vdi.getSmConfig(conn);
for (String key : smConfig.keySet()) {
if (key.startsWith("host_")) {
vdi.removeFromSmConfig(conn, key);
break;
}
}
}
}
return new FenceAnswer(cmd);
} catch (XmlRpcException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
} catch (XenAPIException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
}
}
/**
* When Dynamic Memory Control (DMC) is enabled -
* xenserver allows scaling the guest memory while the guest is running
@ -117,9 +60,9 @@ public class XenServer56FP1Resource extends XenServer56Resource {
* When false, scaling is allowed hence DMC is enabled
*/
@Override
protected boolean isDmcEnabled(Connection conn, Host host) throws XenAPIException, XmlRpcException {
Map<String, String> hostParams = host.getLicenseParams(conn);
Boolean isDmcEnabled = hostParams.get("restrict_dmc").equalsIgnoreCase("false");
public boolean isDmcEnabled(final Connection conn, final Host host) throws XenAPIException, XmlRpcException {
final Map<String, String> hostParams = host.getLicenseParams(conn);
final Boolean isDmcEnabled = hostParams.get("restrict_dmc").equalsIgnoreCase("false");
return isDmcEnabled;
}
}

View File

@ -19,13 +19,20 @@ package com.cloud.hypervisor.xenserver.resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
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.StartupCommand;
import com.cloud.hypervisor.xenserver.resource.wrapper.CitrixRequestWrapper;
import com.cloud.resource.ServerResource;
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.Network;
@ -33,98 +40,81 @@ import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Types.IpConfigurationMode;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VLAN;
import com.xensource.xenapi.VM;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.resource.ServerResource;
import com.cloud.utils.ExecutionResult;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SSHCmdHelper;
@Local(value = ServerResource.class)
public class XenServer56Resource extends CitrixResourceBase {
private final static Logger s_logger = Logger.getLogger(XenServer56Resource.class);
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof FenceCommand) {
return execute((FenceCommand)cmd);
} else if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand)cmd);
} else {
public Answer executeRequest(final Command cmd) {
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
try {
return wrapper.execute(cmd, this);
} catch (final Exception e) {
return super.executeRequest(cmd);
}
}
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver56/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver56/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 disableVlanNetwork(Connection conn, Network network) {
public void disableVlanNetwork(final Connection conn, final Network network) {
try {
Network.Record networkr = network.getRecord(conn);
final Network.Record networkr = network.getRecord(conn);
if (!networkr.nameLabel.startsWith("VLAN")) {
return;
}
String bridge = networkr.bridge.trim();
for (PIF pif : networkr.PIFs) {
PIF.Record pifr = pif.getRecord(conn);
if (!pifr.host.getUuid(conn).equalsIgnoreCase(_host.uuid)) {
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.getUuid())) {
continue;
}
VLAN vlan = pifr.VLANMasterOf;
final VLAN vlan = pifr.VLANMasterOf;
if (vlan != null) {
String vlannum = pifr.VLAN.toString();
String device = pifr.device.trim();
final String vlannum = pifr.VLAN.toString();
final String device = pifr.device.trim();
if (vlannum.equals("-1")) {
return;
}
try {
vlan.destroy(conn);
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 (XenAPIException e) {
s_logger.trace("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.uuid + " due to " + e.toString());
} catch (final XenAPIException e) {
s_logger.trace("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.getUuid() + " due to " + e.toString());
}
}
return;
}
} catch (XenAPIException e) {
String msg = "Unable to disable VLAN network due to " + e.toString();
} catch (final XenAPIException e) {
final String msg = "Unable to disable VLAN network due to " + e.toString();
s_logger.warn(msg, e);
} catch (Exception e) {
String msg = "Unable to disable VLAN network due to " + e.getMessage();
} catch (final Exception e) {
final String msg = "Unable to disable VLAN network due to " + e.getMessage();
s_logger.warn(msg, e);
}
}
@Override
protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) {
public String networkUsage(final Connection conn, final String privateIpAddress, final String option, final String vif) {
String args = "";
if (option.equals("get")) {
args += "-g";
@ -143,90 +133,22 @@ public class XenServer56Resource extends CitrixResourceBase {
return executeInVR(privateIpAddress, "netusage.sh", args).getDetails();
}
protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) {
try {
Connection conn = getConnection();
String option = cmd.getOption();
String publicIp = cmd.getGatewayIP();
String args = " -l " + publicIp + " ";
if (option.equals("get")) {
args += "-g";
} else if (option.equals("create")) {
args += "-c";
String vpcCIDR = cmd.getVpcCIDR();
args += " -v " + vpcCIDR;
} else if (option.equals("reset")) {
args += "-r";
} else if (option.equals("vpn")) {
args += "-n";
} else if (option.equals("remove")) {
args += "-d";
} else {
return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
}
ExecutionResult result = executeInVR(cmd.getPrivateIP(), "vpc_netusage.sh", args);
String detail = result.getDetails();
if (!result.isSuccess()) {
throw new Exception(" vpc network usage plugin call failed ");
}
if (option.equals("get") || option.equals("vpn")) {
long[] stats = new long[2];
if (detail != null) {
String[] splitResult = detail.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
}
return new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]);
}
}
return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
} catch (Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(cmd, ex);
}
}
protected NetworkUsageAnswer execute(NetworkUsageCommand cmd) {
if (cmd.isForVpc()) {
return VPCNetworkUsage(cmd);
}
try {
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);
return answer;
}
long[] stats = getNetworkStats(conn, cmd.getPrivateIP());
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
return answer;
} catch (Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(cmd, ex);
}
}
protected Boolean check_heartbeat(String hostuuid) {
com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.ip, 22);
public Boolean checkHeartbeat(final String hostuuid) {
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 shcmd = "/opt/cloud/bin/check_heartbeat.sh " + hostuuid + " "
+ Integer.toString(_heartbeatInterval * 2);
final String shcmd = "/opt/cloud/bin/check_heartbeat.sh " + hostuuid + " " + Integer.toString(_heartbeatInterval * 2);
if (!SSHCmdHelper.sshExecuteCmd(sshConnection, shcmd)) {
s_logger.debug("Heart beat is gone so dead.");
return false;
}
s_logger.debug("Heart beat is still going");
return true;
} catch (Exception e) {
} catch (final Exception e) {
s_logger.debug("health check failed due to catch exception " + e.toString());
return null;
} finally {
@ -234,41 +156,12 @@ public class XenServer56Resource extends CitrixResourceBase {
}
}
protected FenceAnswer execute(FenceCommand cmd) {
Connection conn = getConnection();
try {
Boolean alive = check_heartbeat(cmd.getHostGuid());
if ( alive == null ) {
s_logger.debug("Failed to check heartbeat, so unable to fence");
return new FenceAnswer(cmd, false, "Failed to check heartbeat, so unable to fence");
}
if ( alive ) {
s_logger.debug("Heart beat is still going so unable to fence");
return new FenceAnswer(cmd, false, "Heartbeat is still going on unable to fence");
}
Set<VM> vms = VM.getByNameLabel(conn, cmd.getVmName());
for (VM vm : vms) {
s_logger.info("Fence command for VM " + cmd.getVmName());
vm.powerStateReset(conn);
vm.destroy(conn);
}
return new FenceAnswer(cmd);
} catch (XmlRpcException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
} catch (XenAPIException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
}
}
@Override
protected boolean transferManagementNetwork(Connection conn, Host host, PIF src, PIF.Record spr, PIF dest) throws XmlRpcException, XenAPIException {
public boolean transferManagementNetwork(final Connection conn, final Host host, final PIF src, final PIF.Record spr, final PIF dest) throws XmlRpcException, XenAPIException {
dest.reconfigureIp(conn, spr.ipConfigurationMode, spr.IP, spr.netmask, spr.gateway, spr.DNS);
Host.managementReconfigure(conn, dest);
String hostUuid = null;
int count = 0;
final int count = 0;
while (count < 10) {
try {
Thread.sleep(10000);
@ -276,11 +169,11 @@ public class XenServer56Resource extends CitrixResourceBase {
if (hostUuid != null) {
break;
}
} catch (XmlRpcException e) {
} catch (final XmlRpcException e) {
s_logger.debug("Waiting for host to come back: " + e.getMessage());
} catch (XenAPIException e) {
} catch (final XenAPIException e) {
s_logger.debug("Waiting for host to come back: " + e.getMessage());
} catch (InterruptedException e) {
} catch (final InterruptedException e) {
s_logger.debug("Gotta run");
return false;
}
@ -297,30 +190,11 @@ public class XenServer56Resource extends CitrixResourceBase {
@Override
public StartupCommand[] initialize() {
pingXAPI();
StartupCommand[] cmds = super.initialize();
final StartupCommand[] cmds = super.initialize();
return cmds;
}
@Override
protected CheckOnHostAnswer execute(CheckOnHostCommand cmd) {
Boolean alive = check_heartbeat(cmd.getHost().getGuid());
String msg = "";
if (alive == null) {
msg = " cannot determine ";
} else if ( alive == true) {
msg = "Heart beat is still going";
} else {
msg = "Heart beat is gone so dead.";
}
s_logger.debug(msg);
return new CheckOnHostAnswer(cmd, alive, msg);
}
public XenServer56Resource() {
super();
}
}
}

View File

@ -22,15 +22,12 @@ import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.resource.ServerResource;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
@Local(value = ServerResource.class)
public class XenServer56SP2Resource extends XenServer56FP1Resource {
private static final Logger s_logger = Logger.getLogger(XenServer56SP2Resource.class);
public XenServer56SP2Resource() {
super();
@ -40,13 +37,13 @@ public class XenServer56SP2Resource extends XenServer56FP1Resource {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver56fp1/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver56fp1/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;
}

View File

@ -22,29 +22,22 @@ import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.resource.ServerResource;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
@Local(value = ServerResource.class)
public class XenServer600Resource extends XenServer56SP2Resource {
private static final Logger s_logger = Logger.getLogger(XenServer600Resource.class);
public XenServer600Resource() {
super();
}
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver60/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver60/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;
}

View File

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

View File

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

View File

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

View File

@ -18,32 +18,28 @@
*/
package com.cloud.hypervisor.xenserver.resource;
import com.cloud.resource.ServerResource;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import org.apache.log4j.Logger;
import javax.ejb.Local;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Local;
import com.cloud.resource.ServerResource;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
@Local(value=ServerResource.class)
public class XenServer650Resource extends Xenserver625Resource {
private static final Logger s_logger = Logger.getLogger(XenServer650Resource.class);
public XenServer650Resource() {
super();
}
@Override
protected List<File> getPatchFiles() {
List files = new ArrayList();
String patch = "scripts/vm/hypervisor/xenserver/xenserver65/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver65/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;
}

View File

@ -24,22 +24,20 @@ import java.util.List;
import javax.ejb.Local;
import org.apache.cloudstack.hypervisor.xenserver.XenServerResourceNewBase;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VM;
import org.apache.cloudstack.hypervisor.xenserver.XenServerResourceNewBase;
import com.cloud.resource.ServerResource;
import com.cloud.storage.resource.StorageSubsystemCommandHandler;
import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SSHCmdHelper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VM;
@Local(value=ServerResource.class)
public class Xenserver625Resource extends XenServerResourceNewBase {
@ -51,49 +49,48 @@ public class Xenserver625Resource extends XenServerResourceNewBase {
@Override
protected List<File> getPatchFiles() {
List<File> files = new ArrayList<File>();
String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch";
String patchfilePath = Script.findScript("", patch);
final List<File> files = new ArrayList<File>();
final String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch";
final String patchfilePath = Script.findScript("", patch);
if (patchfilePath == null) {
throw new CloudRuntimeException("Unable to find patch file " + patch);
}
File file = new File(patchfilePath);
final File file = new File(patchfilePath);
files.add(file);
return files;
}
@Override
protected StorageSubsystemCommandHandler getStorageHandler() {
XenServerStorageProcessor processor = new Xenserver625StorageProcessor(this);
protected StorageSubsystemCommandHandler buildStorageHandler() {
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);
public 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 {
public String revertToSnapshot(final Connection conn, final VM vmSnapshot,
final String vmName, final String oldVmUuid, final Boolean snapshotMemory, final String hostUUID)
throws Types.XenAPIException, XmlRpcException {
String results = callHostPluginAsync(conn, "vmopsSnapshot",
final String results = callHostPluginAsync(conn, "vmopsSnapshot",
"revert_memory_snapshot", 10 * 60 * 1000, "snapshotUUID",
vmSnapshot.getUuid(conn), "vmName", vmName, "oldVmUuid",
oldVmUuid, "snapshotMemory", snapshotMemory.toString(), "hostUUID", hostUUID);

View File

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

View File

@ -0,0 +1,91 @@
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Types.XenAPIException;
/**
* XsNic represents a network and the host's specific PIF.
*/
public class XsLocalNetwork {
private static final Logger s_logger = Logger.getLogger(XsLocalNetwork.class);
private final CitrixResourceBase _citrixResourceBase;
private final Network _n;
private Network.Record _nr;
private PIF _p;
private PIF.Record _pr;
public XsLocalNetwork(final CitrixResourceBase citrixResourceBase, final Network n) {
this(citrixResourceBase, n, null, null, null);
}
public XsLocalNetwork(final CitrixResourceBase citrixResourceBase, final Network n, final Network.Record nr, final PIF p, final PIF.Record pr) {
_citrixResourceBase = citrixResourceBase;
_n = n;
_nr = nr;
_p = p;
_pr = pr;
}
public Network getNetwork() {
return _n;
}
public Network.Record getNetworkRecord(final Connection conn) throws XenAPIException, XmlRpcException {
if (_nr == null) {
_nr = _n.getRecord(conn);
}
return _nr;
}
public PIF getPif(final Connection conn) throws XenAPIException, XmlRpcException {
if (_p == null) {
final Network.Record nr = getNetworkRecord(conn);
for (final PIF pif : nr.PIFs) {
final PIF.Record pr = pif.getRecord(conn);
if (_citrixResourceBase.getHost().getUuid().equals(pr.host.getUuid(conn))) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a network called " + nr.nameLabel + " on host=" + _citrixResourceBase.getHost().getIp() + "; Network=" + nr.uuid + "; pif=" + pr.uuid);
}
_p = pif;
_pr = pr;
break;
}
}
}
return _p;
}
public PIF.Record getPifRecord(final Connection conn) throws XenAPIException, XmlRpcException {
if (_pr == null) {
final PIF p = getPif(conn);
if (_pr == null) {
_pr = p.getRecord(conn);
}
}
return _pr;
}
}

View File

@ -0,0 +1,134 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
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;
public final class CitrixAttachIsoCommandWrapper extends CommandWrapper<AttachIsoCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixAttachIsoCommandWrapper.class);
@Override
public Answer execute(final AttachIsoCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final boolean attach = command.isAttach();
final String vmName = command.getVmName();
final String isoURL = command.getIsoPath();
String errorMsg;
if (attach) {
errorMsg = "Failed to attach ISO";
} else {
errorMsg = "Failed to detach ISO";
}
try {
if (attach) {
VBD isoVBD = null;
// Find the VM
final VM vm = citrixResourceBase.getVM(conn, vmName);
// Find the ISO VDI
final VDI isoVDI = citrixResourceBase.getIsoVDIByURL(conn, vmName, isoURL);
// Find the VM's CD-ROM VBD
final Set<VBD> 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;
break;
}
}
if (isoVBD == null) {
throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName);
} else {
// If an ISO is already inserted, eject it
if (isoVBD.getEmpty(conn) == false) {
isoVBD.eject(conn);
}
// Insert the new ISO
isoVBD.insert(conn, isoVDI);
}
return new Answer(command);
} else {
// Find the VM
final VM vm = citrixResourceBase.getVM(conn, vmName);
final String vmUUID = vm.getUuid(conn);
// Find the ISO VDI
final VDI isoVDI = citrixResourceBase.getIsoVDIByURL(conn, vmName, isoURL);
final SR sr = isoVDI.getSR(conn);
// Look up all VBDs for this VDI
final Set<VBD> vbds = isoVDI.getVBDs(conn);
// Iterate through VBDs, and if the VBD belongs the VM, eject
// the ISO from it
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
if (!vbd.getEmpty(conn)) {
vbd.eject(conn);
}
break;
}
}
if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) {
citrixResourceBase.removeSR(conn, sr);
}
return new Answer(command);
}
} catch (final XenAPIException e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new Answer(command, false, e.toString());
} catch (final Exception e) {
s_logger.warn(errorMsg + ": " + e.toString(), e);
return new Answer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,144 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachVolumeAnswer;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
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;
public final class CitrixAttachVolumeCommandWrapper extends CommandWrapper<AttachVolumeCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixAttachVolumeCommandWrapper.class);
@Override
public Answer execute(final AttachVolumeCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final boolean attach = command.getAttach();
final String vmName = command.getVmName();
final String vdiNameLabel = vmName + "-DATA";
final Long deviceId = command.getDeviceId();
String errorMsg;
if (attach) {
errorMsg = "Failed to attach volume";
} else {
errorMsg = "Failed to detach volume";
}
try {
VDI vdi = null;
if (command.getAttach() && command.isManaged()) {
final SR sr = citrixResourceBase.getIscsiSR(conn, command.get_iScsiName(), command.getStorageHost(), command.get_iScsiName(), command.getChapInitiatorUsername(),
command.getChapInitiatorPassword(), true);
vdi = citrixResourceBase.getVDIbyUuid(conn, command.getVolumePath(), false);
if (vdi == null) {
vdi = citrixResourceBase.createVdi(sr, vdiNameLabel, command.getVolumeSize());
}
} else {
vdi = citrixResourceBase.getVDIbyUuid(conn, command.getVolumePath());
}
// Look up the VM
final VM vm = citrixResourceBase.getVM(conn, vmName);
if (attach) {
// Figure out the disk number to attach the VM to
String diskNumber = null;
if (deviceId != null) {
if (deviceId.longValue() == 3) {
final String msg = "Device 3 is reserved for CD-ROM, choose other device";
return new AttachVolumeAnswer(command, msg);
}
if (citrixResourceBase.isDeviceUsed(conn, vm, deviceId)) {
final String msg = "Device " + deviceId + " is used in VM " + vmName;
return new AttachVolumeAnswer(command, msg);
}
diskNumber = deviceId.toString();
} else {
diskNumber = citrixResourceBase.getUnusedDeviceNum(conn, vm);
}
// Create a new VBD
final VBD.Record vbdr = new VBD.Record();
vbdr.VM = vm;
vbdr.VDI = vdi;
vbdr.bootable = false;
vbdr.userdevice = diskNumber;
vbdr.mode = Types.VbdMode.RW;
vbdr.type = Types.VbdType.DISK;
vbdr.unpluggable = true;
final VBD vbd = VBD.create(conn, vbdr);
// Attach the VBD to the VM
vbd.plug(conn);
// Update the VDI's label to include the VM name
vdi.setNameLabel(conn, vdiNameLabel);
return new AttachVolumeAnswer(command, Long.parseLong(diskNumber), vdi.getUuid(conn));
} else {
// Look up all VBDs for this VDI
final Set<VBD> vbds = vdi.getVBDs(conn);
// Detach each VBD from its VM, and then destroy it
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.currentlyAttached) {
vbd.unplug(conn);
}
vbd.destroy(conn);
}
// Update the VDI's label to be "detached"
vdi.setNameLabel(conn, "detached");
if (command.isManaged()) {
citrixResourceBase.handleSrAndVdiDetach(command.get_iScsiName(), conn);
}
return new AttachVolumeAnswer(command);
}
} catch (final XenAPIException e) {
final String msg = errorMsg + " for uuid: " + command.getVolumePath() + " due to " + e.toString();
s_logger.warn(msg, e);
return new AttachVolumeAnswer(command, msg);
} catch (final Exception e) {
final String msg = errorMsg + " for uuid: " + command.getVolumePath() + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new AttachVolumeAnswer(command, msg);
}
}
}

View File

@ -0,0 +1,38 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixCheckConsoleProxyLoadCommandWrapper extends CommandWrapper<CheckConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final CheckConsoleProxyLoadCommand command, final CitrixResourceBase citrixResourceBase) {
final long proxyVmId = command.getProxyVmId();
final String proxyVmName = command.getProxyVmName();
final String proxyManagementIp = command.getProxyManagementIp();
final int cmdPort = command.getProxyCmdPort();
return executeProxyLoadScan(command, proxyVmId, proxyVmName, proxyManagementIp, cmdPort);
}
}

View File

@ -0,0 +1,35 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixCheckHealthCommandWrapper extends CommandWrapper<CheckHealthCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final CheckHealthCommand command, final CitrixResourceBase citrixResourceBase) {
final boolean result = citrixResourceBase.pingXAPI();
return new CheckHealthAnswer(command, result);
}
}

View File

@ -0,0 +1,94 @@
//
// 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.List;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckNetworkAnswer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.network.PhysicalNetworkSetupInfo;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixCheckNetworkCommandWrapper extends CommandWrapper<CheckNetworkCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCheckNetworkCommandWrapper.class);
@Override
public Answer execute(final CheckNetworkCommand command, final CitrixResourceBase citrixResourceBase) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Checking if network name setup is done on the resource");
}
final List<PhysicalNetworkSetupInfo> infoList = command.getPhysicalNetworkInfoList();
try {
boolean errorout = false;
String msg = "";
for (final PhysicalNetworkSetupInfo info : infoList) {
if (!citrixResourceBase.isNetworkSetupByName(info.getGuestNetworkName())) {
msg =
"For Physical Network id:" + info.getPhysicalNetworkId() + ", Guest Network is not configured on the backend by name " +
info.getGuestNetworkName();
errorout = true;
break;
}
if (!citrixResourceBase.isNetworkSetupByName(info.getPrivateNetworkName())) {
msg =
"For Physical Network id:" + info.getPhysicalNetworkId() + ", Private Network is not configured on the backend by name " +
info.getPrivateNetworkName();
errorout = true;
break;
}
if (!citrixResourceBase.isNetworkSetupByName(info.getPublicNetworkName())) {
msg =
"For Physical Network id:" + info.getPhysicalNetworkId() + ", Public Network is not configured on the backend by name " +
info.getPublicNetworkName();
errorout = true;
break;
}
/*if(!isNetworkSetupByName(info.getStorageNetworkName())){
msg = "For Physical Network id:"+ info.getPhysicalNetworkId() + ", Storage Network is not configured on the backend by name " + info.getStorageNetworkName();
errorout = true;
break;
}*/
}
if (errorout) {
s_logger.error(msg);
return new CheckNetworkAnswer(command, false, msg);
} else {
return new CheckNetworkAnswer(command, true, "Network Setup check by names is done");
}
} catch (final XenAPIException e) {
final String msg = "CheckNetworkCommand failed with XenAPIException:" + e.toString() + " host:" + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg, e);
return new CheckNetworkAnswer(command, false, msg);
} catch (final Exception e) {
final String msg = "CheckNetworkCommand failed with Exception:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg, e);
return new CheckNetworkAnswer(command, false, msg);
}
}
}

View File

@ -0,0 +1,34 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixCheckOnHostCommandWrapper extends CommandWrapper<CheckOnHostCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final CheckOnHostCommand command, final CitrixResourceBase citrixResourceBase) {
return new CheckOnHostAnswer(command, "Not Implmeneted");
}
}

View File

@ -0,0 +1,63 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixCheckSshCommandWrapper extends CommandWrapper<CheckSshCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCheckSshCommandWrapper.class);
@Override
public Answer execute(final CheckSshCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String vmName = command.getName();
final String privateIp = command.getIp();
final int cmdPort = command.getPort();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
}
try {
final String result = citrixResourceBase.connect(conn, command.getName(), privateIp, cmdPort);
if (result != null) {
return new CheckSshAnswer(command, "Can not ping System vm " + vmName + "due to:" + result);
}
//Do not destroy the disk here! It will stio the patching process. Please, don't!
//destroyPatchVbd(conn, vmName);
} catch (final Exception e) {
return new CheckSshAnswer(command, e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port succeeded for vm " + vmName);
}
return new CheckSshAnswer(command);
}
}

View File

@ -0,0 +1,48 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.VirtualMachine.PowerState;
import com.xensource.xenapi.Connection;
public final class CitrixCheckVirtualMachineCommandWrapper extends CommandWrapper<CheckVirtualMachineCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCheckVirtualMachineCommandWrapper.class);
@Override
public Answer execute(final CheckVirtualMachineCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String vmName = command.getVmName();
final PowerState powerState = citrixResourceBase.getVmState(conn, vmName);
final Integer vncPort = null;
if (powerState == PowerState.PowerOn) {
s_logger.debug("3. The VM " + vmName + " is in Running state");
}
return new CheckVirtualMachineAnswer(command, powerState, vncPort);
}
}

View File

@ -0,0 +1,54 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixCleanupNetworkRulesCmdWrapper extends CommandWrapper<CleanupNetworkRulesCmd, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCleanupNetworkRulesCmdWrapper.class);
@Override
public Answer execute(final CleanupNetworkRulesCmd command, final CitrixResourceBase citrixResourceBase) {
if (!citrixResourceBase.canBridgeFirewall()) {
return new Answer(command, true, null);
}
final Connection conn = citrixResourceBase.getConnection();
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "cleanup_rules", "instance", citrixResourceBase.getVMInstanceName());
final int numCleaned = Integer.parseInt(result);
if (result == null || result.isEmpty() || numCleaned < 0) {
s_logger.warn("Failed to cleanup rules for host " + citrixResourceBase.getHost().getIp());
return new Answer(command, false, result);
}
if (numCleaned > 0) {
s_logger.info("Cleaned up rules for " + result + " vms on host " + citrixResourceBase.getHost().getIp());
}
return new Answer(command, true, result);
}
}

View File

@ -0,0 +1,57 @@
//
// 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.HashMap;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ClusterVMMetaDataSyncAnswer;
import com.cloud.agent.api.ClusterVMMetaDataSyncCommand;
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.Pool;
public final class CitrixClusterVMMetaDataSyncCommandWrapper extends CommandWrapper<ClusterVMMetaDataSyncCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixClusterVMMetaDataSyncCommandWrapper.class);
@Override
public Answer execute(final ClusterVMMetaDataSyncCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
//check if this is master
try {
final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
final Pool.Record poolr = pool.getRecord(conn);
final Host.Record hostr = poolr.master.getRecord(conn);
if (!citrixResourceBase.getHost().getUuid().equals(hostr.uuid)) {
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
}
} catch (final Throwable e) {
s_logger.warn("Check for master failed, failing the Cluster sync VMMetaData command");
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
}
final HashMap<String, String> vmMetadatum = citrixResourceBase.clusterVMMetaDataSync(conn);
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), vmMetadatum);
}
}

View File

@ -0,0 +1,82 @@
//
// 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.HashMap;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.DiskProfile;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VDI;
public final class CitrixCreateCommandWrapper extends CommandWrapper<CreateCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCreateCommandWrapper.class);
@Override
public Answer execute(final CreateCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final StorageFilerTO pool = command.getPool();
final DiskProfile dskch = command.getDiskCharacteristics();
VDI vdi = null;
try {
final SR poolSr = citrixResourceBase.getStorageRepository(conn, pool.getUuid());
if (command.getTemplateUrl() != null) {
VDI tmpltvdi = null;
tmpltvdi = citrixResourceBase.getVDIbyUuid(conn, command.getTemplateUrl());
vdi = tmpltvdi.createClone(conn, new HashMap<String, String>());
vdi.setNameLabel(conn, dskch.getName());
} else {
final VDI.Record vdir = new VDI.Record();
vdir.nameLabel = dskch.getName();
vdir.SR = poolSr;
vdir.type = Types.VdiType.USER;
vdir.virtualSize = dskch.getSize();
vdi = VDI.create(conn, vdir);
}
VDI.Record vdir;
vdir = vdi.getRecord(conn);
s_logger.debug("Succesfully created VDI for " + command + ". Uuid = " + vdir.uuid);
final VolumeTO vol =
new VolumeTO(command.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), vdir.nameLabel, pool.getPath(), vdir.uuid, vdir.virtualSize, null);
return new CreateAnswer(command, vol);
} catch (final Exception e) {
s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e);
return new CreateAnswer(command, e);
}
}
}

View File

@ -0,0 +1,57 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.storage.Storage.StoragePoolType;
import com.xensource.xenapi.Connection;
public final class CitrixCreateStoragePoolCommandWrapper extends CommandWrapper<CreateStoragePoolCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixCreateStoragePoolCommandWrapper.class);
@Override
public Answer execute(final CreateStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final StorageFilerTO pool = command.getPool();
try {
if (pool.getType() == StoragePoolType.NetworkFilesystem) {
citrixResourceBase.getNfsSR(conn, Long.toString(pool.getId()), pool.getUuid(), pool.getHost(), pool.getPath(), pool.toString());
} else if (pool.getType() == StoragePoolType.IscsiLUN) {
citrixResourceBase.getIscsiSR(conn, pool.getUuid(), pool.getHost(), pool.getPath(), null, null, false);
} else if (pool.getType() == StoragePoolType.PreSetup) {
} else {
return new Answer(command, false, "The pool type: " + pool.getType().name() + " is not supported.");
}
return new Answer(command, true, "success");
} catch (final Exception e) {
final String msg = "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:"
+ citrixResourceBase.getHost().getUuid() + " pool: " + pool.getHost() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
}
}

View File

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

View File

@ -0,0 +1,52 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.SR;
public final class CitrixDeleteStoragePoolCommandWrapper extends CommandWrapper<DeleteStoragePoolCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixDeleteStoragePoolCommandWrapper.class);
@Override
public Answer execute(final DeleteStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final StorageFilerTO poolTO = command.getPool();
try {
final SR sr = citrixResourceBase.getStorageRepository(conn, poolTO.getUuid());
citrixResourceBase.removeSR(conn, sr);
final Answer answer = new Answer(command, true, "success");
return answer;
} catch (final Exception e) {
final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + poolTO.getHost()
+ poolTO.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
}
}

View File

@ -0,0 +1,90 @@
//
// 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.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.DeleteVMSnapshotAnswer;
import com.cloud.agent.api.DeleteVMSnapshotCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.snapshot.VMSnapshot;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
public final class CitrixDeleteVMSnapshotCommandWrapper extends CommandWrapper<DeleteVMSnapshotCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixDeleteVMSnapshotCommandWrapper.class);
@Override
public Answer execute(final DeleteVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String snapshotName = command.getTarget().getSnapshotName();
final Connection conn = citrixResourceBase.getConnection();
try {
final List<VDI> vdiList = new ArrayList<VDI>();
final Set<VM> snapshots = VM.getByNameLabel(conn, snapshotName);
if (snapshots == null || snapshots.size() == 0) {
s_logger.warn("VM snapshot with name " + snapshotName + " does not exist, assume it is already deleted");
return new DeleteVMSnapshotAnswer(command, command.getVolumeTOs());
}
final VM snapshot = snapshots.iterator().next();
final Set<VBD> vbds = snapshot.getVBDs(conn);
for (final VBD vbd : vbds) {
if (vbd.getType(conn) == Types.VbdType.DISK) {
final VDI vdi = vbd.getVDI(conn);
vdiList.add(vdi);
}
}
if (command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory) {
vdiList.add(snapshot.getSuspendVDI(conn));
}
snapshot.destroy(conn);
for (final VDI vdi : vdiList) {
vdi.destroy(conn);
}
try {
Thread.sleep(5000);
} catch (final InterruptedException ex) {
}
// re-calculate used capacify for this VM snapshot
for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
volumeTo.setSize(size);
}
return new DeleteVMSnapshotAnswer(command, command.getVolumeTOs());
} catch (final Exception e) {
s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
return new DeleteVMSnapshotAnswer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,83 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
public final class CitrixDestroyCommandWrapper extends CommandWrapper<DestroyCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixDestroyCommandWrapper.class);
@Override
public Answer execute(final DestroyCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final VolumeTO vol = command.getVolume();
// Look up the VDI
final String volumeUUID = vol.getPath();
VDI vdi = null;
try {
vdi = citrixResourceBase.getVDIbyUuid(conn, volumeUUID);
} catch (final Exception e) {
return new Answer(command, true, "Success");
}
Set<VBD> vbds = null;
try {
vbds = vdi.getVBDs(conn);
} catch (final Exception e) {
final String msg = "VDI getVBDS for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
for (final VBD vbd : vbds) {
try {
vbd.unplug(conn);
vbd.destroy(conn);
} catch (final Exception e) {
final String msg = "VM destroy for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
}
try {
final Set<VDI> snapshots = vdi.getSnapshots(conn);
for (final VDI snapshot : snapshots) {
snapshot.destroy(conn);
}
vdi.destroy(conn);
} catch (final Exception e) {
final String msg = "VDI destroy for " + volumeUUID + " failed due to " + e.toString();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
return new Answer(command, true, "Success");
}
}

View File

@ -0,0 +1,48 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetHostStatsAnswer;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixGetHostStatsCommandWrapper extends CommandWrapper<GetHostStatsCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixGetHostStatsCommandWrapper.class);
@Override
public Answer execute(final GetHostStatsCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final HostStatsEntry hostStats = citrixResourceBase.getHostStats(conn, command, command.getHostGuid(), command.getHostId());
return new GetHostStatsAnswer(command, hostStats);
} catch (final Exception e) {
final String msg = "Unable to get Host stats" + e.toString();
s_logger.warn(msg, e);
return new GetHostStatsAnswer(command, null);
}
}
}

View File

@ -0,0 +1,69 @@
//
// 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.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixGetStorageStatsCommandWrapper extends CommandWrapper<GetStorageStatsCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixGetStorageStatsCommandWrapper.class);
@Override
public Answer execute(final GetStorageStatsCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Set<SR> srs = SR.getByNameLabel(conn, command.getStorageId());
if (srs.size() != 1) {
final String msg = "There are " + srs.size() + " storageid: " + command.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(command, msg);
}
final SR sr = srs.iterator().next();
sr.scan(conn);
final long capacity = sr.getPhysicalSize(conn);
final long used = sr.getPhysicalUtilisation(conn);
return new GetStorageStatsAnswer(command, capacity, used);
} catch (final XenAPIException e) {
final String msg = "GetStorageStats Exception:" + e.toString() + "host:" + citrixResourceBase.getHost().getUuid() + "storageid: " + command.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(command, msg);
} catch (final XmlRpcException e) {
final String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + citrixResourceBase.getHost().getUuid() + "storageid: " + command.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(command, msg);
} catch (final Exception e) {
final String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + citrixResourceBase.getHost().getUuid() + "storageid: " + command.getStorageId();
s_logger.warn(msg);
return new GetStorageStatsAnswer(command, msg);
}
}
}

View File

@ -0,0 +1,34 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetVmDiskStatsAnswer;
import com.cloud.agent.api.GetVmDiskStatsCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixGetVmDiskStatsCommandWrapper extends CommandWrapper<GetVmDiskStatsCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final GetVmDiskStatsCommand command, final CitrixResourceBase citrixResourceBase) {
return new GetVmDiskStatsAnswer(command, null, null, null);
}
}

View File

@ -0,0 +1,82 @@
//
// 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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
public final class CitrixGetVmStatsCommandWrapper extends CommandWrapper<GetVmStatsCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixGetVmStatsCommandWrapper.class);
@Override
public Answer execute(final GetVmStatsCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final List<String> vmNames = command.getVmNames();
final HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
if (vmNames.size() == 0) {
return new GetVmStatsAnswer(command, vmStatsNameMap);
}
try {
// Determine the UUIDs of the requested VMs
final List<String> vmUUIDs = new ArrayList<String>();
for (final String vmName : vmNames) {
final VM vm = citrixResourceBase.getVM(conn, vmName);
vmUUIDs.add(vm.getUuid(conn));
}
final HashMap<String, VmStatsEntry> vmStatsUUIDMap = citrixResourceBase.getVmStats(conn, command, vmUUIDs, command.getHostGuid());
if (vmStatsUUIDMap == null) {
return new GetVmStatsAnswer(command, vmStatsNameMap);
}
for (final Map.Entry<String,VmStatsEntry>entry : vmStatsUUIDMap.entrySet()) {
vmStatsNameMap.put(vmNames.get(vmUUIDs.indexOf(entry.getKey())), entry.getValue());
}
return new GetVmStatsAnswer(command, vmStatsNameMap);
} catch (final XenAPIException e) {
final String msg = "Unable to get VM stats" + e.toString();
s_logger.warn(msg, e);
return new GetVmStatsAnswer(command, vmStatsNameMap);
} catch (final XmlRpcException e) {
final String msg = "Unable to get VM stats" + e.getMessage();
s_logger.warn(msg, e);
return new GetVmStatsAnswer(command, vmStatsNameMap);
}
}
}

View File

@ -0,0 +1,56 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.VM;
public final class CitrixGetVncPortCommandWrapper extends CommandWrapper<GetVncPortCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixGetVncPortCommandWrapper.class);
@Override
public Answer execute(final GetVncPortCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Set<VM> vms = VM.getByNameLabel(conn, command.getName());
if (vms.size() == 1) {
String consoleurl;
consoleurl = "consoleurl=" + citrixResourceBase.getVncUrl(conn, vms.iterator().next()) + "&" + "sessionref=" + conn.getSessionReference();
return new GetVncPortAnswer(command, consoleurl, -1);
} else {
return new GetVncPortAnswer(command, "There are " + vms.size() + " VMs named " + command.getName());
}
} catch (final Exception e) {
final String msg = "Unable to get vnc port due to " + e.toString();
s_logger.warn(msg, e);
return new GetVncPortAnswer(command, msg);
}
}
}

View File

@ -0,0 +1,75 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.hypervisor.xenserver.resource.wrapper;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.MaintainAnswer;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.hypervisor.xenserver.resource.XsHost;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixMaintainCommandWrapper extends CommandWrapper<MaintainCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixMaintainCommandWrapper.class);
@Override
public Answer execute(final MaintainCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final XsHost xsHost = citrixResourceBase.getHost();
final String uuid = xsHost.getUuid();
final Host host = Host.getByUuid(conn, uuid);
// remove all tags cloud stack
final Host.Record hr = host.getRecord(conn);
// Adding this check because could not get the mock to work. Will push the code and fix it afterwards.
if (hr == null) {
s_logger.warn("Host.Record is null.");
return new MaintainAnswer(command, false, "Host.Record is null");
}
final Iterator<String> it = hr.tags.iterator();
while (it.hasNext()) {
final String tag = it.next();
if (tag.contains("cloud")) {
it.remove();
}
}
host.setTags(conn, hr.tags);
return new MaintainAnswer(command);
} catch (final XenAPIException e) {
s_logger.warn("Unable to put server in maintainence mode", e);
return new MaintainAnswer(command, false, e.getMessage());
} catch (final XmlRpcException e) {
s_logger.warn("Unable to put server in maintainence mode", e);
return new MaintainAnswer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,84 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
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;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VM;
public final class CitrixMigrateCommandWrapper extends CommandWrapper<MigrateCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixMigrateCommandWrapper.class);
@Override
public Answer execute(final MigrateCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String vmName = command.getVmName();
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
final String ipaddr = command.getDestinationIp();
final Set<Host> hosts = Host.getAll(conn);
Host dsthost = null;
if(hosts != null) {
for (final Host host : hosts) {
if (host.getAddress(conn).equals(ipaddr)) {
dsthost = host;
break;
}
}
}
if (dsthost == null) {
final String msg = "Migration failed due to unable to find host " + ipaddr + " in XenServer pool " + citrixResourceBase.getHost().getPool();
s_logger.warn(msg);
return new MigrateAnswer(command, false, msg, null);
}
for (final VM vm : vms) {
final Set<VBD> vbds = vm.getVBDs(conn);
for (final VBD vbd : vbds) {
final VBD.Record vbdRec = vbd.getRecord(conn);
if (vbdRec.type.equals(Types.VbdType.CD) && !vbdRec.empty) {
vbd.eject(conn);
break;
}
}
citrixResourceBase.migrateVM(conn, dsthost, vm, vmName);
vm.setAffinity(conn, dsthost);
}
return new MigrateAnswer(command, true, "migration succeeded", null);
} catch (final Exception e) {
s_logger.warn(e.getMessage(), e);
return new MigrateAnswer(command, false, e.getMessage(), null);
}
}
}

View File

@ -0,0 +1,33 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixModifySshKeysCommandWrapper extends CommandWrapper<ModifySshKeysCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final ModifySshKeysCommand command, final CitrixResourceBase citrixResourceBase) {
return new Answer(command);
}
}

View File

@ -0,0 +1,96 @@
//
// 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.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.storage.template.TemplateProp;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixModifyStoragePoolCommandWrapper extends CommandWrapper<ModifyStoragePoolCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixModifyStoragePoolCommandWrapper.class);
@Override
public Answer execute(final ModifyStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final StorageFilerTO pool = command.getPool();
final boolean add = command.getAdd();
if (add) {
try {
final SR sr = citrixResourceBase.getStorageRepository(conn, pool.getUuid());
citrixResourceBase.setupHeartbeatSr(conn, sr, false);
final long capacity = sr.getPhysicalSize(conn);
final long available = capacity - sr.getPhysicalUtilisation(conn);
if (capacity == -1) {
final String msg = "Pool capacity is -1! pool: " + pool.getHost() + pool.getPath();
s_logger.warn(msg);
return new Answer(command, false, msg);
}
final Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>();
final ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(command, capacity, available, tInfo);
return answer;
} catch (final XenAPIException e) {
final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.toString() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + pool.getHost()
+ pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
} catch (final Exception e) {
final String msg = "ModifyStoragePoolCommand add XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: "
+ pool.getHost() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
} else {
try {
final SR sr = citrixResourceBase.getStorageRepository(conn, pool.getUuid());
final String srUuid = sr.getUuid(conn);
final String result = citrixResourceBase.callHostPluginPremium(conn, "setup_heartbeat_file", "host", citrixResourceBase.getHost().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(command, true, "seccuss");
} catch (final XenAPIException e) {
final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.toString() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: "
+ pool.getHost() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
} catch (final Exception e) {
final String msg = "ModifyStoragePoolCommand remove XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: "
+ pool.getHost() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
}
}
}

View File

@ -0,0 +1,35 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixNetworkElementCommandWrapper extends CommandWrapper<NetworkElementCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final NetworkElementCommand command, final CitrixResourceBase citrixResourceBase) {
final VirtualRoutingResource routingResource = citrixResourceBase.getVirtualRoutingResource();
return routingResource.executeRequest(command);
}
}

View File

@ -0,0 +1,45 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.NetworkRulesSystemVmCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.VirtualMachine;
import com.xensource.xenapi.Connection;
public final class CitrixNetworkRulesSystemVmCommandWrapper extends CommandWrapper<NetworkRulesSystemVmCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final NetworkRulesSystemVmCommand command, final CitrixResourceBase citrixResourceBase) {
boolean success = true;
final Connection conn = citrixResourceBase.getConnection();
if (command.getType() != VirtualMachine.Type.User) {
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules_systemvm", "vmName", command.getVmName());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
success = false;
}
}
return new Answer(command, success, "");
}
}

View File

@ -0,0 +1,44 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixNetworkRulesVmSecondaryIpCommandWrapper extends CommandWrapper<NetworkRulesVmSecondaryIpCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final NetworkRulesVmSecondaryIpCommand command, final CitrixResourceBase citrixResourceBase) {
boolean success = true;
final Connection conn = citrixResourceBase.getConnection();
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "network_rules_vmSecondaryIp", "vmName", command.getVmName(), "vmMac", command.getVmMac(),
"vmSecIp", command.getVmSecIp(), "action", command.getAction());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
success = false;
}
return new Answer(command, success, "");
}
}

View File

@ -0,0 +1,67 @@
//
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsCreateGreTunnelAnswer;
import com.cloud.agent.api.OvsCreateGreTunnelCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixOvsCreateGreTunnelCommandWrapper extends CommandWrapper<OvsCreateGreTunnelCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsCreateGreTunnelCommandWrapper.class);
@Override
public Answer execute(final OvsCreateGreTunnelCommand command, final CitrixResourceBase citrixResourceBase) {
citrixResourceBase.setIsOvs(true);
final Connection conn = citrixResourceBase.getConnection();
String bridge = "unkonwn";
try {
final Network nw = citrixResourceBase.setupvSwitchNetwork(conn);
bridge = nw.getBridge(conn);
final String result = citrixResourceBase.callHostPlugin(conn, "ovsgre", "ovs_create_gre", "bridge", bridge, "remoteIP", command.getRemoteIp(), "greKey",
command.getKey(), "from", Long.toString(command.getFrom()), "to", Long.toString(command.getTo()));
final String[] res = result.split(":");
if (res.length != 2 || res.length == 2 && res[1].equalsIgnoreCase("[]")) {
return new OvsCreateGreTunnelAnswer(command, false, result, citrixResourceBase.getHost().getIp(), bridge);
} else {
return new OvsCreateGreTunnelAnswer(command, true, result, citrixResourceBase.getHost().getIp(), bridge, Integer.parseInt(res[1]));
}
} catch (final BadServerResponse e) {
s_logger.error("An error occurred while creating a GRE tunnel to " + command.getRemoteIp() + " on host " + citrixResourceBase.getHost().getIp(), e);
} catch (final XenAPIException e) {
s_logger.error("An error occurred while creating a GRE tunnel to " + command.getRemoteIp() + " on host " + citrixResourceBase.getHost().getIp(), e);
} catch (final XmlRpcException e) {
s_logger.error("An error occurred while creating a GRE tunnel to " + command.getRemoteIp() + " on host " + citrixResourceBase.getHost().getIp(), e);
}
return new OvsCreateGreTunnelAnswer(command, false, "EXCEPTION", citrixResourceBase.getHost().getIp(), bridge);
}
}

View File

@ -0,0 +1,67 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsCreateTunnelAnswer;
import com.cloud.agent.api.OvsCreateTunnelCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
public final class CitrixOvsCreateTunnelCommandWrapper extends CommandWrapper<OvsCreateTunnelCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsCreateTunnelCommandWrapper.class);
@Override
public Answer execute(final OvsCreateTunnelCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
String bridge = "unknown";
try {
final Network nw = citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getNetworkName());
if (nw == null) {
s_logger.debug("Error during bridge setup");
return new OvsCreateTunnelAnswer(command, false, "Cannot create network", bridge);
}
citrixResourceBase.configureTunnelNetwork(conn, command.getNetworkId(), command.getFrom(), command.getNetworkName());
bridge = nw.getBridge(conn);
final String result =
citrixResourceBase.callHostPlugin(conn, "ovstunnel", "create_tunnel", "bridge", bridge, "remote_ip", command.getRemoteIp(),
"key", command.getKey().toString(), "from",
command.getFrom().toString(), "to", command.getTo().toString(), "cloudstack-network-id",
command.getNetworkUuid());
final String[] res = result.split(":");
if (res.length == 2 && res[0].equalsIgnoreCase("SUCCESS")) {
return new OvsCreateTunnelAnswer(command, true, result, res[1], bridge);
} else {
return new OvsCreateTunnelAnswer(command, false, result, bridge);
}
} catch (final Exception e) {
s_logger.debug("Error during tunnel setup");
s_logger.warn("Caught execption when creating ovs tunnel", e);
return new OvsCreateTunnelAnswer(command, false, e.getMessage(), bridge);
}
}
}

View File

@ -0,0 +1,62 @@
//
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsDeleteFlowCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixOvsDeleteFlowCommandWrapper extends CommandWrapper<OvsDeleteFlowCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsDeleteFlowCommandWrapper.class);
@Override
public Answer execute(final OvsDeleteFlowCommand command, final CitrixResourceBase citrixResourceBase) {
citrixResourceBase.setIsOvs(true);
final Connection conn = citrixResourceBase.getConnection();
try {
final Network nw = citrixResourceBase.setupvSwitchNetwork(conn);
final String bridge = nw.getBridge(conn);
final String result = citrixResourceBase.callHostPlugin(conn, "ovsgre", "ovs_delete_flow", "bridge", bridge, "vmName", command.getVmName());
if (result.equalsIgnoreCase("SUCCESS")) {
return new Answer(command, true, "success to delete flows for " + command.getVmName());
} else {
return new Answer(command, false, result);
}
} catch (final BadServerResponse e) {
s_logger.error("Failed to delete flow", e);
} catch (final XenAPIException e) {
s_logger.error("Failed to delete flow", e);
} catch (final XmlRpcException e) {
s_logger.error("Failed to delete flow", e);
}
return new Answer(command, false, "failed to delete flow for " + command.getVmName());
}
}

View File

@ -0,0 +1,53 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsDestroyBridgeCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
public final class CitrixOvsDestroyBridgeCommandWrapper extends CommandWrapper<OvsDestroyBridgeCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsDestroyBridgeCommandWrapper.class);
@Override
public Answer execute(final OvsDestroyBridgeCommand command, final CitrixResourceBase citrixResourceBase) {
try {
final Connection conn = citrixResourceBase.getConnection();
final Network nw = citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getBridgeName());
citrixResourceBase.cleanUpTmpDomVif(conn, nw);
citrixResourceBase.destroyTunnelNetwork(conn, nw, command.getHostId());
s_logger.debug("OVS Bridge destroyed");
return new Answer(command, true, null);
} catch (final Exception e) {
s_logger.warn("caught execption when destroying ovs bridge", e);
return new Answer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,58 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsDestroyTunnelCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
public final class CitrixOvsDestroyTunnelCommandWrapper extends CommandWrapper<OvsDestroyTunnelCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsDestroyTunnelCommandWrapper.class);
@Override
public Answer execute(final OvsDestroyTunnelCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Network nw = citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getBridgeName());
if (nw == null) {
s_logger.warn("Unable to find tunnel network for GRE key:" + command.getBridgeName());
return new Answer(command, false, "No network found");
}
final String bridge = nw.getBridge(conn);
final String result = citrixResourceBase.callHostPlugin(conn, "ovstunnel", "destroy_tunnel", "bridge", bridge, "in_port", command.getInPortName());
if (result.equalsIgnoreCase("SUCCESS")) {
return new Answer(command, true, result);
} else {
return new Answer(command, false, result);
}
} catch (final Exception e) {
s_logger.warn("caught execption when destroy ovs tunnel", e);
return new Answer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,71 @@
//
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsFetchInterfaceAnswer;
import com.cloud.agent.api.OvsFetchInterfaceCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.hypervisor.xenserver.resource.XsLocalNetwork;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixOvsFetchInterfaceCommandWrapper extends CommandWrapper<OvsFetchInterfaceCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsFetchInterfaceCommandWrapper.class);
@Override
public Answer execute(final OvsFetchInterfaceCommand command, final CitrixResourceBase citrixResourceBase) {
String label = command.getLabel();
//FIXME: this is a tricky to pass the network checking in XCP. I temporary get default label from Host.
if (citrixResourceBase.isXcp()) {
label = citrixResourceBase.getLabel();
}
s_logger.debug("Will look for network with name-label:" + label + " on host " + citrixResourceBase.getHost().getIp());
final Connection conn = citrixResourceBase.getConnection();
try {
final XsLocalNetwork nw = citrixResourceBase.getNetworkByName(conn, label);
if(nw == null) {
throw new CloudRuntimeException("Unable to locate the network with name-label: " + label + " on host: " + citrixResourceBase.getHost().getIp());
}
s_logger.debug("Network object:" + nw.getNetwork().getUuid(conn));
final PIF pif = nw.getPif(conn);
final PIF.Record pifRec = pif.getRecord(conn);
s_logger.debug("PIF object:" + pifRec.uuid + "(" + pifRec.device + ")");
return new OvsFetchInterfaceAnswer(command, 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 " + citrixResourceBase.getHost().getIp(), e);
return new OvsFetchInterfaceAnswer(command, false, "EXCEPTION:" + e.getMessage());
} catch (final XenAPIException e) {
s_logger.error("An error occurred while fetching the interface for " + label + " on host " + citrixResourceBase.getHost().getIp(), e);
return new OvsFetchInterfaceAnswer(command, false, "EXCEPTION:" + e.getMessage());
} catch (final XmlRpcException e) {
s_logger.error("An error occurred while fetching the interface for " + label + " on host " + citrixResourceBase.getHost().getIp(), e);
return new OvsFetchInterfaceAnswer(command, false, "EXCEPTION:" + e.getMessage());
}
}
}

View File

@ -0,0 +1,72 @@
//
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsSetTagAndFlowAnswer;
import com.cloud.agent.api.OvsSetTagAndFlowCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixOvsSetTagAndFlowCommandWrapper extends CommandWrapper<OvsSetTagAndFlowCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsSetTagAndFlowCommandWrapper.class);
@Override
public Answer execute(final OvsSetTagAndFlowCommand command, final CitrixResourceBase citrixResourceBase) {
citrixResourceBase.setIsOvs(true);
final Connection conn = citrixResourceBase.getConnection();
try {
final Network nw = citrixResourceBase.setupvSwitchNetwork(conn);
final String bridge = nw.getBridge(conn);
/*
* If VM is domainRouter, this will try to set flow and tag on its
* none guest network nic. don't worry, it will fail silently at
* host plugin side
*/
final String result = citrixResourceBase.callHostPlugin(conn, "ovsgre", "ovs_set_tag_and_flow", "bridge", bridge, "vmName", command.getVmName(), "tag",
command.getTag(), "vlans", command.getVlans(), "seqno", command.getSeqNo());
s_logger.debug("set flow for " + command.getVmName() + " " + result);
if (result != null && result.equalsIgnoreCase("SUCCESS")) {
return new OvsSetTagAndFlowAnswer(command, true, result);
} else {
return new OvsSetTagAndFlowAnswer(command, false, result);
}
} catch (final BadServerResponse e) {
s_logger.error("Failed to set tag and flow", e);
} catch (final XenAPIException e) {
s_logger.error("Failed to set tag and flow", e);
} catch (final XmlRpcException e) {
s_logger.error("Failed to set tag and flow", e);
}
return new OvsSetTagAndFlowAnswer(command, false, "EXCEPTION");
}
}

View File

@ -0,0 +1,45 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsSetupBridgeCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixOvsSetupBridgeCommandWrapper extends CommandWrapper<OvsSetupBridgeCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsSetupBridgeCommandWrapper.class);
@Override
public Answer execute(final OvsSetupBridgeCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getBridgeName());
citrixResourceBase.configureTunnelNetwork(conn, command.getNetworkId(), command.getHostId(), command.getBridgeName());
s_logger.debug("OVS Bridge configured");
return new Answer(command, true, null);
}
}

View File

@ -0,0 +1,57 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
public final class CitrixOvsVpcPhysicalTopologyConfigCommandWrapper extends CommandWrapper<OvsVpcPhysicalTopologyConfigCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsVpcPhysicalTopologyConfigCommandWrapper.class);
@Override
public Answer execute(final OvsVpcPhysicalTopologyConfigCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Network nw = citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getBridgeName());
final String bridgeName = nw.getBridge(conn);
final long sequenceNo = command.getSequenceNumber();
final String result = citrixResourceBase.callHostPlugin(conn, "ovstunnel", "configure_ovs_bridge_for_network_topology", "bridge",
bridgeName, "config", command.getVpcConfigInJson(), "host-id", ((Long)command.getHostId()).toString(),
"seq-no", Long.toString(sequenceNo));
if (result.startsWith("SUCCESS")) {
return new Answer(command, true, result);
} else {
return new Answer(command, false, result);
}
} catch (final Exception e) {
s_logger.warn("caught exception while updating host with latest VPC topology", e);
return new Answer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,57 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
public final class CitrixOvsVpcRoutingPolicyConfigCommandWrapper extends CommandWrapper<OvsVpcRoutingPolicyConfigCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixOvsVpcRoutingPolicyConfigCommandWrapper.class);
@Override
public Answer execute(final OvsVpcRoutingPolicyConfigCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Network nw = citrixResourceBase.findOrCreateTunnelNetwork(conn, command.getBridgeName());
final String bridgeName = nw.getBridge(conn);
final long sequenceNo = command.getSequenceNumber();
final String result = citrixResourceBase.callHostPlugin(conn, "ovstunnel", "configure_ovs_bridge_for_routing_policies", "bridge",
bridgeName, "host-id", ((Long)command.getHostId()).toString(), "config",
command.getVpcConfigInJson(), "seq-no", Long.toString(sequenceNo));
if (result.startsWith("SUCCESS")) {
return new Answer(command, true, result);
} else {
return new Answer(command, false, result);
}
} catch (final Exception e) {
s_logger.warn("caught exception while updating host with latest routing policies", e);
return new Answer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,41 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.PerformanceMonitorAnswer;
import com.cloud.agent.api.PerformanceMonitorCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixPerformanceMonitorCommandWrapper extends CommandWrapper<PerformanceMonitorCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final PerformanceMonitorCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String perfMon = citrixResourceBase.getPerfMon(conn, command.getParams(), command.getWait());
if (perfMon == null) {
return new PerformanceMonitorAnswer(command, false, perfMon);
} else {
return new PerformanceMonitorAnswer(command, true, perfMon);
}
}
}

View File

@ -0,0 +1,47 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixPingTestCommandWrapper extends CommandWrapper<PingTestCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final PingTestCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
boolean result = false;
final String computingHostIp = command.getComputingHostIp();
if (computingHostIp != null) {
result = citrixResourceBase.doPingTest(conn, computingHostIp);
} else {
result = citrixResourceBase.doPingTest(conn, command.getRouterIp(), command.getPrivateIp());
}
if (!result) {
return new Answer(command, false, "PingTestCommand failed");
}
return new Answer(command);
}
}

View File

@ -0,0 +1,92 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.PlugNicAnswer;
import com.cloud.agent.api.PlugNicCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
public final class CitrixPlugNicCommandWrapper extends CommandWrapper<PlugNicCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixPlugNicCommandWrapper.class);
@Override
public Answer execute(final PlugNicCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String vmName = command.getVmName();
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms == null || vms.isEmpty()) {
return new PlugNicAnswer(command, false, "Can not find VM " + vmName);
}
final VM vm = vms.iterator().next();
final NicTO nic = command.getNic();
String mac = nic.getMac();
final Set<VIF> routerVIFs = vm.getVIFs(conn);
mac = mac.trim();
int counter = 0;
for (final VIF vif : routerVIFs) {
final String lmac = vif.getMAC(conn);
if (lmac.trim().equals(mac)) {
counter++;
}
}
// We allow 2 routers with the same mac. It's needed for the redundant vpc routers.
// [FIXME] Find a way to identify the type of the router or if it's
// redundant.
if (counter > 2) {
final String msg = " Plug Nic failed due to a VIF with the same mac " + nic.getMac() + " exists in more than 2 routers.";
s_logger.error(msg);
return new PlugNicAnswer(command, false, msg);
}
// Wilder Rodrigues - replaced this code with the code above.
// VIF vif = getVifByMac(conn, vm, nic.getMac());
// if (vif != null) {
// final String msg = " Plug Nic failed due to a VIF with the same mac " + nic.getMac() + " exists";
// s_logger.warn(msg);
// return new PlugNicAnswer(cmd, false, msg);
// }
final String deviceId = citrixResourceBase.getLowestAvailableVIFDeviceNum(conn, vm);
nic.setDeviceId(Integer.parseInt(deviceId));
final VIF vif = citrixResourceBase.createVif(conn, vmName, vm, null, nic);
// vif = createVif(conn, vmName, vm, null, nic);
vif.plug(conn);
return new PlugNicAnswer(command, true, "success");
} catch (final Exception e) {
final String msg = " Plug Nic failed due to " + e.toString();
s_logger.error(msg, e);
return new PlugNicAnswer(command, false, msg);
}
}
}

View File

@ -0,0 +1,61 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixPrepareForMigrationCommandWrapper extends CommandWrapper<PrepareForMigrationCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixPrepareForMigrationCommandWrapper.class);
@Override
public Answer execute(final PrepareForMigrationCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final VirtualMachineTO vm = command.getVirtualMachine();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Preparing host for migrating " + vm);
}
final NicTO[] nics = vm.getNics();
try {
citrixResourceBase.prepareISO(conn, vm.getName());
for (final NicTO nic : nics) {
citrixResourceBase.getNetwork(conn, nic);
}
s_logger.debug("4. The VM " + vm.getName() + " is in Migrating state");
return new PrepareForMigrationAnswer(command);
} catch (final Exception e) {
s_logger.warn("Catch Exception " + e.getClass().getName() + " prepare for migration failed due to " + e.toString(), e);
return new PrepareForMigrationAnswer(command, e);
}
}
}

View File

@ -0,0 +1,83 @@
//
// 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.net.URI;
import java.util.HashMap;
import java.util.Set;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.VDI;
public final class CitrixPrimaryStorageDownloadCommandWrapper extends CommandWrapper<PrimaryStorageDownloadCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixPrimaryStorageDownloadCommandWrapper.class);
@Override
public Answer execute(final PrimaryStorageDownloadCommand command, final CitrixResourceBase citrixResourceBase) {
final String tmplturl = command.getUrl();
final String poolName = command.getPoolUuid();
final int wait = command.getWait();
try {
final URI uri = new URI(tmplturl);
final String tmplpath = uri.getHost() + ":" + uri.getPath();
final Connection conn = citrixResourceBase.getConnection();
SR poolsr = null;
final Set<SR> srs = SR.getByNameLabel(conn, poolName);
if (srs.size() != 1) {
final String msg = "There are " + srs.size() + " SRs with same name: " + poolName;
s_logger.warn(msg);
return new PrimaryStorageDownloadAnswer(msg);
} else {
poolsr = srs.iterator().next();
}
final String pUuid = poolsr.getUuid(conn);
final boolean isISCSI = citrixResourceBase.IsISCSI(poolsr.getType(conn));
final String uuid = citrixResourceBase.copyVhdFromSecondaryStorage(conn, tmplpath, pUuid, wait);
final VDI tmpl = citrixResourceBase.getVDIbyUuid(conn, uuid);
final VDI snapshotvdi = tmpl.snapshot(conn, new HashMap<String, String>());
final String snapshotUuid = snapshotvdi.getUuid(conn);
snapshotvdi.setNameLabel(conn, "Template " + command.getName());
final String parentuuid = citrixResourceBase.getVhdParent(conn, pUuid, snapshotUuid, isISCSI);
final VDI parent = citrixResourceBase.getVDIbyUuid(conn, parentuuid);
final Long phySize = parent.getPhysicalUtilisation(conn);
tmpl.destroy(conn);
poolsr.scan(conn);
try {
Thread.sleep(5000);
} catch (final Exception e) {
}
return new PrimaryStorageDownloadAnswer(snapshotvdi.getUuid(conn), phySize);
} catch (final Exception e) {
final String msg = "Catch Exception " + e.getClass().getName() + " on host:" + citrixResourceBase.getHost().getUuid() + " for template: " + tmplturl + " due to "
+ e.toString();
s_logger.warn(msg, e);
return new PrimaryStorageDownloadAnswer(msg);
}
}
}

View File

@ -0,0 +1,92 @@
//
// 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 org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.PvlanSetupCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.hypervisor.xenserver.resource.XsLocalNetwork;
import com.cloud.network.Networks.TrafficType;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixPvlanSetupCommandWrapper extends CommandWrapper<PvlanSetupCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixPvlanSetupCommandWrapper.class);
@Override
public Answer execute(final PvlanSetupCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String primaryPvlan = command.getPrimary();
final String isolatedPvlan = command.getIsolated();
final String op = command.getOp();
final String dhcpName = command.getDhcpName();
final String dhcpMac = command.getDhcpMac();
final String dhcpIp = command.getDhcpIp();
final String vmMac = command.getVmMac();
final String networkTag = command.getNetworkTag();
String nwNameLabel = null;
try {
final XsLocalNetwork nw = citrixResourceBase.getNativeNetworkForTraffic(conn, TrafficType.Guest, networkTag);
if (nw == null) {
s_logger.error("Network is not configured on the backend for pvlan " + primaryPvlan);
throw new CloudRuntimeException("Network for the backend is not configured correctly for pvlan primary: " + primaryPvlan);
}
nwNameLabel = nw.getNetwork().getNameLabel(conn);
} catch (final XenAPIException e) {
s_logger.warn("Fail to get network", e);
return new Answer(command, false, e.toString());
} catch (final XmlRpcException e) {
s_logger.warn("Fail to get network", e);
return new Answer(command, false, e.toString());
}
String result = null;
if (command.getType() == PvlanSetupCommand.Type.DHCP) {
result = citrixResourceBase.callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-dhcp", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan",
isolatedPvlan, "dhcp-name", dhcpName, "dhcp-ip", dhcpIp, "dhcp-mac", dhcpMac);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program pvlan for dhcp server with mac " + dhcpMac);
return new Answer(command, false, result);
} else {
s_logger.info("Programmed pvlan for dhcp server with mac " + dhcpMac);
}
} else if (command.getType() == PvlanSetupCommand.Type.VM) {
result = citrixResourceBase.callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-vm", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan",
isolatedPvlan, "vm-mac", vmMac);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program pvlan for vm with mac " + vmMac);
return new Answer(command, false, result);
} else {
s_logger.info("Programmed pvlan for vm with mac " + vmMac);
}
}
return new Answer(command, true, result);
}
}

View File

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

View File

@ -0,0 +1,68 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
public final class CitrixRebootCommandWrapper extends CommandWrapper<RebootCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixRebootCommandWrapper.class);
@Override
public Answer execute(final RebootCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
s_logger.debug("7. The VM " + command.getVmName() + " is in Starting state");
try {
Set<VM> vms = null;
try {
vms = VM.getByNameLabel(conn, command.getVmName());
} catch (final XenAPIException e0) {
s_logger.debug("getByNameLabel failed " + e0.toString());
return new RebootAnswer(command, "getByNameLabel failed " + e0.toString(), false);
} catch (final Exception e0) {
s_logger.debug("getByNameLabel failed " + e0.getMessage());
return new RebootAnswer(command, "getByNameLabel failed", false);
}
for (final VM vm : vms) {
try {
citrixResourceBase.rebootVM(conn, vm, vm.getNameLabel(conn));
} catch (final Exception e) {
final String msg = e.toString();
s_logger.warn(msg, e);
return new RebootAnswer(command, msg, false);
}
}
return new RebootAnswer(command, "reboot succeeded", true);
} finally {
s_logger.debug("8. The VM " + command.getVmName() + " is in Running state");
}
}
}

View File

@ -0,0 +1,52 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixRebootRouterCommandWrapper extends CommandWrapper<RebootRouterCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final RebootRouterCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
final RebootCommand rebootCommand = new RebootCommand(command.getVmName());
final Answer answer = wrapper.execute(rebootCommand, citrixResourceBase);
if (answer.getResult()) {
final String cnct = citrixResourceBase.connect(conn, command.getVmName(), command.getPrivateIpAddress());
citrixResourceBase.networkUsage(conn, command.getPrivateIpAddress(), "create", null);
if (cnct == null) {
return answer;
} else {
return new Answer(command, false, cnct);
}
}
return answer;
}
}

View File

@ -0,0 +1,280 @@
//
// 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.Hashtable;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.ClusterVMMetaDataSyncCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.CreateVMSnapshotCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.DeleteVMSnapshotCommand;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.GetVmDiskStatsCommand;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.NetworkRulesSystemVmCommand;
import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.OvsCreateGreTunnelCommand;
import com.cloud.agent.api.OvsCreateTunnelCommand;
import com.cloud.agent.api.OvsDeleteFlowCommand;
import com.cloud.agent.api.OvsDestroyBridgeCommand;
import com.cloud.agent.api.OvsDestroyTunnelCommand;
import com.cloud.agent.api.OvsFetchInterfaceCommand;
import com.cloud.agent.api.OvsSetTagAndFlowCommand;
import com.cloud.agent.api.OvsSetupBridgeCommand;
import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
import com.cloud.agent.api.PerformanceMonitorCommand;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.agent.api.PlugNicCommand;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.PvlanSetupCommand;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.RevertToVMSnapshotCommand;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.SetupCommand;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.UpdateHostPasswordCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.storage.ResizeVolumeCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.hypervisor.xenserver.resource.XenServer56FP1Resource;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.RequestWrapper;
import com.cloud.resource.ServerResource;
public class CitrixRequestWrapper extends RequestWrapper {
private static final Logger s_logger = Logger.getLogger(CitrixRequestWrapper.class);
private static CitrixRequestWrapper instance;
static {
instance = new CitrixRequestWrapper();
}
@SuppressWarnings("rawtypes")
private final Hashtable<Class<? extends ServerResource>, Hashtable<Class<? extends Command>, CommandWrapper>> resources;
@SuppressWarnings("rawtypes")
private CitrixRequestWrapper() {
resources = new Hashtable<Class<? extends ServerResource>, Hashtable<Class<? extends Command>, CommandWrapper>>();
init();
}
@SuppressWarnings("rawtypes")
private void init() {
// CitrixResourceBase commands
final Hashtable<Class<? extends Command>, CommandWrapper> citrixCommands = new Hashtable<Class<? extends Command>, CommandWrapper>();
citrixCommands.put(RebootRouterCommand.class, new CitrixRebootRouterCommandWrapper());
citrixCommands.put(CreateCommand.class, new CitrixCreateCommandWrapper());
citrixCommands.put(CheckConsoleProxyLoadCommand.class, new CitrixCheckConsoleProxyLoadCommandWrapper());
citrixCommands.put(WatchConsoleProxyLoadCommand.class, new CitrixWatchConsoleProxyLoadCommandWrapper());
citrixCommands.put(ReadyCommand.class, new CitrixReadyCommandWrapper());
citrixCommands.put(GetHostStatsCommand.class, new CitrixGetHostStatsCommandWrapper());
citrixCommands.put(GetVmStatsCommand.class, new CitrixGetVmStatsCommandWrapper());
citrixCommands.put(GetVmDiskStatsCommand.class, new CitrixGetVmDiskStatsCommandWrapper());
citrixCommands.put(CheckHealthCommand.class, new CitrixCheckHealthCommandWrapper());
citrixCommands.put(StopCommand.class, new CitrixStopCommandWrapper());
citrixCommands.put(RebootCommand.class, new CitrixRebootCommandWrapper());
citrixCommands.put(CheckVirtualMachineCommand.class, new CitrixCheckVirtualMachineCommandWrapper());
citrixCommands.put(PrepareForMigrationCommand.class, new CitrixPrepareForMigrationCommandWrapper());
citrixCommands.put(MigrateCommand.class, new CitrixMigrateCommandWrapper());
citrixCommands.put(DestroyCommand.class, new CitrixDestroyCommandWrapper());
citrixCommands.put(CreateStoragePoolCommand.class, new CitrixCreateStoragePoolCommandWrapper());
citrixCommands.put(ModifyStoragePoolCommand.class, new CitrixModifyStoragePoolCommandWrapper());
citrixCommands.put(DeleteStoragePoolCommand.class, new CitrixDeleteStoragePoolCommandWrapper());
citrixCommands.put(ResizeVolumeCommand.class, new CitrixResizeVolumeCommandWrapper());
citrixCommands.put(AttachVolumeCommand.class, new CitrixAttachVolumeCommandWrapper());
citrixCommands.put(AttachIsoCommand.class, new CitrixAttachIsoCommandWrapper());
citrixCommands.put(UpgradeSnapshotCommand.class, new CitrixUpgradeSnapshotCommandWrapper());
citrixCommands.put(GetStorageStatsCommand.class, new CitrixGetStorageStatsCommandWrapper());
citrixCommands.put(PrimaryStorageDownloadCommand.class, new CitrixPrimaryStorageDownloadCommandWrapper());
citrixCommands.put(GetVncPortCommand.class, new CitrixGetVncPortCommandWrapper());
citrixCommands.put(SetupCommand.class, new CitrixSetupCommandWrapper());
citrixCommands.put(MaintainCommand.class, new CitrixMaintainCommandWrapper());
citrixCommands.put(PingTestCommand.class, new CitrixPingTestCommandWrapper());
citrixCommands.put(CheckOnHostCommand.class, new CitrixCheckOnHostCommandWrapper());
citrixCommands.put(ModifySshKeysCommand.class, new CitrixModifySshKeysCommandWrapper());
citrixCommands.put(StartCommand.class, new CitrixStartCommandWrapper());
citrixCommands.put(OvsSetTagAndFlowCommand.class, new CitrixOvsSetTagAndFlowCommandWrapper());
citrixCommands.put(CheckSshCommand.class, new CitrixCheckSshCommandWrapper());
citrixCommands.put(SecurityGroupRulesCmd.class, new CitrixSecurityGroupRulesCommandWrapper());
citrixCommands.put(OvsFetchInterfaceCommand.class, new CitrixOvsFetchInterfaceCommandWrapper());
citrixCommands.put(OvsCreateGreTunnelCommand.class, new CitrixOvsCreateGreTunnelCommandWrapper());
citrixCommands.put(OvsDeleteFlowCommand.class, new CitrixOvsDeleteFlowCommandWrapper());
citrixCommands.put(OvsVpcPhysicalTopologyConfigCommand.class, new CitrixOvsVpcPhysicalTopologyConfigCommandWrapper());
citrixCommands.put(OvsVpcRoutingPolicyConfigCommand.class, new CitrixOvsVpcRoutingPolicyConfigCommandWrapper());
citrixCommands.put(CleanupNetworkRulesCmd.class, new CitrixCleanupNetworkRulesCmdWrapper());
citrixCommands.put(NetworkRulesSystemVmCommand.class, new CitrixNetworkRulesSystemVmCommandWrapper());
citrixCommands.put(OvsCreateTunnelCommand.class, new CitrixOvsCreateTunnelCommandWrapper());
citrixCommands.put(OvsSetupBridgeCommand.class, new CitrixOvsSetupBridgeCommandWrapper());
citrixCommands.put(OvsDestroyBridgeCommand.class, new CitrixOvsDestroyBridgeCommandWrapper());
citrixCommands.put(OvsDestroyTunnelCommand.class, new CitrixOvsDestroyTunnelCommandWrapper());
citrixCommands.put(UpdateHostPasswordCommand.class, new CitrixUpdateHostPasswordCommandWrapper());
citrixCommands.put(ClusterVMMetaDataSyncCommand.class, new CitrixClusterVMMetaDataSyncCommandWrapper());
citrixCommands.put(CheckNetworkCommand.class, new CitrixCheckNetworkCommandWrapper());
citrixCommands.put(PlugNicCommand.class, new CitrixPlugNicCommandWrapper());
citrixCommands.put(UnPlugNicCommand.class, new CitrixUnPlugNicCommandWrapper());
citrixCommands.put(CreateVMSnapshotCommand.class, new CitrixCreateVMSnapshotCommandWrapper());
citrixCommands.put(DeleteVMSnapshotCommand.class, new CitrixDeleteVMSnapshotCommandWrapper());
citrixCommands.put(RevertToVMSnapshotCommand.class, new CitrixRevertToVMSnapshotCommandWrapper());
citrixCommands.put(NetworkRulesVmSecondaryIpCommand.class, new CitrixNetworkRulesVmSecondaryIpCommandWrapper());
citrixCommands.put(ScaleVmCommand.class, new CitrixScaleVmCommandWrapper());
citrixCommands.put(PvlanSetupCommand.class, new CitrixPvlanSetupCommandWrapper());
citrixCommands.put(PerformanceMonitorCommand.class, new CitrixPerformanceMonitorCommandWrapper());
citrixCommands.put(NetworkElementCommand.class, new CitrixNetworkElementCommandWrapper());
resources.put(CitrixResourceBase.class, citrixCommands);
// XenServer56Resource commands
final Hashtable<Class<? extends Command>, CommandWrapper> xenServer56Commands = new Hashtable<Class<? extends Command>, CommandWrapper>();
xenServer56Commands.put(CheckOnHostCommand.class, new XenServer56CheckOnHostCommandWrapper());
xenServer56Commands.put(FenceCommand.class, new XenServer56FenceCommandWrapper());
xenServer56Commands.put(NetworkUsageCommand.class, new XenServer56NetworkUsageCommandWrapper());
resources.put(XenServer56Resource.class, xenServer56Commands);
// XenServer56FP1Resource commands
final Hashtable<Class<? extends Command>, CommandWrapper> xenServer56P1Commands = new Hashtable<Class<? extends Command>, CommandWrapper>();
xenServer56P1Commands.put(FenceCommand.class, new XenServer56FP1FenceCommandWrapper());
resources.put(XenServer56FP1Resource.class, xenServer56P1Commands);
}
public static CitrixRequestWrapper getInstance() {
return instance;
}
@SuppressWarnings({"rawtypes" })
@Override
public Answer execute(final Command command, final ServerResource serverResource) {
final Class<? extends ServerResource> resourceClass = serverResource.getClass();
final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands = retrieveResource(command, resourceClass);
CommandWrapper<Command, Answer, ServerResource> commandWrapper = retrieveCommands(command.getClass(), resourceCommands);
while (commandWrapper == null) {
//Could not find the command in the given resource, will traverse the family tree.
commandWrapper = retryWhenAllFails(command, resourceClass, resourceCommands);
}
return commandWrapper.execute(command, serverResource);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Hashtable<Class<? extends Command>, CommandWrapper> retrieveResource(final Command command, final Class<? extends ServerResource> resourceClass) {
Class<? extends ServerResource> keepResourceClass = resourceClass;
Hashtable<Class<? extends Command>, CommandWrapper> resource = resources.get(keepResourceClass);
while (resource == null) {
try {
final Class<? extends ServerResource> keepResourceClass2 = (Class<? extends ServerResource>) keepResourceClass.getSuperclass();
resource = resources.get(keepResourceClass2);
keepResourceClass = keepResourceClass2;
} catch (final ClassCastException e) {
throw new NullPointerException("No key found for '" + command.getClass() + "' in the Map!");
}
}
return resource;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected CommandWrapper<Command, Answer, ServerResource> retrieveCommands(final Class<? extends Command> commandClass,
final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands) {
Class<? extends Command> keepCommandClass = commandClass;
CommandWrapper<Command, Answer, ServerResource> commandWrapper = resourceCommands.get(keepCommandClass);
while (commandWrapper == null) {
try {
final Class<? extends Command> commandClass2 = (Class<? extends Command>) keepCommandClass.getSuperclass();
if (commandClass2 == null) {
throw new NullPointerException("All the COMMAND hierarchy tree has been visited but no compliant key has been found for '" + commandClass +"'.");
}
commandWrapper = resourceCommands.get(commandClass2);
keepCommandClass = commandClass2;
} catch (final NullPointerException e) {
// Will now traverse all the resource hierarchy. Returning null is not a problem.
// It is all being nicely checked and in case we do not have a resource, an Unsupported answer will be thrown by the base class.
return null;
}
}
return commandWrapper;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected CommandWrapper<Command, Answer, ServerResource> retryWhenAllFails(final Command command, final Class<? extends ServerResource> resourceClass,
final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands) {
Class<? extends ServerResource> keepResourceClass = resourceClass;
CommandWrapper<Command, Answer, ServerResource> commandWrapper = resourceCommands.get(command.getClass());
while (commandWrapper == null) {
//Could not find the command in the given resource, will traverse the family tree.
try {
final Class<? extends ServerResource> resourceClass2 = (Class<? extends ServerResource>) keepResourceClass.getSuperclass();
if (resourceClass2 == null) {
throw new NullPointerException("All the SERVER-RESOURCE hierarchy tree has been visited but no compliant key has been found for '" + command.getClass() +"'.");
}
final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands2 = retrieveResource(command, (Class<? extends ServerResource>) keepResourceClass.getSuperclass());
keepResourceClass = resourceClass2;
commandWrapper = retrieveCommands(command.getClass(), resourceCommands2);
} catch (final NullPointerException e) {
throw e;
}
}
return commandWrapper;
}
}

View File

@ -0,0 +1,52 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.storage.ResizeVolumeAnswer;
import com.cloud.agent.api.storage.ResizeVolumeCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.VDI;
public final class CitrixResizeVolumeCommandWrapper extends CommandWrapper<ResizeVolumeCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixResizeVolumeCommandWrapper.class);
@Override
public Answer execute(final ResizeVolumeCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String volid = command.getPath();
final long newSize = command.getNewSize();
try {
final VDI vdi = citrixResourceBase.getVDIbyUuid(conn, volid);
vdi.resize(conn, newSize);
return new ResizeVolumeAnswer(command, true, "success", newSize);
} catch (final Exception e) {
s_logger.warn("Unable to resize volume", e);
final String error = "failed to resize volume:" + e;
return new ResizeVolumeAnswer(command, false, error);
}
}
}

View File

@ -0,0 +1,110 @@
//
// 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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.RevertToVMSnapshotAnswer;
import com.cloud.agent.api.RevertToVMSnapshotCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.snapshot.VMSnapshot;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
public final class CitrixRevertToVMSnapshotCommandWrapper extends CommandWrapper<RevertToVMSnapshotCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixRevertToVMSnapshotCommandWrapper.class);
@Override
public Answer execute(final RevertToVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String vmName = command.getVmName();
final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
final VMSnapshot.Type vmSnapshotType = command.getTarget().getType();
final Boolean snapshotMemory = vmSnapshotType == VMSnapshot.Type.DiskAndMemory;
final Connection conn = citrixResourceBase.getConnection();
PowerState vmState = null;
VM vm = null;
try {
final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
if (vmSnapshots == null || vmSnapshots.size() == 0) {
return new RevertToVMSnapshotAnswer(command, false, "Cannot find vmSnapshot with name: " + command.getTarget().getSnapshotName());
}
final VM vmSnapshot = vmSnapshots.iterator().next();
// find target VM or creating a work VM
try {
vm = citrixResourceBase.getVM(conn, vmName);
} catch (final Exception e) {
vm = citrixResourceBase.createWorkingVM(conn, vmName, command.getGuestOSType(), command.getPlatformEmulator(), listVolumeTo);
}
if (vm == null) {
return new RevertToVMSnapshotAnswer(command, false, "Revert to VM Snapshot Failed due to can not find vm: " + vmName);
}
// call plugin to execute revert
citrixResourceBase.revertToSnapshot(conn, vmSnapshot, vmName, vm.getUuid(conn), snapshotMemory, citrixResourceBase.getHost().getUuid());
vm = citrixResourceBase.getVM(conn, vmName);
final Set<VBD> vbds = vm.getVBDs(conn);
final Map<String, VDI> vdiMap = new HashMap<String, VDI>();
// get vdi:vbdr to a map
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.type == Types.VbdType.DISK) {
final VDI vdi = vbdr.VDI;
vdiMap.put(vbdr.userdevice, vdi);
}
}
if (!snapshotMemory) {
vm.destroy(conn);
vmState = PowerState.PowerOff;
} else {
vmState = PowerState.PowerOn;
}
// after revert, VM's volumes path have been changed, need to report to manager
for (final VolumeObjectTO volumeTo : listVolumeTo) {
final Long deviceId = volumeTo.getDeviceId();
final VDI vdi = vdiMap.get(deviceId.toString());
volumeTo.setPath(vdi.getUuid(conn));
}
return new RevertToVMSnapshotAnswer(command, listVolumeTo, vmState);
} catch (final Exception e) {
s_logger.error("revert vm " + vmName + " to snapshot " + command.getTarget().getSnapshotName() + " failed due to " + e.getMessage());
return new RevertToVMSnapshotAnswer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,106 @@
//
// 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.Iterator;
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.ScaleVmAnswer;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types.VmPowerState;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
public final class CitrixScaleVmCommandWrapper extends CommandWrapper<ScaleVmCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixScaleVmCommandWrapper.class);
@Override
public Answer execute(final ScaleVmCommand command, final CitrixResourceBase citrixResourceBase) {
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final String vmName = vmSpec.getName();
try {
final Connection conn = citrixResourceBase.getConnection();
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
// If DMC is not enable then don't execute this command.
if (!citrixResourceBase.isDmcEnabled(conn, host)) {
throw new CloudRuntimeException("Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:"
+ citrixResourceBase.getHost().getUuid() + " ,check your license and hypervisor version.");
}
if (vms == null || vms.size() == 0) {
s_logger.info("No running VM " + vmName + " exists on XenServer" + citrixResourceBase.getHost().getUuid());
return new ScaleVmAnswer(command, false, "VM does not exist");
}
// stop vm which is running on this host or is in halted state
final Iterator<VM> iter = vms.iterator();
while (iter.hasNext()) {
final VM vm = iter.next();
final VM.Record vmr = vm.getRecord(conn);
if (vmr.powerState == VmPowerState.HALTED || vmr.powerState == VmPowerState.RUNNING && !citrixResourceBase.isRefNull(vmr.residentOn)
&& !vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
iter.remove();
}
}
for (final VM vm : vms) {
vm.getRecord(conn);
try {
citrixResourceBase.scaleVM(conn, vm, vmSpec, host);
} catch (final Exception e) {
final String msg = "Catch exception " + e.getClass().getName() + " when scaling VM:" + vmName + " due to " + e.toString();
s_logger.debug(msg);
return new ScaleVmAnswer(command, false, msg);
}
}
final String msg = "scaling VM " + vmName + " is successful on host " + host;
s_logger.debug(msg);
return new ScaleVmAnswer(command, true, msg);
} catch (final XenAPIException e) {
final String msg = "Upgrade Vm " + vmName + " fail due to " + e.toString();
s_logger.warn(msg, e);
return new ScaleVmAnswer(command, false, msg);
} catch (final XmlRpcException e) {
final String msg = "Upgrade Vm " + vmName + " fail due to " + e.getMessage();
s_logger.warn(msg, e);
return new ScaleVmAnswer(command, false, msg);
} catch (final Exception e) {
final String msg = "Unable to upgrade " + vmName + " due to " + e.getMessage();
s_logger.warn(msg, e);
return new ScaleVmAnswer(command, false, msg);
}
}
}

View File

@ -0,0 +1,61 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixSecurityGroupRulesCommandWrapper extends CommandWrapper<SecurityGroupRulesCmd, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixSecurityGroupRulesCommandWrapper.class);
@Override
public Answer execute(final SecurityGroupRulesCmd command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending network rules command to " + citrixResourceBase.getHost().getIp());
}
if (!citrixResourceBase.canBridgeFirewall()) {
s_logger.warn("Host " + citrixResourceBase.getHost().getIp() + " cannot do bridge firewalling");
return new SecurityGroupRuleAnswer(command, false, "Host " + citrixResourceBase.getHost().getIp() + " cannot do bridge firewalling",
SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL);
}
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "network_rules", "vmName", command.getVmName(), "vmIP", command.getGuestIp(), "vmMAC",
command.getGuestMac(), "vmID", Long.toString(command.getVmId()), "signature", command.getSignature(), "seqno", Long.toString(command.getSeqNum()), "deflated",
"true", "rules", command.compressStringifiedRules(), "secIps", command.getSecIpsString());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program network rules for vm " + command.getVmName());
return new SecurityGroupRuleAnswer(command, false, "programming network rules failed");
} else {
s_logger.info("Programmed network rules for vm " + command.getVmName() + " guestIp=" + command.getGuestIp() + ", ingress numrules="
+ command.getIngressRuleSet().length + ", egress numrules=" + command.getEgressRuleSet().length);
return new SecurityGroupRuleAnswer(command);
}
}
}

View File

@ -0,0 +1,200 @@
//
// 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.Map;
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.SetupAnswer;
import com.cloud.agent.api.SetupCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.xensource.xenapi.Bond;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.PIF;
import com.xensource.xenapi.Pool;
import com.xensource.xenapi.Types;
import com.xensource.xenapi.Types.XenAPIException;
public final class CitrixSetupCommandWrapper extends CommandWrapper<SetupCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixSetupCommandWrapper.class);
@Override
public Answer execute(final SetupCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
try {
final Map<Pool, Pool.Record> poolRecs = Pool.getAllRecords(conn);
if (poolRecs.size() != 1) {
throw new CloudRuntimeException("There are " + poolRecs.size() + " pool for host :" + citrixResourceBase.getHost().getUuid());
}
final Host master = poolRecs.values().iterator().next().master;
citrixResourceBase.setupServer(conn, master);
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
citrixResourceBase.setupServer(conn, host);
if (!citrixResourceBase.setIptables(conn)) {
s_logger.warn("set xenserver Iptable failed");
return null;
}
if (citrixResourceBase.isSecurityGroupEnabled()) {
final boolean canBridgeFirewall = citrixResourceBase.canBridgeFirewall(conn);
citrixResourceBase.setCanBridgeFirewall(canBridgeFirewall);
if (!canBridgeFirewall) {
final String msg = "Failed to configure brige firewall";
s_logger.warn(msg);
s_logger.warn("Check host " + citrixResourceBase.getHost().getIp() +" for CSP is installed or not and check network mode for bridge");
return new SetupAnswer(command, msg);
}
}
final boolean r = citrixResourceBase.launchHeartBeat(conn);
if (!r) {
return null;
}
citrixResourceBase.cleanupTemplateSR(conn);
try {
if (command.useMultipath()) {
// the config value is set to true
host.addToOtherConfig(conn, "multipathing", "true");
host.addToOtherConfig(conn, "multipathhandle", "dmp");
}
} catch (final Types.MapDuplicateKey e) {
s_logger.debug("multipath is already set");
}
if (command.needSetup() ) {
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "setup_iscsi", "uuid", citrixResourceBase.getHost().getUuid());
if (!result.contains("> DONE <")) {
s_logger.warn("Unable to setup iscsi: " + result);
return new SetupAnswer(command, result);
}
Pair<PIF, PIF.Record> mgmtPif = null;
final Set<PIF> 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(citrixResourceBase.getHost().getUuid())
.append("; pif=")
.append(rec.uuid)
.append("; vlan=")
.append(rec.VLAN)
.toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Management network is on pif=" + rec.uuid);
}
mgmtPif = new Pair<PIF, PIF.Record>(pif, rec);
break;
}
}
if (mgmtPif == null) {
final String msg = "Unable to find management network for " + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
final Map<Network, Network.Record> networks = Network.getAllRecords(conn);
if(networks == null) {
final String msg = "Unable to setup as there are no networks in the host: " + citrixResourceBase.getHost().getUuid();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
for (final Network.Record network : networks.values()) {
if (network.nameLabel.equals("cloud-private")) {
for (final PIF pif : network.PIFs) {
final PIF.Record pr = pif.getRecord(conn);
if (citrixResourceBase.getHost().getUuid().equals(pr.host.getUuid(conn))) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a network called cloud-private. host=" + citrixResourceBase.getHost().getUuid() + "; Network=" + network.uuid + "; pif=" + pr.uuid);
}
if (pr.VLAN != null && pr.VLAN != -1) {
final String msg =
new StringBuilder("Unsupported configuration. Network cloud-private is on a VLAN. Network=").append(network.uuid)
.append(" ; pif=")
.append(pr.uuid)
.toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
if (!pr.management && pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) {
if (pr.bondMasterOf.size() > 1) {
final String msg =
new StringBuilder("Unsupported configuration. Network cloud-private has more than one bond. Network=").append(network.uuid)
.append("; pif=")
.append(pr.uuid)
.toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
final Bond bond = pr.bondMasterOf.iterator().next();
final Set<PIF> slaves = bond.getSlaves(conn);
for (final PIF slave : slaves) {
final PIF.Record spr = slave.getRecord(conn);
if (spr.management) {
if (!citrixResourceBase.transferManagementNetwork(conn, host, slave, spr, pif)) {
final String msg =
new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" +
citrixResourceBase.getHost().getUuid()).toString();
s_logger.warn(msg);
return new SetupAnswer(command, msg);
}
break;
}
}
}
}
}
}
}
}
return new SetupAnswer(command, false);
} catch (final XmlRpcException e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
} catch (final XenAPIException e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
} catch (final Exception e) {
s_logger.warn("Unable to setup", e);
return new SetupAnswer(command, e.getMessage());
}
}
}

View File

@ -0,0 +1,210 @@
//
// 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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.OvsSetTagAndFlowAnswer;
import com.cloud.agent.api.OvsSetTagAndFlowCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.network.Networks;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.resource.CommandWrapper;
import com.cloud.vm.VirtualMachine;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types.VmPowerState;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
public final class CitrixStartCommandWrapper extends CommandWrapper<StartCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixStartCommandWrapper.class);
@Override
public Answer execute(final StartCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final String vmName = vmSpec.getName();
VmPowerState state = VmPowerState.HALTED;
VM vm = null;
// if a VDI is created, record its UUID to send back to the CS MS
final Map<String, String> iqnToPath = new HashMap<String, String>();
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms != null) {
for (final VM v : vms) {
final VM.Record vRec = v.getRecord(conn);
if (vRec.powerState == VmPowerState.HALTED) {
v.destroy(conn);
} else if (vRec.powerState == VmPowerState.RUNNING) {
final String host = vRec.residentOn.getUuid(conn);
final String msg = "VM " + vmName + " is runing on host " + host;
s_logger.debug(msg);
return new StartAnswer(command, msg, host);
} else {
final String msg = "There is already a VM having the same name " + vmName + " vm record " + vRec.toString();
s_logger.warn(msg);
return new StartAnswer(command, msg);
}
}
}
s_logger.debug("1. The VM " + vmName + " is in Starting state.");
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
vm = citrixResourceBase.createVmFromTemplate(conn, vmSpec, host);
final GPUDeviceTO gpuDevice = vmSpec.getGpuDevice();
if (gpuDevice != null) {
s_logger.debug("Creating VGPU for of VGPU type: " + gpuDevice.getVgpuType() + " in GPU group " + gpuDevice.getGpuGroup() + " for VM " + vmName);
citrixResourceBase.createVGPU(conn, command, vm, gpuDevice);
}
for (final DiskTO disk : vmSpec.getDisks()) {
final VDI newVdi = citrixResourceBase.prepareManagedDisk(conn, disk, vmName);
if (newVdi != null) {
final String path = newVdi.getUuid(conn);
iqnToPath.put(disk.getDetails().get(DiskTO.IQN), path);
}
citrixResourceBase.createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), newVdi);
}
if (vmSpec.getType() != VirtualMachine.Type.User) {
citrixResourceBase.createPatchVbd(conn, vmName, vm);
}
for (final NicTO nic : vmSpec.getNics()) {
citrixResourceBase.createVif(conn, vmName, vm, vmSpec, nic);
}
citrixResourceBase.startVM(conn, host, vm, vmName);
if (citrixResourceBase.isOvs()) {
// TODO(Salvatore-orlando): This code should go
for (final NicTO nic : vmSpec.getNics()) {
if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vswitch) {
final HashMap<String, String> args = citrixResourceBase.parseDefaultOvsRuleComamnd(BroadcastDomainType.getValue(nic.getBroadcastUri()));
final OvsSetTagAndFlowCommand flowCmd = new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"),
Long.parseLong(args.get("vmId")));
final CitrixRequestWrapper citrixRequestWrapper = CitrixRequestWrapper.getInstance();
final OvsSetTagAndFlowAnswer r = (OvsSetTagAndFlowAnswer) citrixRequestWrapper.execute(flowCmd, citrixResourceBase);
if (!r.getResult()) {
s_logger.warn("Failed to set flow for VM " + r.getVmId());
} else {
s_logger.info("Success to set flow for VM " + r.getVmId());
}
}
}
}
if (citrixResourceBase.canBridgeFirewall()) {
String result = null;
if (vmSpec.getType() != VirtualMachine.Type.User) {
final NicTO[] nics = vmSpec.getNics();
boolean secGrpEnabled = false;
for (final NicTO nic : nics) {
if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
secGrpEnabled = true;
break;
}
}
if (secGrpEnabled) {
result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules_systemvm", "vmName", vmName);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default network rules for " + vmName);
} else {
s_logger.info("Programmed default network rules for " + vmName);
}
}
} else {
// For user vm, program the rules for each nic if the
// isolation uri scheme is ec2
final NicTO[] nics = vmSpec.getNics();
for (final NicTO nic : nics) {
if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
final List<String> nicSecIps = nic.getNicSecIps();
String secIpsStr;
final StringBuilder sb = new StringBuilder();
if (nicSecIps != null) {
for (final String ip : nicSecIps) {
sb.append(ip).append(":");
}
secIpsStr = sb.toString();
} else {
secIpsStr = "0:";
}
result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(),
"vmID", Long.toString(vmSpec.getId()), "secIps", secIpsStr);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
} else {
s_logger.info("Programmed default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
}
}
}
}
}
state = VmPowerState.RUNNING;
final StartAnswer startAnswer = new StartAnswer(command);
startAnswer.setIqnToPath(iqnToPath);
return startAnswer;
} catch (final Exception e) {
s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
final String msg = citrixResourceBase.handleVmStartFailure(conn, vmName, vm, "", e);
final StartAnswer startAnswer = new StartAnswer(command, msg);
startAnswer.setIqnToPath(iqnToPath);
return startAnswer;
} finally {
if (state != VmPowerState.HALTED) {
s_logger.debug("2. The VM " + vmName + " is in " + state + " state.");
} else {
s_logger.debug("The VM is in stopped state, detected problem during startup : " + vmName);
}
}
}
}

View File

@ -0,0 +1,173 @@
//
// 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.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.StringUtils;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.SR;
import com.xensource.xenapi.Types.VmPowerState;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VGPU;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
public final class CitrixStopCommandWrapper extends CommandWrapper<StopCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixStopCommandWrapper.class);
@Override
public Answer execute(final StopCommand command, final CitrixResourceBase citrixResourceBase) {
final String vmName = command.getVmName();
String platformstring = null;
try {
final Connection conn = citrixResourceBase.getConnection();
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
// stop vm which is running on this host or is in halted state
final Iterator<VM> iter = vms.iterator();
while (iter.hasNext()) {
final VM vm = iter.next();
final VM.Record vmr = vm.getRecord(conn);
if (vmr.powerState != VmPowerState.RUNNING) {
continue;
}
if (citrixResourceBase.isRefNull(vmr.residentOn)) {
continue;
}
if (vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
continue;
}
iter.remove();
}
if (vms.size() == 0) {
return new StopAnswer(command, "VM does not exist", true);
}
for (final VM vm : vms) {
final VM.Record vmr = vm.getRecord(conn);
platformstring = StringUtils.mapToString(vmr.platform);
if (vmr.isControlDomain) {
final String msg = "Tring to Shutdown control domain";
s_logger.warn(msg);
return new StopAnswer(command, msg, false);
}
if (vmr.powerState == VmPowerState.RUNNING && !citrixResourceBase.isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(citrixResourceBase.getHost().getUuid())) {
final String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + citrixResourceBase.getHost().getUuid() + " but host:" + vmr.residentOn.getUuid(conn);
s_logger.warn(msg);
return new StopAnswer(command, msg, platformstring, false);
}
if (command.checkBeforeCleanup() && vmr.powerState == VmPowerState.RUNNING) {
final String msg = "Vm " + vmName + " is running on host and checkBeforeCleanup flag is set, so bailing out";
s_logger.debug(msg);
return new StopAnswer(command, msg, false);
}
s_logger.debug("9. The VM " + vmName + " is in Stopping state");
try {
if (vmr.powerState == VmPowerState.RUNNING) {
/* when stop a vm, set affinity to current xenserver */
vm.setAffinity(conn, vm.getResidentOn(conn));
if (citrixResourceBase.canBridgeFirewall()) {
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "destroy_network_rules_for_vm", "vmName", command.getVmName());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to remove network rules for vm " + command.getVmName());
} else {
s_logger.info("Removed network rules for vm " + command.getVmName());
}
}
citrixResourceBase.shutdownVM(conn, vm, vmName);
}
} catch (final Exception e) {
final String msg = "Catch exception " + e.getClass().getName() + " when stop VM:" + command.getVmName() + " due to " + e.toString();
s_logger.debug(msg);
return new StopAnswer(command, msg, platformstring, false);
} finally {
try {
if (vm.getPowerState(conn) == VmPowerState.HALTED) {
Set<VGPU> vGPUs = null;
// Get updated GPU details
try {
vGPUs = vm.getVGPUs(conn);
} catch (final XenAPIException e2) {
s_logger.debug("VM " + vmName + " does not have GPU support.");
}
if (vGPUs != null && !vGPUs.isEmpty()) {
final HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = citrixResourceBase.getGPUGroupDetails(conn);
command.setGpuDevice(new GPUDeviceTO(null, null, groupDetails));
}
final Set<VIF> vifs = vm.getVIFs(conn);
final List<Network> networks = new ArrayList<Network>();
for (final VIF vif : vifs) {
networks.add(vif.getNetwork(conn));
}
vm.destroy(conn);
final SR sr = citrixResourceBase.getISOSRbyVmName(conn, command.getVmName());
citrixResourceBase.removeSR(conn, sr);
// Disable any VLAN networks that aren't used
// anymore
for (final Network network : networks) {
try {
if (network.getNameLabel(conn).startsWith("VLAN")) {
citrixResourceBase.disableVlanNetwork(conn, network);
}
} catch (final Exception e) {
// network might be destroyed by other host
}
}
return new StopAnswer(command, "Stop VM " + vmName + " Succeed", platformstring, true);
}
} catch (final Exception e) {
final String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage();
s_logger.warn(msg, e);
} finally {
s_logger.debug("10. The VM " + vmName + " is in Stopped state");
}
}
}
} catch (final Exception e) {
final String msg = "Stop Vm " + vmName + " fail due to " + e.toString();
s_logger.warn(msg, e);
return new StopAnswer(command, msg, platformstring, false);
}
return new StopAnswer(command, "Stop VM failed", platformstring, false);
}
}

View File

@ -0,0 +1,72 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.UnPlugNicAnswer;
import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Network;
import com.xensource.xenapi.VIF;
import com.xensource.xenapi.VM;
public final class CitrixUnPlugNicCommandWrapper extends CommandWrapper<UnPlugNicCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixUnPlugNicCommandWrapper.class);
@Override
public Answer execute(final UnPlugNicCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final String vmName = command.getVmName();
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms == null || vms.isEmpty()) {
return new UnPlugNicAnswer(command, false, "Can not find VM " + vmName);
}
final VM vm = vms.iterator().next();
final NicTO nic = command.getNic();
final String mac = nic.getMac();
final VIF vif = citrixResourceBase.getVifByMac(conn, vm, mac);
if (vif != null) {
vif.unplug(conn);
final Network network = vif.getNetwork(conn);
vif.destroy(conn);
try {
if (network.getNameLabel(conn).startsWith("VLAN")) {
citrixResourceBase.disableVlanNetwork(conn, network);
}
} catch (final Exception e) {
}
}
return new UnPlugNicAnswer(command, true, "success");
} catch (final Exception e) {
final String msg = " UnPlug Nic failed due to " + e.toString();
s_logger.warn(msg, e);
return new UnPlugNicAnswer(command, false, msg);
}
}
}

View File

@ -0,0 +1,34 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.UpdateHostPasswordCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final UpdateHostPasswordCommand command, final CitrixResourceBase citrixResourceBase) {
citrixResourceBase.addToPwdQueue(command.getNewPassword());
return new Answer(command, true, null);
}
}

View File

@ -0,0 +1,64 @@
//
// 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.net.URI;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
public final class CitrixUpgradeSnapshotCommandWrapper extends CommandWrapper<UpgradeSnapshotCommand, Answer, CitrixResourceBase> {
private static final Logger s_logger = Logger.getLogger(CitrixUpgradeSnapshotCommandWrapper.class);
@Override
public Answer execute(final UpgradeSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String secondaryStorageUrl = command.getSecondaryStorageUrl();
final String backedUpSnapshotUuid = command.getSnapshotUuid();
final Long volumeId = command.getVolumeId();
final Long accountId = command.getAccountId();
final Long templateId = command.getTemplateId();
final Long tmpltAcountId = command.getTmpltAccountId();
final String version = command.getVersion();
if (!version.equals("2.1")) {
return new Answer(command, true, "success");
}
try {
final Connection conn = citrixResourceBase.getConnection();
final URI uri = new URI(secondaryStorageUrl);
final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
final String snapshotPath = secondaryStorageMountPath + "/snapshots/" + accountId + "/" + volumeId + "/" + backedUpSnapshotUuid + ".vhd";
final String templatePath = secondaryStorageMountPath + "/template/tmpl/" + tmpltAcountId + "/" + templateId;
citrixResourceBase.upgradeSnapshot(conn, templatePath, snapshotPath);
return new Answer(command, true, "success");
} catch (final Exception e) {
final String details = "upgrading snapshot " + backedUpSnapshotUuid + " failed due to " + e.toString();
s_logger.error(details, e);
}
return new Answer(command, false, "failure");
}
}

View File

@ -0,0 +1,38 @@
//
// 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 com.cloud.agent.api.Answer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
import com.cloud.resource.CommandWrapper;
public final class CitrixWatchConsoleProxyLoadCommandWrapper extends CommandWrapper<WatchConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
@Override
public Answer execute(final WatchConsoleProxyLoadCommand command, final CitrixResourceBase citrixResourceBase) {
final long proxyVmId = command.getProxyVmId();
final String proxyVmName = command.getProxyVmName();
final String proxyManagementIp = command.getProxyManagementIp();
final int cmdPort = command.getProxyCmdPort();
return executeProxyLoadScan(command, proxyVmId, proxyVmName, proxyManagementIp, cmdPort);
}
}

View File

@ -0,0 +1,48 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.resource.CommandWrapper;
public final class XenServer56CheckOnHostCommandWrapper extends CommandWrapper<CheckOnHostCommand, Answer, XenServer56Resource> {
private static final Logger s_logger = Logger.getLogger(XenServer56CheckOnHostCommandWrapper.class);
@Override
public Answer execute(final CheckOnHostCommand command, final XenServer56Resource xenServer56) {
final Boolean alive = xenServer56.checkHeartbeat(command.getHost().getGuid());
String msg = "";
if (alive == null) {
msg = " cannot determine ";
} else if ( alive == true) {
msg = "Heart beat is still going";
} else {
msg = "Heart beat is gone so dead.";
}
s_logger.debug(msg);
return new CheckOnHostAnswer(command, alive, msg);
}
}

View File

@ -0,0 +1,92 @@
//
// 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.HashSet;
import java.util.Map;
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.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VBD;
import com.xensource.xenapi.VDI;
import com.xensource.xenapi.VM;
public final class XenServer56FP1FenceCommandWrapper extends CommandWrapper<FenceCommand, Answer, XenServer56Resource> {
private static final Logger s_logger = Logger.getLogger(XenServer56FP1FenceCommandWrapper.class);
@Override
public Answer execute(final FenceCommand command, final XenServer56Resource xenServer56) {
final Connection conn = xenServer56.getConnection();
try {
final Boolean alive = xenServer56.checkHeartbeat(command.getHostGuid());
if ( alive == null ) {
s_logger.debug("Failed to check heartbeat, so unable to fence");
return new FenceAnswer(command, false, "Failed to check heartbeat, so unable to fence");
}
if ( alive ) {
s_logger.debug("Heart beat is still going so unable to fence");
return new FenceAnswer(command, false, "Heartbeat is still going on unable to fence");
}
final Set<VM> vms = VM.getByNameLabel(conn, command.getVmName());
for (final VM vm : vms) {
final Set<VDI> vdis = new HashSet<VDI>();
final Set<VBD> vbds = vm.getVBDs(conn);
for (final VBD vbd : vbds) {
final VDI vdi = vbd.getVDI(conn);
if (!xenServer56.isRefNull(vdi)) {
vdis.add(vdi);
}
}
s_logger.info("Fence command for VM " + command.getVmName());
vm.powerStateReset(conn);
vm.destroy(conn);
for (final VDI vdi : vdis) {
final Map<String, String> smConfig = vdi.getSmConfig(conn);
for (final String key : smConfig.keySet()) {
if (key.startsWith("host_")) {
vdi.removeFromSmConfig(conn, key);
break;
}
}
}
}
return new FenceAnswer(command);
} catch (final XmlRpcException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
} catch (final XenAPIException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
} catch (final Exception e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,71 @@
//
// 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.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.resource.CommandWrapper;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM;
public final class XenServer56FenceCommandWrapper extends CommandWrapper<FenceCommand, Answer, XenServer56Resource> {
private static final Logger s_logger = Logger.getLogger(XenServer56FenceCommandWrapper.class);
@Override
public Answer execute(final FenceCommand command, final XenServer56Resource xenServer56) {
final Connection conn = xenServer56.getConnection();
try {
final Boolean alive = xenServer56.checkHeartbeat(command.getHostGuid());
if (alive == null) {
s_logger.debug("Failed to check heartbeat, so unable to fence");
return new FenceAnswer(command, false, "Failed to check heartbeat, so unable to fence");
}
if (alive) {
s_logger.debug("Heart beat is still going so unable to fence");
return new FenceAnswer(command, false, "Heartbeat is still going on unable to fence");
}
final Set<VM> vms = VM.getByNameLabel(conn, command.getVmName());
for (final VM vm : vms) {
s_logger.info("Fence command for VM " + command.getVmName());
vm.powerStateReset(conn);
vm.destroy(conn);
}
return new FenceAnswer(command);
} catch (final XmlRpcException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
} catch (final XenAPIException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
} catch (final Exception e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(command, false, e.getMessage());
}
}
}

View File

@ -0,0 +1,102 @@
//
// 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 org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.resource.CommandWrapper;
import com.cloud.utils.ExecutionResult;
import com.xensource.xenapi.Connection;
public final class XenServer56NetworkUsageCommandWrapper extends CommandWrapper<NetworkUsageCommand, Answer, XenServer56Resource> {
private static final Logger s_logger = Logger.getLogger(XenServer56NetworkUsageCommandWrapper.class);
@Override
public Answer execute(final NetworkUsageCommand command, final XenServer56Resource xenServer56) {
if (command.isForVpc()) {
return executeNetworkUsage(command, xenServer56);
}
try {
final Connection conn = xenServer56.getConnection();
if (command.getOption() != null && command.getOption().equals("create")) {
final String result = xenServer56.networkUsage(conn, command.getPrivateIP(), "create", null);
final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, result, 0L, 0L);
return answer;
}
final long[] stats = xenServer56.getNetworkStats(conn, command.getPrivateIP());
final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, "", stats[0], stats[1]);
return answer;
} catch (final Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(command, ex);
}
}
protected NetworkUsageAnswer executeNetworkUsage(final NetworkUsageCommand command, final XenServer56Resource xenServer56) {
try {
final String option = command.getOption();
final String publicIp = command.getGatewayIP();
String args = " -l " + publicIp + " ";
if (option.equals("get")) {
args += "-g";
} else if (option.equals("create")) {
args += "-c";
final String vpcCIDR = command.getVpcCIDR();
args += " -v " + vpcCIDR;
} else if (option.equals("reset")) {
args += "-r";
} else if (option.equals("vpn")) {
args += "-n";
} else if (option.equals("remove")) {
args += "-d";
} else {
return new NetworkUsageAnswer(command, "success", 0L, 0L);
}
final ExecutionResult result = xenServer56.executeInVR(command.getPrivateIP(), "vpc_netusage.sh", args);
final String detail = result.getDetails();
if (!result.isSuccess()) {
throw new Exception(" vpc network usage plugin call failed ");
}
if (option.equals("get") || option.equals("vpn")) {
final long[] stats = new long[2];
if (detail != null) {
final String[] splitResult = detail.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += new Long(splitResult[i++]).longValue();
stats[1] += new Long(splitResult[i++]).longValue();
}
return new NetworkUsageAnswer(command, "success", stats[0], stats[1]);
}
}
return new NetworkUsageAnswer(command, "success", 0L, 0L);
} catch (final Exception ex) {
s_logger.warn("Failed to get network usage stats due to ", ex);
return new NetworkUsageAnswer(command, ex);
}
}
}

View File

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

View File

@ -1,190 +0,0 @@
/*
* 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 static org.junit.Assert.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.xmlrpc.XmlRpcException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import com.xensource.xenapi.Connection;
import com.xensource.xenapi.Host;
import com.xensource.xenapi.Types;
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) {
return super.execute(cmd);
}
@Override
public String callHostPlugin(Connection conn, String plugin, String cmd, String... params) {
return "Success";
}
@Override
protected void scaleVM(Connection conn, VM vm, VirtualMachineTO vmSpec, Host host) throws Types.XenAPIException, XmlRpcException {
_host.speed = 500;
super.scaleVM(conn, vm, vmSpec, host);
}
@Override
protected boolean isDmcEnabled(Connection conn, Host host) throws Types.XenAPIException, XmlRpcException {
return true;
}
};
@Mock
XsHost _host;
@Mock
Host host;
@Mock
ScaleVmCommand cmd;
@Mock
VirtualMachineTO vmSpec;
@Mock
Connection conn;
@Mock
VM vm;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doReturn(vmSpec).when(cmd).getVirtualMachine();
doReturn("i-2-3-VM").when(vmSpec).getName();
}
// Expecting XmlRpcException while trying to get the record of vm using connection
@Test(expected = XmlRpcException.class)
public void testScaleVMF1() throws Types.BadServerResponse, Types.XenAPIException, XmlRpcException {
doReturn(conn).when(_resource).getConnection();
Set<VM> vms = mock(Set.class);
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);
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);
doReturn(new String("OpaqueRef:NULL")).when(object).toWireString();
doNothing().when(_resource).scaleVM(conn, vm, vmSpec, host);
_resource.execute(cmd);
verify(iter, times(2)).hasNext();
verify(iter, times(2)).next();
}
// Test to scale vm "i-2-3-VM" cpu-cap disabled
@Test
public void testScaleVMF2() throws Types.XenAPIException, XmlRpcException {
when(vm.getMemoryStaticMax(conn)).thenReturn(1073741824L);
when(vm.getMemoryStaticMin(conn)).thenReturn(268435456L);
doReturn(536870912L).when(vmSpec).getMinRam();
doReturn(536870912L).when(vmSpec).getMaxRam();
doNothing().when(vm).setMemoryDynamicRange(conn, 536870912L, 536870912L);
doReturn(1).when(vmSpec).getCpus();
doNothing().when(vm).setVCPUsNumberLive(conn, 1L);
doReturn(500).when(vmSpec).getMinSpeed();
doReturn(false).when(vmSpec).getLimitCpuUse();
Map<String, String> args = mock(HashMap.class);
when(host.callPlugin(conn, "vmops", "add_to_VCPUs_params_live", args)).thenReturn("Success");
doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
_resource.scaleVM(conn, vm, vmSpec, host);
verify(vmSpec, times(1)).getLimitCpuUse();
verify(_resource, times(1)).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
}
// Test to scale vm "i-2-3-VM" cpu-cap enabled
@Test
public void testScaleVMF3() throws Types.XenAPIException, XmlRpcException {
when(vm.getMemoryStaticMax(conn)).thenReturn(1073741824L);
when(vm.getMemoryStaticMin(conn)).thenReturn(268435456L);
doReturn(536870912L).when(vmSpec).getMinRam();
doReturn(536870912L).when(vmSpec).getMaxRam();
doNothing().when(vm).setMemoryDynamicRange(conn, 536870912L, 536870912L);
doReturn(1).when(vmSpec).getCpus();
doNothing().when(vm).setVCPUsNumberLive(conn, 1L);
doReturn(500).when(vmSpec).getMinSpeed();
doReturn(500).when(vmSpec).getMaxSpeed();
doReturn(true).when(vmSpec).getLimitCpuUse();
doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", "99", "vmname", "i-2-3-VM");
Map<String, String> args = mock(HashMap.class);
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");
_resource.scaleVM(conn, vm, vmSpec, host);
verify(vmSpec, times(1)).getLimitCpuUse();
verify(_resource, times(1)).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
verify(_resource, times(1)).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", "99", "vmname", "i-2-3-VM");
}
@Test
public void testSetNicDevIdIfCorrectVifIsNotNull() throws Exception {
IpAddressTO ip = mock(IpAddressTO.class);
when(ip.isAdd()).thenReturn(false);
VIF correctVif = null;
try {
_resource.setNicDevIdIfCorrectVifIsNotNull(conn, ip, correctVif);
} catch (NullPointerException e) {
fail("this test is meant to show that null pointer is not thrown");
}
}
}

View File

@ -0,0 +1,49 @@
package com.cloud.hypervisor.xenserver.resource.wrapper;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.host.Host;
import com.cloud.hypervisor.xenserver.resource.XenServer56FP1Resource;
import com.cloud.vm.VMInstanceVO;
import com.xensource.xenapi.Connection;
@RunWith(PowerMockRunner.class)
public class XenServer56FP1WrapperTest {
@Mock
private XenServer56FP1Resource xenServer56Resource;
@Test
public void testFenceCommand() {
final VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
final Host host = Mockito.mock(Host.class);
final Connection conn = Mockito.mock(Connection.class);
final FenceCommand fenceCommand = new FenceCommand(vm, host);
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(xenServer56Resource.getConnection()).thenReturn(conn);
final Answer answer = wrapper.execute(fenceCommand, xenServer56Resource);
verify(xenServer56Resource, times(1)).getConnection();
verify(xenServer56Resource, times(1)).checkHeartbeat(fenceCommand.getHostGuid());
assertFalse(answer.getResult());
}
}

View File

@ -0,0 +1,161 @@
package com.cloud.hypervisor.xenserver.resource.wrapper;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.SetupCommand;
import com.cloud.host.Host;
import com.cloud.host.HostEnvironment;
import com.cloud.hypervisor.xenserver.resource.XenServer56Resource;
import com.cloud.hypervisor.xenserver.resource.XsHost;
import com.cloud.utils.ExecutionResult;
import com.cloud.vm.VMInstanceVO;
import com.xensource.xenapi.Connection;
@RunWith(PowerMockRunner.class)
public class XenServer56WrapperTest {
@Mock
private XenServer56Resource xenServer56Resource;
@Test
public void testCheckOnHostCommand() {
final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);
final CheckOnHostCommand onHostCommand = new CheckOnHostCommand(host);
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(onHostCommand, xenServer56Resource);
assertTrue(answer.getResult());
}
@Test
public void testFenceCommand() {
final VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
final Host host = Mockito.mock(Host.class);
final Connection conn = Mockito.mock(Connection.class);
final FenceCommand fenceCommand = new FenceCommand(vm, host);
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(xenServer56Resource.getConnection()).thenReturn(conn);
final Answer answer = wrapper.execute(fenceCommand, xenServer56Resource);
verify(xenServer56Resource, times(1)).getConnection();
verify(xenServer56Resource, times(1)).checkHeartbeat(fenceCommand.getHostGuid());
assertFalse(answer.getResult());
}
@Test
public void testNetworkUsageCommandSuccess() {
final Connection conn = Mockito.mock(Connection.class);
final NetworkUsageCommand networkCommand = new NetworkUsageCommand("192.168.10.10", "domRName", false, "192.168.10.1");
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(xenServer56Resource.getConnection()).thenReturn(conn);
when(xenServer56Resource.getNetworkStats(conn, networkCommand.getPrivateIP())).thenReturn(new long[]{1, 1});
final Answer answer = wrapper.execute(networkCommand, xenServer56Resource);
verify(xenServer56Resource, times(1)).getConnection();
assertTrue(answer.getResult());
}
@Test
public void testNetworkUsageCommandFailure() {
final Connection conn = Mockito.mock(Connection.class);
final NetworkUsageCommand networkCommand = new NetworkUsageCommand("192.168.10.10", "domRName", false, "192.168.10.1");
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(xenServer56Resource.getConnection()).thenReturn(conn);
when(xenServer56Resource.getNetworkStats(conn, networkCommand.getPrivateIP())).thenReturn(new long[0]);
final Answer answer = wrapper.execute(networkCommand, xenServer56Resource);
verify(xenServer56Resource, times(1)).getConnection();
assertFalse(answer.getResult());
}
@Test
public void testNetworkUsageCommandCreateVpc() {
final ExecutionResult executionResult = Mockito.mock(ExecutionResult.class);
final NetworkUsageCommand networkCommand = new NetworkUsageCommand("192.168.10.10", "domRName", true, "192.168.10.1", "10.1.1.1/24");
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
final String args = " -l 192.168.10.1 -c -v 10.1.1.1/24";
when(xenServer56Resource.executeInVR(networkCommand.getPrivateIP(), "vpc_netusage.sh", args)).thenReturn(executionResult);
when(executionResult.isSuccess()).thenReturn(true);
final Answer answer = wrapper.execute(networkCommand, xenServer56Resource);
assertTrue(answer.getResult());
}
@Test
public void testNetworkUsageCommandCreateVpcFailure() {
final ExecutionResult executionResult = Mockito.mock(ExecutionResult.class);
final NetworkUsageCommand networkCommand = new NetworkUsageCommand("192.168.10.10", "domRName", true, "192.168.10.1", "10.1.1.1/24");
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
final String args = " -l 192.168.10.1 -c -v 10.1.1.1/24";
when(xenServer56Resource.executeInVR(networkCommand.getPrivateIP(), "vpc_netusage.sh", args)).thenReturn(executionResult);
when(executionResult.isSuccess()).thenReturn(false);
final Answer answer = wrapper.execute(networkCommand, xenServer56Resource);
assertFalse(answer.getResult());
}
@Test
public void testSetupCommand() {
final XsHost xsHost = Mockito.mock(XsHost.class);
final HostEnvironment env = Mockito.mock(HostEnvironment.class);
final SetupCommand setupCommand = new SetupCommand(env);
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(xenServer56Resource.getHost()).thenReturn(xsHost);
final Answer answer = wrapper.execute(setupCommand, xenServer56Resource);
verify(xenServer56Resource, times(1)).getConnection();
assertFalse(answer.getResult());
}
}

View File

@ -0,0 +1,56 @@
package com.cloud.hypervisor.xenserver.resource.wrapper;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.SetupCommand;
import com.cloud.host.HostEnvironment;
import com.cloud.hypervisor.xenserver.resource.XenServer610Resource;
import com.cloud.network.PhysicalNetworkSetupInfo;
@RunWith(PowerMockRunner.class)
public class XenServer610WrapperTest {
@Mock
protected XenServer610Resource xenServer610Resource;
@Test
public void testCheckNetworkCommandFailure() {
final XenServer610Resource xenServer610Resource = new XenServer610Resource();
final PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo();
final List<PhysicalNetworkSetupInfo> setupInfos = new ArrayList<PhysicalNetworkSetupInfo>();
setupInfos.add(info);
final CheckNetworkCommand checkNet = new CheckNetworkCommand(setupInfos);
final Answer answer = xenServer610Resource.executeRequest(checkNet);
assertTrue(answer.getResult());
}
@Test
public void testSetupCommand() {
final XenServer610Resource xenServer610Resource = new XenServer610Resource();
final HostEnvironment env = Mockito.mock(HostEnvironment.class);
final SetupCommand setupCommand = new SetupCommand(env);
final Answer answer = xenServer610Resource.executeRequest(setupCommand);
assertFalse(answer.getResult());
}
}

View File

@ -0,0 +1,35 @@
package com.cloud.hypervisor.xenserver.resource.wrapper;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.hypervisor.xenserver.resource.XenServer620Resource;
import com.cloud.network.PhysicalNetworkSetupInfo;
@RunWith(PowerMockRunner.class)
public class XenServer620WrapperTest {
@Test
public void testCheckNetworkCommandFailure() {
final XenServer620Resource xenServer620Resource = new XenServer620Resource();
final PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo();
final List<PhysicalNetworkSetupInfo> setupInfos = new ArrayList<PhysicalNetworkSetupInfo>();
setupInfos.add(info);
final CheckNetworkCommand checkNet = new CheckNetworkCommand(setupInfos);
final Answer answer = xenServer620Resource.executeRequest(checkNet);
assertTrue(answer.getResult());
}
}