fixing some more formatting issues

This commit is contained in:
David Nalley 2012-02-10 20:34:44 -05:00
parent 783b9e7f6e
commit c11d702cac
16 changed files with 1604 additions and 1497 deletions

View File

@ -1,6 +1,6 @@
/**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
*
*
*
* This software is licensed under the GNU General Public License v3 or later.
*
@ -31,10 +31,8 @@
*
*/
package com.cloud.agent.resource.computing;
import java.net.InetAddress;
import java.util.ArrayList;
@ -42,7 +40,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
@ -50,8 +47,6 @@ import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.LibvirtException;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StartAnswer;
@ -67,7 +62,6 @@ import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.dhcp.DhcpSnooper;
import com.cloud.agent.dhcp.DhcpSnooperImpl;
import com.cloud.agent.resource.computing.LibvirtComputingResource;
import com.cloud.agent.resource.computing.LibvirtConnection;
import com.cloud.agent.resource.computing.LibvirtVMDef;
@ -76,7 +70,6 @@ import com.cloud.agent.resource.computing.LibvirtVMDef.InterfaceDef;
import com.cloud.agent.vmdata.JettyVmDataServer;
import com.cloud.agent.vmdata.VmDataServer;
import com.cloud.network.Networks.TrafficType;
import com.cloud.utils.Pair;
import com.cloud.vm.VirtualMachine;
@ -84,229 +77,234 @@ import com.cloud.vm.VirtualMachine.State;
/**
* Logic specific to the Cloudzones feature
*
* }
*
* }
**/
public class CloudZonesComputingResource extends LibvirtComputingResource {
private static final Logger s_logger = Logger.getLogger(CloudZonesComputingResource.class);
protected DhcpSnooper _dhcpSnooper;
String _parent;
long _dhcpTimeout;
protected String _hostIp;
protected String _hostMacAddress;
protected VmDataServer _vmDataServer = new JettyVmDataServer();
private static final Logger s_logger = Logger
.getLogger(CloudZonesComputingResource.class);
protected DhcpSnooper _dhcpSnooper;
String _parent;
long _dhcpTimeout;
protected String _hostIp;
protected String _hostMacAddress;
protected VmDataServer _vmDataServer = new JettyVmDataServer();
private void setupDhcpManager(Connect conn, String bridgeName) {
private void setupDhcpManager(Connect conn, String bridgeName) {
_dhcpSnooper = new DhcpSnooperImpl(bridgeName, _dhcpTimeout);
_dhcpSnooper = new DhcpSnooperImpl(bridgeName, _dhcpTimeout);
List<Pair<String, String>> macs = new ArrayList<Pair<String, String>>();
try {
int[] domainIds = conn.listDomains();
for (int i = 0; i < domainIds.length; i++) {
Domain vm = conn.domainLookupByID(domainIds[i]);
if (vm.getName().startsWith("i-")) {
List<InterfaceDef> nics = getInterfaces(conn, vm.getName());
InterfaceDef nic = nics.get(0);
macs.add(new Pair<String, String>(nic.getMacAddress(), vm
.getName()));
}
}
} catch (LibvirtException e) {
s_logger.debug("Failed to get MACs: " + e.toString());
}
List<Pair<String, String>> macs = new ArrayList<Pair<String, String>>();
try {
int[] domainIds = conn.listDomains();
for (int i = 0; i < domainIds.length; i++) {
Domain vm = conn.domainLookupByID(domainIds[i]);
if (vm.getName().startsWith("i-")) {
List<InterfaceDef> nics = getInterfaces(conn, vm.getName());
InterfaceDef nic = nics.get(0);
macs.add(new Pair<String, String>(nic.getMacAddress(), vm.getName()));
}
}
} catch (LibvirtException e) {
s_logger.debug("Failed to get MACs: " + e.toString());
}
_dhcpSnooper.initializeMacTable(macs);
}
_dhcpSnooper.initializeMacTable(macs);
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
boolean success = super.configure(name, params);
if (!success) {
return false;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
boolean success = super.configure(name, params);
if (!success) {
return false;
}
_parent = (String) params.get("mount.path");
_parent = (String)params.get("mount.path");
try {
_dhcpTimeout = Long.parseLong((String) params.get("dhcp.timeout"));
} catch (Exception e) {
_dhcpTimeout = 1200000;
}
try {
_dhcpTimeout = Long.parseLong((String)params.get("dhcp.timeout"));
} catch (Exception e) {
_dhcpTimeout = 1200000;
}
_hostIp = (String) params.get("host.ip");
_hostMacAddress = (String) params.get("host.mac.address");
_hostIp = (String)params.get("host.ip");
_hostMacAddress = (String)params.get("host.mac.address");
try {
Connect conn;
conn = LibvirtConnection.getConnection();
setupDhcpManager(conn, _guestBridgeName);
} catch (LibvirtException e) {
s_logger.debug("Failed to get libvirt connection:" + e.toString());
return false;
}
try {
Connect conn;
conn = LibvirtConnection.getConnection();
setupDhcpManager(conn, _guestBridgeName);
} catch (LibvirtException e) {
s_logger.debug("Failed to get libvirt connection:" + e.toString());
return false;
}
_dhcpSnooper.configure(name, params);
_vmDataServer.configure(name, params);
_dhcpSnooper.configure(name, params);
_vmDataServer.configure(name, params);
return true;
}
return true;
}
@Override
protected synchronized StartAnswer execute(StartCommand cmd) {
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
String vmName = vmSpec.getName();
LibvirtVMDef vm = null;
@Override
protected synchronized StartAnswer execute(StartCommand cmd) {
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
String vmName = vmSpec.getName();
LibvirtVMDef vm = null;
State state = State.Stopped;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
synchronized (_vms) {
_vms.put(vmName, State.Starting);
}
State state = State.Stopped;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
synchronized (_vms) {
_vms.put(vmName, State.Starting);
}
vm = createVMFromSpec(vmSpec);
vm = createVMFromSpec(vmSpec);
createVbd(conn, vmSpec, vmName, vm);
createVbd(conn, vmSpec, vmName, vm);
createVifs(conn, vmSpec, vm);
createVifs(conn, vmSpec, vm);
s_logger.debug("starting " + vmName + ": " + vm.toString());
startDomain(conn, vmName, vm.toString());
s_logger.debug("starting " + vmName + ": " + vm.toString());
startDomain(conn, vmName, vm.toString());
NicTO[] nics = vmSpec.getNics();
for (NicTO nic : nics) {
if (nic.isSecurityGroupEnabled()) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
default_network_rules_for_systemvm(conn, vmName);
} else {
nic.setIp(null);
default_network_rules(conn, vmName, nic, vmSpec.getId());
}
}
}
// Attach each data volume to the VM, if there is a deferred
// attached disk
for (DiskDef disk : vm.getDevices().getDisks()) {
if (disk.isAttachDeferred()) {
attachOrDetachDevice(conn, true, vmName, disk.toString());
}
}
NicTO[] nics = vmSpec.getNics();
for (NicTO nic : nics) {
if (nic.isSecurityGroupEnabled()) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
default_network_rules_for_systemvm(conn, vmName);
} else {
nic.setIp(null);
default_network_rules(conn, vmName, nic, vmSpec.getId());
}
}
}
if (vmSpec.getType() == VirtualMachine.Type.User) {
for (NicTO nic : nics) {
if (nic.getType() == TrafficType.Guest) {
InetAddress ipAddr = _dhcpSnooper.getIPAddr(
nic.getMac(), vmName);
if (ipAddr == null) {
s_logger.debug("Failed to get guest DHCP ip, stop it");
StopCommand stpCmd = new StopCommand(vmName);
execute(stpCmd);
return new StartAnswer(cmd,
"Failed to get guest DHCP ip, stop it");
}
s_logger.debug(ipAddr);
nic.setIp(ipAddr.getHostAddress());
// Attach each data volume to the VM, if there is a deferred attached disk
for (DiskDef disk : vm.getDevices().getDisks()) {
if (disk.isAttachDeferred()) {
attachOrDetachDevice(conn, true, vmName, disk.toString());
}
}
post_default_network_rules(conn, vmName, nic,
vmSpec.getId(), _dhcpSnooper.getDhcpServerIP(),
_hostIp, _hostMacAddress);
_vmDataServer.handleVmStarted(cmd.getVirtualMachine());
}
}
}
if (vmSpec.getType() == VirtualMachine.Type.User) {
for (NicTO nic: nics) {
if (nic.getType() == TrafficType.Guest) {
InetAddress ipAddr = _dhcpSnooper.getIPAddr(nic.getMac(), vmName);
if (ipAddr == null) {
s_logger.debug("Failed to get guest DHCP ip, stop it");
StopCommand stpCmd = new StopCommand(vmName);
execute(stpCmd);
return new StartAnswer(cmd, "Failed to get guest DHCP ip, stop it");
}
s_logger.debug(ipAddr);
nic.setIp(ipAddr.getHostAddress());
state = State.Running;
return new StartAnswer(cmd);
} catch (Exception e) {
s_logger.warn("Exception ", e);
if (conn != null) {
handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(cmd, e.getMessage());
} finally {
synchronized (_vms) {
if (state != State.Stopped) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
post_default_network_rules(conn, vmName, nic, vmSpec.getId(), _dhcpSnooper.getDhcpServerIP(), _hostIp, _hostMacAddress);
_vmDataServer.handleVmStarted(cmd.getVirtualMachine());
}
}
}
protected Answer execute(StopCommand cmd) {
final String vmName = cmd.getVmName();
state = State.Running;
return new StartAnswer(cmd);
} catch (Exception e) {
s_logger.warn("Exception ", e);
if (conn != null) {
handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(cmd, e.getMessage());
} finally {
synchronized (_vms) {
if (state != State.Stopped) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
Long bytesReceived = new Long(0);
Long bytesSent = new Long(0);
protected Answer execute(StopCommand cmd) {
final String vmName = cmd.getVmName();
State state = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
Connect conn = LibvirtConnection.getConnection();
Long bytesReceived = new Long(0);
Long bytesSent = new Long(0);
try {
Domain dm = conn.domainLookupByUUID(UUID
.nameUUIDFromBytes(vmName.getBytes()));
} catch (LibvirtException e) {
state = State.Stopped;
return new StopAnswer(cmd, null, 0, bytesSent, bytesReceived);
}
State state = null;
synchronized(_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
Connect conn = LibvirtConnection.getConnection();
String macAddress = null;
if (vmName.startsWith("i-")) {
List<InterfaceDef> nics = getInterfaces(conn, vmName);
if (!nics.isEmpty()) {
macAddress = nics.get(0).getMacAddress();
}
}
try {
Domain dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
} catch (LibvirtException e) {
state = State.Stopped;
return new StopAnswer(cmd, null, 0, bytesSent, bytesReceived);
}
destroy_network_rules_for_vm(conn, vmName);
String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
String macAddress = null;
if (vmName.startsWith("i-")) {
List<InterfaceDef> nics = getInterfaces(conn, vmName);
if (!nics.isEmpty()) {
macAddress = nics.get(0).getMacAddress();
}
}
try {
cleanupVnet(conn, cmd.getVnet());
_dhcpSnooper.cleanup(macAddress, vmName);
_vmDataServer.handleVmStopped(cmd.getVmName());
} catch (Exception e) {
destroy_network_rules_for_vm(conn, vmName);
String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
}
try {
cleanupVnet(conn, cmd.getVnet());
_dhcpSnooper.cleanup(macAddress, vmName);
_vmDataServer.handleVmStopped(cmd.getVmName());
} catch (Exception e) {
state = State.Stopped;
return new StopAnswer(cmd, result, 0, bytesSent, bytesReceived);
} catch (LibvirtException e) {
return new StopAnswer(cmd, e.getMessage());
} finally {
synchronized (_vms) {
if (state != null) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof VmDataCommand) {
return execute((VmDataCommand) cmd);
} else if (cmd instanceof SavePasswordCommand) {
return execute((SavePasswordCommand) cmd);
}
return super.executeRequest(cmd);
}
state = State.Stopped;
return new StopAnswer(cmd, result, 0, bytesSent, bytesReceived);
} catch (LibvirtException e) {
return new StopAnswer(cmd, e.getMessage());
} finally {
synchronized(_vms) {
if (state != null) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
protected Answer execute(final VmDataCommand cmd) {
return _vmDataServer.handleVmDataCommand(cmd);
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof VmDataCommand) {
return execute((VmDataCommand)cmd);
} else if (cmd instanceof SavePasswordCommand) {
return execute ((SavePasswordCommand)cmd);
}
return super.executeRequest(cmd);
}
protected Answer execute(final VmDataCommand cmd) {
return _vmDataServer.handleVmDataCommand(cmd);
}
protected Answer execute(final SavePasswordCommand cmd) {
return new Answer(cmd);
}
protected Answer execute(final SavePasswordCommand cmd) {
return new Answer(cmd);
}
}

View File

@ -24,7 +24,8 @@ import java.util.Map;
import org.apache.log4j.Logger;
public class KVMGuestOsMapper {
private static final Logger s_logger = Logger.getLogger(KVMGuestOsMapper.class);
private static final Logger s_logger = Logger
.getLogger(KVMGuestOsMapper.class);
private static Map<String, String> s_mapper = new HashMap<String, String>();
static {
s_mapper.put("CentOS 4.5 (32-bit)", "CentOS 4.5");
@ -44,27 +45,48 @@ public class KVMGuestOsMapper {
s_mapper.put("CentOS 5.5 (32-bit)", "CentOS 5.5");
s_mapper.put("CentOS 5.5 (64-bit)", "CentOS 5.5");
s_mapper.put("Red Hat Enterprise Linux 2", "Red Hat Enterprise Linux 2");
s_mapper.put("Red Hat Enterprise Linux 3 (32-bit)", "Red Hat Enterprise Linux 3");
s_mapper.put("Red Hat Enterprise Linux 3 (64-bit)", "Red Hat Enterprise Linux 3");
s_mapper.put("Red Hat Enterprise Linux 4(64-bit)", "Red Hat Enterprise Linux 4");
s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5");
s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6");
s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7");
s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8");
s_mapper.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5.0");
s_mapper.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5.0");
s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1");
s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1");
s_mapper.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5.2");
s_mapper.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5.2");
s_mapper.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5.3");
s_mapper.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5.3");
s_mapper.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5.4");
s_mapper.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5.4");
s_mapper.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5.5");
s_mapper.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5.5");
s_mapper.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0");
s_mapper.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0");
s_mapper.put("Red Hat Enterprise Linux 3 (32-bit)",
"Red Hat Enterprise Linux 3");
s_mapper.put("Red Hat Enterprise Linux 3 (64-bit)",
"Red Hat Enterprise Linux 3");
s_mapper.put("Red Hat Enterprise Linux 4(64-bit)",
"Red Hat Enterprise Linux 4");
s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)",
"Red Hat Enterprise Linux 4.5");
s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)",
"Red Hat Enterprise Linux 4.6");
s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)",
"Red Hat Enterprise Linux 4.7");
s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)",
"Red Hat Enterprise Linux 4.8");
s_mapper.put("Red Hat Enterprise Linux 5.0 (32-bit)",
"Red Hat Enterprise Linux 5.0");
s_mapper.put("Red Hat Enterprise Linux 5.0 (64-bit)",
"Red Hat Enterprise Linux 5.0");
s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)",
"Red Hat Enterprise Linux 5.1");
s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)",
"Red Hat Enterprise Linux 5.1");
s_mapper.put("Red Hat Enterprise Linux 5.2 (32-bit)",
"Red Hat Enterprise Linux 5.2");
s_mapper.put("Red Hat Enterprise Linux 5.2 (64-bit)",
"Red Hat Enterprise Linux 5.2");
s_mapper.put("Red Hat Enterprise Linux 5.3 (32-bit)",
"Red Hat Enterprise Linux 5.3");
s_mapper.put("Red Hat Enterprise Linux 5.3 (64-bit)",
"Red Hat Enterprise Linux 5.3");
s_mapper.put("Red Hat Enterprise Linux 5.4 (32-bit)",
"Red Hat Enterprise Linux 5.4");
s_mapper.put("Red Hat Enterprise Linux 5.4 (64-bit)",
"Red Hat Enterprise Linux 5.4");
s_mapper.put("Red Hat Enterprise Linux 5.5 (32-bit)",
"Red Hat Enterprise Linux 5.5");
s_mapper.put("Red Hat Enterprise Linux 5.5 (64-bit)",
"Red Hat Enterprise Linux 5.5");
s_mapper.put("Red Hat Enterprise Linux 6.0 (32-bit)",
"Red Hat Enterprise Linux 6.0");
s_mapper.put("Red Hat Enterprise Linux 6.0 (64-bit)",
"Red Hat Enterprise Linux 6.0");
s_mapper.put("Fedora 13", "Fedora 13");
s_mapper.put("Fedora 12", "Fedora 12");
s_mapper.put("Fedora 11", "Fedora 11");
@ -97,14 +119,21 @@ public class KVMGuestOsMapper {
s_mapper.put("Asianux 3(64-bit)", "Other Linux");
s_mapper.put("Windows 7 (32-bit)", "Windows 7");
s_mapper.put("Windows 7 (64-bit)", "Windows 7");
s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003");
s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 Standard Edition(32-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 Standard Edition(64-bit)",
"Windows Server 2003");
s_mapper.put("Windows Server 2003 Web Edition", "Windows Server 2003");
s_mapper.put("Microsoft Small Bussiness Server 2003", "Windows Server 2003");
s_mapper.put("Microsoft Small Bussiness Server 2003",
"Windows Server 2003");
s_mapper.put("Windows Server 2008 (32-bit)", "Windows Server 2008");
s_mapper.put("Windows Server 2008 (64-bit)", "Windows Server 2008");
s_mapper.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008");
@ -138,4 +167,3 @@ public class KVMGuestOsMapper {
}
}
}

View File

@ -35,17 +35,17 @@ import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.OutputInterpreter.AllLinesParser;
import com.cloud.utils.script.Script;
public class KVMHABase {
private long _timeout = 60000; /*1 minutes*/
private long _timeout = 60000; /* 1 minutes */
protected static String _heartBeatPath;
protected long _heartBeatUpdateTimeout = 60000;
protected long _heartBeatUpdateFreq = 60000;
protected long _heartBeatUpdateMaxRetry = 3;
public static enum PoolType {
PrimaryStorage,
SecondaryStorage
PrimaryStorage, SecondaryStorage
}
public static class NfsStoragePool {
String _poolUUID;
String _poolIp;
@ -53,7 +53,8 @@ public class KVMHABase {
String _mountDestPath;
PoolType _type;
public NfsStoragePool(String poolUUID, String poolIp, String poolSourcePath, String mountDestPath, PoolType type) {
public NfsStoragePool(String poolUUID, String poolIp,
String poolSourcePath, String mountDestPath, PoolType type) {
this._poolUUID = poolUUID;
this._poolIp = poolIp;
this._poolMountSourcePath = poolSourcePath;
@ -64,7 +65,8 @@ public class KVMHABase {
protected String checkingMountPoint(NfsStoragePool pool, String poolName) {
String mountSource = pool._poolIp + ":" + pool._poolMountSourcePath;
String mountPaths = Script.runSimpleBashScript("cat /proc/mounts | grep " + mountSource);
String mountPaths = Script
.runSimpleBashScript("cat /proc/mounts | grep " + mountSource);
String destPath = pool._mountDestPath;
if (mountPaths != null) {
@ -73,7 +75,7 @@ public class KVMHABase {
String mountDestPath = token[1];
if (mountType.equalsIgnoreCase("nfs")) {
if (poolName != null && !mountDestPath.startsWith(destPath)) {
/*we need to mount it under poolName*/
/* we need to mount it under poolName */
Script mount = new Script("/bin/bash", 60000);
mount.add("-c");
mount.add("mount " + mountSource + " " + destPath);
@ -87,8 +89,8 @@ public class KVMHABase {
}
}
} else {
/*Can't find the mount point?*/
/*we need to mount it under poolName*/
/* Can't find the mount point? */
/* we need to mount it under poolName */
if (poolName != null) {
Script mount = new Script("/bin/bash", 60000);
mount.add("-c");
@ -110,13 +112,17 @@ public class KVMHABase {
StoragePool pool = null;
String poolName = null;
try {
pool = LibvirtConnection.getConnection().storagePoolLookupByUUIDString(storagePool._poolUUID);
pool = LibvirtConnection.getConnection()
.storagePoolLookupByUUIDString(storagePool._poolUUID);
if (pool != null) {
StoragePoolInfo spi = pool.getInfo();
if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) {
pool.create(0);
} else {
/*Sometimes, the mount point is lost, even libvirt thinks the storage pool still running*/
/*
* Sometimes, the mount point is lost, even libvirt thinks
* the storage pool still running
*/
}
}
poolName = pool.getName();
@ -136,7 +142,7 @@ public class KVMHABase {
}
protected void destroyVMs(String mountPath) {
/*if there are VMs using disks under this mount path, destroy them*/
/* if there are VMs using disks under this mount path, destroy them */
Script cmd = new Script("/bin/bash", _timeout);
cmd.add("-c");
cmd.add("ps axu|grep qemu|grep " + mountPath + "* |awk '{print $2}'");
@ -154,14 +160,16 @@ public class KVMHABase {
}
protected String getHBFile(String mountPoint, String hostIP) {
return mountPoint + File.separator + "KVMHA" + File.separator + "hb-" + hostIP;
return mountPoint + File.separator + "KVMHA" + File.separator + "hb-"
+ hostIP;
}
protected String getHBFolder(String mountPoint) {
return mountPoint + File.separator + "KVMHA" + File.separator;
}
protected String runScriptRetry(String cmdString, OutputInterpreter interpreter) {
protected String runScriptRetry(String cmdString,
OutputInterpreter interpreter) {
String result = null;
for (int i = 0; i < 3; i++) {
Script cmd = new Script("/bin/bash", _timeout);
@ -184,20 +192,22 @@ public class KVMHABase {
public static void main(String[] args) {
NfsStoragePool pool = new KVMHAMonitor.NfsStoragePool(null,null,null,null, PoolType.PrimaryStorage);
NfsStoragePool pool = new KVMHAMonitor.NfsStoragePool(null, null, null,
null, PoolType.PrimaryStorage);
KVMHAMonitor haWritter = new KVMHAMonitor(pool, "192.168.1.163", null);
Thread ha = new Thread(haWritter);
ha.start();
KVMHAChecker haChecker = new KVMHAChecker(haWritter.getStoragePools(), "192.168.1.163");
KVMHAChecker haChecker = new KVMHAChecker(haWritter.getStoragePools(),
"192.168.1.163");
ExecutorService exe = Executors.newFixedThreadPool(1);
Future<Boolean> future = exe.submit((Callable<Boolean>)haChecker);
Future<Boolean> future = exe.submit((Callable<Boolean>) haChecker);
try {
for (int i = 0; i < 10; i++) {
System.out.println(future.get());
future = exe.submit((Callable<Boolean>)haChecker);
future = exe.submit((Callable<Boolean>) haChecker);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block

View File

@ -28,29 +28,34 @@ import org.libvirt.Connect;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
public class KVMHAChecker extends KVMHABase implements Callable<Boolean> {
private static final Logger s_logger = Logger.getLogger(KVMHAChecker.class);
private List<NfsStoragePool> _pools;
private String _hostIP;
private long _heartBeatCheckerTimeout = 360000; /*6 minutes*/
private long _heartBeatCheckerTimeout = 360000; /* 6 minutes */
public KVMHAChecker(List<NfsStoragePool> pools, String host) {
this._pools = pools;
this._hostIP = host;
}
/*True means heartbeaing is on going, or we can't get it's status. False means heartbeating is stopped definitely */
/*
* True means heartbeaing is on going, or we can't get it's status. False
* means heartbeating is stopped definitely
*/
private Boolean checkingHB() {
List<Boolean> results = new ArrayList<Boolean>();
for (NfsStoragePool pool : _pools) {
Script cmd = new Script(_heartBeatPath, _heartBeatCheckerTimeout, s_logger);
Script cmd = new Script(_heartBeatPath, _heartBeatCheckerTimeout,
s_logger);
cmd.add("-i", pool._poolIp);
cmd.add("-p", pool._poolMountSourcePath);
cmd.add("-m", pool._mountDestPath);
cmd.add("-h", _hostIP);
cmd.add("-r");
cmd.add("-t", String.valueOf((_heartBeatUpdateFreq + _heartBeatUpdateTimeout)/1000 * 2));
cmd.add("-t",
String.valueOf((_heartBeatUpdateFreq + _heartBeatUpdateTimeout) / 1000 * 2));
OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
String result = cmd.execute(parser);
s_logger.debug("pool: " + pool._poolIp);
@ -64,7 +69,6 @@ public class KVMHAChecker extends KVMHABase implements Callable<Boolean> {
}
}
for (Boolean r : results) {
if (r) {
return true;
@ -76,7 +80,8 @@ public class KVMHAChecker extends KVMHABase implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
//s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new org.apache.log4j.PatternLayout(), "System.out"));
// s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new
// org.apache.log4j.PatternLayout(), "System.out"));
return checkingHB();
}
}

View File

@ -25,63 +25,66 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import com.cloud.utils.script.Script;
public class KVMHAMonitor extends KVMHABase implements Runnable{
public class KVMHAMonitor extends KVMHABase implements Runnable {
private static final Logger s_logger = Logger.getLogger(KVMHAMonitor.class);
private Map<String, NfsStoragePool> _storagePool = new ConcurrentHashMap<String, NfsStoragePool>();
private String _hostIP; /*private ip address*/
private String _hostIP; /* private ip address */
public KVMHAMonitor(NfsStoragePool pool, String host, String scriptPath) {
if (pool != null) {
this._storagePool.put(pool._poolUUID, pool);
}
}
this._hostIP = host;
this._heartBeatPath = scriptPath;
}
public void addStoragePool(NfsStoragePool pool) {
synchronized (_storagePool) {
this._storagePool.put(pool._poolUUID, pool);
}
}
public void removeStoragePool(String uuid) {
synchronized (_storagePool) {
this._storagePool.remove(uuid);
}
}
public List<NfsStoragePool> getStoragePools() {
synchronized (_storagePool) {
return new ArrayList<NfsStoragePool>(_storagePool.values());
}
}
private class Monitor implements Runnable {
@Override
public void run() {
synchronized (_storagePool) {
for (NfsStoragePool primaryStoragePool : _storagePool.values()) {
String result = null;
for (int i = 0; i < 5; i++) {
Script cmd = new Script(_heartBeatPath, _heartBeatUpdateTimeout, s_logger);
cmd.add("-i", primaryStoragePool._poolIp);
cmd.add("-p", primaryStoragePool._poolMountSourcePath);
cmd.add("-m", primaryStoragePool._mountDestPath);
cmd.add("-h", _hostIP);
result = cmd.execute();
if (result != null) {
s_logger.warn("write heartbeat failed: " + result + ", retry: " + i);
} else {
break;
}
Script cmd = new Script(_heartBeatPath,
_heartBeatUpdateTimeout, s_logger);
cmd.add("-i", primaryStoragePool._poolIp);
cmd.add("-p", primaryStoragePool._poolMountSourcePath);
cmd.add("-m", primaryStoragePool._mountDestPath);
cmd.add("-h", _hostIP);
result = cmd.execute();
if (result != null) {
s_logger.warn("write heartbeat failed: " + result
+ ", retry: " + i);
} else {
break;
}
}
if (result != null) {
s_logger.warn("write heartbeat failed: " + result + "; reboot the host");
Script cmd = new Script(_heartBeatPath, _heartBeatUpdateTimeout, s_logger);
s_logger.warn("write heartbeat failed: " + result
+ "; reboot the host");
Script cmd = new Script(_heartBeatPath,
_heartBeatUpdateTimeout, s_logger);
cmd.add("-i", primaryStoragePool._poolIp);
cmd.add("-p", primaryStoragePool._poolMountSourcePath);
cmd.add("-m", primaryStoragePool._mountDestPath);
@ -90,28 +93,29 @@ public class KVMHAMonitor extends KVMHABase implements Runnable{
}
}
}
}
}
}
@Override
public void run() {
//s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new org.apache.log4j.PatternLayout(), "System.out"));
// s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new
// org.apache.log4j.PatternLayout(), "System.out"));
while (true) {
Thread monitorThread = new Thread(new Monitor());
monitorThread.start();
try {
monitorThread.join();
} catch (InterruptedException e) {
}
try {
Thread.sleep(_heartBeatUpdateFreq);
} catch (InterruptedException e) {
}
}
}
}

View File

@ -26,10 +26,9 @@ import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* @author chiradeep
*
*
*/
public class LibvirtCapXMLParser extends LibvirtXMLParser {
private boolean _host = false;
@ -37,14 +36,16 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
private boolean _osType = false;
private boolean _domainTypeKVM = false;
private boolean _emulatorFlag = false;
private final StringBuffer _emulator = new StringBuffer() ;
private final StringBuffer _emulator = new StringBuffer();
private final StringBuffer _capXML = new StringBuffer();
private static final Logger s_logger = Logger.getLogger(LibvirtCapXMLParser.class);
private final ArrayList<String> guestOsTypes = new ArrayList<String>();
private static final Logger s_logger = Logger
.getLogger(LibvirtCapXMLParser.class);
private final ArrayList<String> guestOsTypes = new ArrayList<String>();
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equalsIgnoreCase("host")) {
if (qName.equalsIgnoreCase("host")) {
_host = false;
} else if (qName.equalsIgnoreCase("os_type")) {
_osType = false;
@ -61,7 +62,8 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
public void characters(char[] ch, int start, int length)
throws SAXException {
if (_host) {
_capXML.append(ch, start, length);
} else if (_osType) {
@ -71,11 +73,10 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(qName.equalsIgnoreCase("host")) {
if (qName.equalsIgnoreCase("host")) {
_host = true;
} else if (qName.equalsIgnoreCase("guest")) {
_guest = true;
@ -86,7 +87,7 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
} else if (qName.equalsIgnoreCase("domain")) {
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getQName(i).equalsIgnoreCase("type")
&& attributes.getValue(i).equalsIgnoreCase("kvm")) {
&& attributes.getValue(i).equalsIgnoreCase("kvm")) {
_domainTypeKVM = true;
}
}
@ -95,8 +96,9 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
_emulator.delete(0, _emulator.length());
} else if (_host) {
_capXML.append("<").append(qName);
for (int i=0; i < attributes.getLength(); i++) {
_capXML.append(" ").append(attributes.getQName(i)).append("=").append(attributes.getValue(i));
for (int i = 0; i < attributes.getLength(); i++) {
_capXML.append(" ").append(attributes.getQName(i)).append("=")
.append(attributes.getValue(i));
}
_capXML.append(">");
}
@ -104,13 +106,13 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
}
public String parseCapabilitiesXML(String capXML) {
if (!_initialized){
if (!_initialized) {
return null;
}
try {
_sp.parse(new InputSource(new StringReader(capXML)), this);
return _capXML.toString();
} catch(SAXException se) {
} catch (SAXException se) {
s_logger.warn(se.getMessage());
} catch (IOException ie) {
s_logger.error(ie.getMessage());
@ -126,98 +128,64 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser {
return _emulator.toString();
}
public static void main(String [] args) {
String capXML = "<capabilities>"+
" <host>"+
" <cpu>"+
" <arch>x86_64</arch>"+
" <model>core2duo</model>"+
" <topology sockets='1' cores='2' threads='1'/>"+
" <feature name='lahf_lm'/>"+
" <feature name='xtpr'/>"+
" <feature name='cx16'/>"+
" <feature name='tm2'/>"+
" <feature name='est'/>"+
" <feature name='vmx'/>"+
" <feature name='ds_cpl'/>"+
" <feature name='pbe'/>"+
" <feature name='tm'/>"+
" <feature name='ht'/>"+
" <feature name='ss'/>"+
" <feature name='acpi'/>"+
" <feature name='ds'/>"+
" </cpu>"+
" <migration_features>"+
" <live/>"+
" <uri_transports>"+
" <uri_transport>tcp</uri_transport>"+
" </uri_transports>"+
" </migration_features>"+
" <topology>"+
" <cells num='1'>"+
" <cell id='0'>"+
" <cpus num='2'>"+
" <cpu id='0'/>"+
" <cpu id='1'/>"+
" </cpus>"+
" </cell>"+
" </cells>"+
" </topology>"+
" </host>"+
""+
" <guest>"+
" <os_type>hvm</os_type>"+
" <arch name='i686'>"+
" <wordsize>32</wordsize>"+
" <emulator>/usr/bin/qemu</emulator>"+
" <machine>pc-0.11</machine>"+
" <machine canonical='pc-0.11'>pc</machine>"+
" <machine>pc-0.10</machine>"+
" <machine>isapc</machine>"+
" <domain type='qemu'>"+
" </domain>"+
" <domain type='kvm'>"+
" <emulator>/usr/bin/qemu-kvm</emulator>"+
" <machine>pc-0.11</machine>"+
" <machine canonical='pc-0.11'>pc</machine>"+
" <machine>pc-0.10</machine>"+
" <machine>isapc</machine>"+
" </domain>"+
" </arch>"+
" <features>"+
" <cpuselection/>"+
" <pae/>"+
" <nonpae/>"+
" <acpi default='on' toggle='yes'/>"+
" <apic default='on' toggle='no'/>"+
" </features>"+
" </guest>"+
" <guest>"+
" <os_type>hvm</os_type>"+
" <arch name='x86_64'>"+
" <wordsize>64</wordsize>"+
" <emulator>/usr/bin/qemu-system-x86_64</emulator>"+
" <machine>pc-0.11</machine>"+
" <machine canonical='pc-0.11'>pc</machine>"+
" <machine>pc-0.10</machine>"+
" <machine>isapc</machine>"+
" <domain type='qemu'>"+
" </domain>"+
" <domain type='kvm'>"+
" <emulator>/usr/bin/qemu-kvm</emulator>"+
" <machine>pc-0.11</machine>"+
" <machine canonical='pc-0.11'>pc</machine>"+
" <machine>pc-0.10</machine>"+
" <machine>isapc</machine>"+
" </domain>"+
" </arch>"+
" <features>"+
" <cpuselection/>"+
" <acpi default='on' toggle='yes'/>"+
" <apic default='on' toggle='no'/>"+
" </features>"+
" </guest>"+
"</capabilities>";
public static void main(String[] args) {
String capXML = "<capabilities>" + " <host>" + " <cpu>"
+ " <arch>x86_64</arch>" + " <model>core2duo</model>"
+ " <topology sockets='1' cores='2' threads='1'/>"
+ " <feature name='lahf_lm'/>"
+ " <feature name='xtpr'/>"
+ " <feature name='cx16'/>"
+ " <feature name='tm2'/>" + " <feature name='est'/>"
+ " <feature name='vmx'/>"
+ " <feature name='ds_cpl'/>"
+ " <feature name='pbe'/>" + " <feature name='tm'/>"
+ " <feature name='ht'/>" + " <feature name='ss'/>"
+ " <feature name='acpi'/>" + " <feature name='ds'/>"
+ " </cpu>" + " <migration_features>" + " <live/>"
+ " <uri_transports>"
+ " <uri_transport>tcp</uri_transport>"
+ " </uri_transports>" + " </migration_features>"
+ " <topology>" + " <cells num='1'>"
+ " <cell id='0'>" + " <cpus num='2'>"
+ " <cpu id='0'/>" + " <cpu id='1'/>"
+ " </cpus>" + " </cell>" + " </cells>"
+ " </topology>" + " </host>" + "" + " <guest>"
+ " <os_type>hvm</os_type>" + " <arch name='i686'>"
+ " <wordsize>32</wordsize>"
+ " <emulator>/usr/bin/qemu</emulator>"
+ " <machine>pc-0.11</machine>"
+ " <machine canonical='pc-0.11'>pc</machine>"
+ " <machine>pc-0.10</machine>"
+ " <machine>isapc</machine>"
+ " <domain type='qemu'>" + " </domain>"
+ " <domain type='kvm'>"
+ " <emulator>/usr/bin/qemu-kvm</emulator>"
+ " <machine>pc-0.11</machine>"
+ " <machine canonical='pc-0.11'>pc</machine>"
+ " <machine>pc-0.10</machine>"
+ " <machine>isapc</machine>" + " </domain>"
+ " </arch>" + " <features>" + " <cpuselection/>"
+ " <pae/>" + " <nonpae/>"
+ " <acpi default='on' toggle='yes'/>"
+ " <apic default='on' toggle='no'/>" + " </features>"
+ " </guest>" + " <guest>" + " <os_type>hvm</os_type>"
+ " <arch name='x86_64'>" + " <wordsize>64</wordsize>"
+ " <emulator>/usr/bin/qemu-system-x86_64</emulator>"
+ " <machine>pc-0.11</machine>"
+ " <machine canonical='pc-0.11'>pc</machine>"
+ " <machine>pc-0.10</machine>"
+ " <machine>isapc</machine>"
+ " <domain type='qemu'>" + " </domain>"
+ " <domain type='kvm'>"
+ " <emulator>/usr/bin/qemu-kvm</emulator>"
+ " <machine>pc-0.11</machine>"
+ " <machine canonical='pc-0.11'>pc</machine>"
+ " <machine>pc-0.10</machine>"
+ " <machine>isapc</machine>" + " </domain>"
+ " </arch>" + " <features>" + " <cpuselection/>"
+ " <acpi default='on' toggle='yes'/>"
+ " <apic default='on' toggle='no'/>" + " </features>"
+ " </guest>" + "</capabilities>";
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
String cap = parser.parseCapabilitiesXML(capXML);

View File

@ -22,24 +22,26 @@ import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.LibvirtException;
public class LibvirtConnection {
private static final Logger s_logger = Logger.getLogger(LibvirtConnection.class);
private static final Logger s_logger = Logger
.getLogger(LibvirtConnection.class);
static private Connect _connection;
static private String _hypervisorURI;
static public Connect getConnection() throws LibvirtException {
if (_connection == null) {
_connection = new Connect(_hypervisorURI, false);
} else {
try {
_connection.getVersion();
} catch (LibvirtException e) {
s_logger.debug("Connection with libvirtd is broken, due to " + e.getMessage());
_connection = new Connect(_hypervisorURI, false);
}
}
} else {
try {
_connection.getVersion();
} catch (LibvirtException e) {
s_logger.debug("Connection with libvirtd is broken, due to "
+ e.getMessage());
_connection = new Connect(_hypervisorURI, false);
}
}
return _connection;
return _connection;
}
static void initialize(String hypervisorURI) {

View File

@ -43,124 +43,132 @@ import com.cloud.agent.resource.computing.LibvirtVMDef.InterfaceDef.nicModel;
/**
* @author chiradeep
*
*
*/
public class LibvirtDomainXMLParser {
private static final Logger s_logger = Logger.getLogger(LibvirtDomainXMLParser.class);
private static final Logger s_logger = Logger
.getLogger(LibvirtDomainXMLParser.class);
private final List<InterfaceDef> interfaces = new ArrayList<InterfaceDef>();
private final List<DiskDef> diskDefs = new ArrayList<DiskDef>();
private Integer vncPort;
private String desc;
public boolean parseDomainXML(String domXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(domXML));
Document doc = builder.parse(is);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(domXML));
Document doc = builder.parse(is);
Element rootElement = doc.getDocumentElement();
Element rootElement = doc.getDocumentElement();
desc = getTagValue("description", rootElement);
desc = getTagValue("description", rootElement);
Element devices = (Element)rootElement.getElementsByTagName("devices").item(0);
NodeList disks = devices.getElementsByTagName("disk");
for (int i = 0; i < disks.getLength(); i++) {
Element disk = (Element)disks.item(i);
String diskFmtType = getAttrValue("driver", "type", disk);
String diskFile = getAttrValue("source", "file", disk);
String diskDev = getAttrValue("source", "dev", disk);
Element devices = (Element) rootElement.getElementsByTagName(
"devices").item(0);
NodeList disks = devices.getElementsByTagName("disk");
for (int i = 0; i < disks.getLength(); i++) {
Element disk = (Element) disks.item(i);
String diskFmtType = getAttrValue("driver", "type", disk);
String diskFile = getAttrValue("source", "file", disk);
String diskDev = getAttrValue("source", "dev", disk);
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
String type = disk.getAttribute("type");
String device = disk.getAttribute("device");
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
String type = disk.getAttribute("type");
String device = disk.getAttribute("device");
DiskDef def = new DiskDef();
if (type.equalsIgnoreCase("file")) {
if (device.equalsIgnoreCase("disk")) {
DiskDef.diskFmtType fmt = null;
if (diskFmtType != null) {
fmt = DiskDef.diskFmtType.valueOf(diskFmtType.toUpperCase());
}
def.defFileBasedDisk(diskFile, diskLabel, DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt);
} else if (device.equalsIgnoreCase("cdrom")) {
def.defISODisk(diskFile);
}
} else if (type.equalsIgnoreCase("block")) {
def.defBlockBasedDisk(diskDev, diskLabel, DiskDef.diskBus.valueOf(bus.toUpperCase()));
}
diskDefs.add(def);
}
DiskDef def = new DiskDef();
if (type.equalsIgnoreCase("file")) {
if (device.equalsIgnoreCase("disk")) {
DiskDef.diskFmtType fmt = null;
if (diskFmtType != null) {
fmt = DiskDef.diskFmtType.valueOf(diskFmtType
.toUpperCase());
}
def.defFileBasedDisk(diskFile, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt);
} else if (device.equalsIgnoreCase("cdrom")) {
def.defISODisk(diskFile);
}
} else if (type.equalsIgnoreCase("block")) {
def.defBlockBasedDisk(diskDev, diskLabel,
DiskDef.diskBus.valueOf(bus.toUpperCase()));
}
diskDefs.add(def);
}
NodeList nics = devices.getElementsByTagName("interface");
for (int i = 0; i < nics.getLength(); i++ ) {
Element nic = (Element)nics.item(i);
NodeList nics = devices.getElementsByTagName("interface");
for (int i = 0; i < nics.getLength(); i++) {
Element nic = (Element) nics.item(i);
String type = nic.getAttribute("type");
String mac = getAttrValue("mac", "address", nic);
String dev = getAttrValue("target", "dev", nic);
String model = getAttrValue("model", "type", nic);
InterfaceDef def = new InterfaceDef();
String type = nic.getAttribute("type");
String mac = getAttrValue("mac", "address", nic);
String dev = getAttrValue("target", "dev", nic);
String model = getAttrValue("model", "type", nic);
InterfaceDef def = new InterfaceDef();
if (type.equalsIgnoreCase("network")) {
String network = getAttrValue("source", "network", nic);
def.defPrivateNet(network, dev, mac, nicModel.valueOf(model.toUpperCase()));
} else if (type.equalsIgnoreCase("bridge")) {
String bridge = getAttrValue("source", "bridge", nic);
def.defBridgeNet(bridge, dev, mac, nicModel.valueOf(model.toUpperCase()));
}
interfaces.add(def);
}
if (type.equalsIgnoreCase("network")) {
String network = getAttrValue("source", "network", nic);
def.defPrivateNet(network, dev, mac,
nicModel.valueOf(model.toUpperCase()));
} else if (type.equalsIgnoreCase("bridge")) {
String bridge = getAttrValue("source", "bridge", nic);
def.defBridgeNet(bridge, dev, mac,
nicModel.valueOf(model.toUpperCase()));
}
interfaces.add(def);
}
Element graphic = (Element)devices.getElementsByTagName("graphics").item(0);
String port = graphic.getAttribute("port");
if (port != null) {
try {
vncPort = Integer.parseInt(port);
if (vncPort != -1) {
vncPort = vncPort - 5900;
} else {
vncPort = null;
}
}catch (NumberFormatException nfe){
vncPort = null;
}
}
Element graphic = (Element) devices
.getElementsByTagName("graphics").item(0);
String port = graphic.getAttribute("port");
if (port != null) {
try {
vncPort = Integer.parseInt(port);
if (vncPort != -1) {
vncPort = vncPort - 5900;
} else {
vncPort = null;
}
} catch (NumberFormatException nfe) {
vncPort = null;
}
}
return true;
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return false;
return true;
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return false;
}
private static String getTagValue(String tag, Element eElement){
NodeList tagNodeList = eElement.getElementsByTagName(tag);
if (tagNodeList == null || tagNodeList.getLength() == 0) {
return null;
}
private static String getTagValue(String tag, Element eElement) {
NodeList tagNodeList = eElement.getElementsByTagName(tag);
if (tagNodeList == null || tagNodeList.getLength() == 0) {
return null;
}
NodeList nlList= tagNodeList.item(0).getChildNodes();
NodeList nlList = tagNodeList.item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
return nValue.getNodeValue();
}
private static String getAttrValue(String tag, String attr, Element eElement){
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element)tagNode.item(0);
return node.getAttribute(attr);
private static String getAttrValue(String tag, String attr, Element eElement) {
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element) tagNode.item(0);
return node.getAttribute(attr);
}
public Integer getVncPort() {
@ -179,68 +187,58 @@ public class LibvirtDomainXMLParser {
return desc;
}
public static void main(String [] args){
public static void main(String[] args) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
parser.parseDomainXML("<domain type='kvm' id='12'>"+
"<name>r-6-CV-5002-1</name>"+
"<uuid>581b5a4b-b496-8d4d-e44e-a7dcbe9df0b5</uuid>"+
"<description>testVM</description>"+
"<memory>131072</memory>"+
"<currentMemory>131072</currentMemory>"+
"<vcpu>1</vcpu>"+
"<os>"+
"<type arch='i686' machine='pc-0.11'>hvm</type>"+
"<kernel>/var/lib/libvirt/qemu/vmlinuz-2.6.31.6-166.fc12.i686</kernel>"+
"<cmdline>ro root=/dev/sda1 acpi=force selinux=0 eth0ip=10.1.1.1 eth0mask=255.255.255.0 eth2ip=192.168.10.152 eth2mask=255.255.255.0 gateway=192.168.10.1 dns1=72.52.126.11 dns2=72.52.126.12 domain=v4.myvm.com</cmdline>"+
"<boot dev='hd'/>"+
"</os>"+
"<features>"+
"<acpi/>"+
"<pae/>"+
"</features>"+
"<clock offset='utc'/>"+
"<on_poweroff>destroy</on_poweroff>"+
"<on_reboot>restart</on_reboot>"+
"<on_crash>destroy</on_crash>"+
"<devices>"+
"<emulator>/usr/bin/qemu-kvm</emulator>"+
"<disk type='file' device='disk'>"+
"<driver name='qemu' type='raw'/>"+
"<source file='/mnt/tank//vmops/CV/vm/u000004/r000006/rootdisk'/>"+
"<target dev='hda' bus='ide'/>"+
"</disk>"+
"<interface type='bridge'>"+
"<mac address='02:00:50:02:00:01'/>"+
"<source bridge='vnbr5002'/>"+
"<target dev='vtap5002'/>"+
"<model type='e1000'/>"+
"</interface>"+
"<interface type='network'>"+
"<mac address='00:16:3e:77:e2:a1'/>"+
"<source network='vmops-private'/>"+
"<target dev='vnet3'/>"+
"<model type='e1000'/>"+
"</interface>"+
"<interface type='bridge'>"+
"<mac address='06:85:00:00:00:04'/>"+
"<source bridge='br0'/>"+
"<target dev='tap5002'/>"+
"<model type='e1000'/>"+
"</interface>"+
"<input type='mouse' bus='ps2'/>"+
"<graphics type='vnc' port='6031' autoport='no' listen=''/>"+
"<video>"+
"<model type='cirrus' vram='9216' heads='1'/>"+
"</video>"+
"</devices>"+
"</domain>"
parser.parseDomainXML("<domain type='kvm' id='12'>"
+ "<name>r-6-CV-5002-1</name>"
+ "<uuid>581b5a4b-b496-8d4d-e44e-a7dcbe9df0b5</uuid>"
+ "<description>testVM</description>"
+ "<memory>131072</memory>"
+ "<currentMemory>131072</currentMemory>"
+ "<vcpu>1</vcpu>"
+ "<os>"
+ "<type arch='i686' machine='pc-0.11'>hvm</type>"
+ "<kernel>/var/lib/libvirt/qemu/vmlinuz-2.6.31.6-166.fc12.i686</kernel>"
+ "<cmdline>ro root=/dev/sda1 acpi=force selinux=0 eth0ip=10.1.1.1 eth0mask=255.255.255.0 eth2ip=192.168.10.152 eth2mask=255.255.255.0 gateway=192.168.10.1 dns1=72.52.126.11 dns2=72.52.126.12 domain=v4.myvm.com</cmdline>"
+ "<boot dev='hd'/>"
+ "</os>"
+ "<features>"
+ "<acpi/>"
+ "<pae/>"
+ "</features>"
+ "<clock offset='utc'/>"
+ "<on_poweroff>destroy</on_poweroff>"
+ "<on_reboot>restart</on_reboot>"
+ "<on_crash>destroy</on_crash>"
+ "<devices>"
+ "<emulator>/usr/bin/qemu-kvm</emulator>"
+ "<disk type='file' device='disk'>"
+ "<driver name='qemu' type='raw'/>"
+ "<source file='/mnt/tank//vmops/CV/vm/u000004/r000006/rootdisk'/>"
+ "<target dev='hda' bus='ide'/>" + "</disk>"
+ "<interface type='bridge'>"
+ "<mac address='02:00:50:02:00:01'/>"
+ "<source bridge='vnbr5002'/>" + "<target dev='vtap5002'/>"
+ "<model type='e1000'/>" + "</interface>"
+ "<interface type='network'>"
+ "<mac address='00:16:3e:77:e2:a1'/>"
+ "<source network='vmops-private'/>" + "<target dev='vnet3'/>"
+ "<model type='e1000'/>" + "</interface>"
+ "<interface type='bridge'>"
+ "<mac address='06:85:00:00:00:04'/>"
+ "<source bridge='br0'/>" + "<target dev='tap5002'/>"
+ "<model type='e1000'/>" + "</interface>"
+ "<input type='mouse' bus='ps2'/>"
+ "<graphics type='vnc' port='6031' autoport='no' listen=''/>"
+ "<video>" + "<model type='cirrus' vram='9216' heads='1'/>"
+ "</video>" + "</devices>" + "</domain>"
);
for (InterfaceDef intf: parser.getInterfaces()){
for (InterfaceDef intf : parser.getInterfaces()) {
System.out.println(intf);
}
for (DiskDef disk : parser.getDisks()) {
System.out.println(disk);
System.out.println(disk);
}
System.out.println(parser.getVncPort());
System.out.println(parser.getDescription());
@ -249,7 +247,7 @@ public class LibvirtDomainXMLParser {
test.add("1");
test.add("2");
if (test.contains("1")) {
System.out.print("fdf");
System.out.print("fdf");
}
}

View File

@ -22,10 +22,9 @@ import java.util.List;
public class LibvirtNetworkDef {
enum netType {
BRIDGE,
NAT,
LOCAL
BRIDGE, NAT, LOCAL
}
private final String _networkName;
private final String _uuid;
private netType _networkType;
@ -38,134 +37,156 @@ public class LibvirtNetworkDef {
private String _brNetMask;
private final List<IPRange> ipranges = new ArrayList<IPRange>();
private final List<dhcpMapping> dhcpMaps = new ArrayList<dhcpMapping>();
public static class dhcpMapping {
String _mac;
String _name;
String _ip;
public dhcpMapping(String mac, String name, String ip) {
_mac = mac;
_name = name;
_ip = ip;
}
}
public static class IPRange {
String _start;
String _end;
public IPRange(String start, String end) {
_start = start;
_end = end;
}
}
public LibvirtNetworkDef(String netName, String uuid, String domName) {
_networkName = netName;
_uuid = uuid;
_domainName = domName;
}
public void defNATNetwork(String brName, boolean stp, int delay, String fwNic, String ipAddr, String netMask) {
_networkType = netType.NAT;
_brName = brName;
_stp = stp;
_delay = delay;
_fwDev = fwNic;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void defBrNetwork(String brName, boolean stp, int delay, String fwNic, String ipAddr, String netMask) {
_networkType = netType.BRIDGE;
_brName = brName;
_stp = stp;
_delay = delay;
_fwDev = fwNic;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void defLocalNetwork(String brName, boolean stp, int delay, String ipAddr, String netMask) {
_networkType = netType.LOCAL;
_brName = brName;
_stp = stp;
_delay = delay;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void adddhcpIPRange(String start, String end) {
IPRange ipr = new IPRange(start, end);
ipranges.add(ipr);
}
public void adddhcpMapping(String mac, String host, String ip) {
dhcpMapping map = new dhcpMapping(mac, host, ip);
dhcpMaps.add(map);
}
@Override
public String toString() {
StringBuilder netBuilder = new StringBuilder();
netBuilder.append("<network>\n");
netBuilder.append("<name>" + _networkName + "</name>\n");
if (_uuid != null)
netBuilder.append("<uuid>" + _uuid + "</uuid>\n");
if (_brName != null) {
netBuilder.append("<bridge name='" + _brName + "'");
if (_stp) {
netBuilder.append(" stp='on'");
} else {
netBuilder.append(" stp='off'");
}
if (_delay != -1) {
netBuilder.append(" delay='" + _delay +"'");
}
netBuilder.append("/>\n");
}
if (_domainName != null) {
netBuilder.append("<domain name='" + _domainName + "'/>\n");
}
if (_networkType == netType.BRIDGE) {
netBuilder.append("<forward mode='route'");
if (_fwDev != null) {
netBuilder.append(" dev='" + _fwDev + "'");
}
netBuilder.append("/>\n");
} else if (_networkType == netType.NAT) {
netBuilder.append("<forward mode='nat'");
if (_fwDev != null) {
netBuilder.append(" dev='" + _fwDev + "'");
}
netBuilder.append("/>\n");
}
if (_brIPAddr != null || _brNetMask != null || !ipranges.isEmpty() || !dhcpMaps.isEmpty()) {
netBuilder.append("<ip");
if (_brIPAddr != null)
netBuilder.append(" address='" + _brIPAddr + "'");
if (_brNetMask != null) {
netBuilder.append(" netmask='" + _brNetMask + "'");
}
netBuilder.append(">\n");
public static class dhcpMapping {
String _mac;
String _name;
String _ip;
public dhcpMapping(String mac, String name, String ip) {
_mac = mac;
_name = name;
_ip = ip;
}
}
public static class IPRange {
String _start;
String _end;
public IPRange(String start, String end) {
_start = start;
_end = end;
}
}
public LibvirtNetworkDef(String netName, String uuid, String domName) {
_networkName = netName;
_uuid = uuid;
_domainName = domName;
}
public void defNATNetwork(String brName, boolean stp, int delay,
String fwNic, String ipAddr, String netMask) {
_networkType = netType.NAT;
_brName = brName;
_stp = stp;
_delay = delay;
_fwDev = fwNic;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void defBrNetwork(String brName, boolean stp, int delay,
String fwNic, String ipAddr, String netMask) {
_networkType = netType.BRIDGE;
_brName = brName;
_stp = stp;
_delay = delay;
_fwDev = fwNic;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void defLocalNetwork(String brName, boolean stp, int delay,
String ipAddr, String netMask) {
_networkType = netType.LOCAL;
_brName = brName;
_stp = stp;
_delay = delay;
_brIPAddr = ipAddr;
_brNetMask = netMask;
}
public void adddhcpIPRange(String start, String end) {
IPRange ipr = new IPRange(start, end);
ipranges.add(ipr);
}
public void adddhcpMapping(String mac, String host, String ip) {
dhcpMapping map = new dhcpMapping(mac, host, ip);
dhcpMaps.add(map);
}
@Override
public String toString() {
StringBuilder netBuilder = new StringBuilder();
netBuilder.append("<network>\n");
netBuilder.append("<name>" + _networkName + "</name>\n");
if (_uuid != null)
netBuilder.append("<uuid>" + _uuid + "</uuid>\n");
if (_brName != null) {
netBuilder.append("<bridge name='" + _brName + "'");
if (_stp) {
netBuilder.append(" stp='on'");
} else {
netBuilder.append(" stp='off'");
}
if (_delay != -1) {
netBuilder.append(" delay='" + _delay + "'");
}
netBuilder.append("/>\n");
}
if (_domainName != null) {
netBuilder.append("<domain name='" + _domainName + "'/>\n");
}
if (_networkType == netType.BRIDGE) {
netBuilder.append("<forward mode='route'");
if (_fwDev != null) {
netBuilder.append(" dev='" + _fwDev + "'");
}
netBuilder.append("/>\n");
} else if (_networkType == netType.NAT) {
netBuilder.append("<forward mode='nat'");
if (_fwDev != null) {
netBuilder.append(" dev='" + _fwDev + "'");
}
netBuilder.append("/>\n");
}
if (_brIPAddr != null || _brNetMask != null || !ipranges.isEmpty()
|| !dhcpMaps.isEmpty()) {
netBuilder.append("<ip");
if (_brIPAddr != null)
netBuilder.append(" address='" + _brIPAddr + "'");
if (_brNetMask != null) {
netBuilder.append(" netmask='" + _brNetMask + "'");
}
netBuilder.append(">\n");
if (!ipranges.isEmpty() || !dhcpMaps.isEmpty()) {
netBuilder.append("<dhcp>\n");
for (IPRange ip : ipranges) {
netBuilder.append("<range start='" + ip._start + "'"
+ " end='" + ip._end + "'/>\n");
}
for (dhcpMapping map : dhcpMaps) {
netBuilder.append("<host mac='" + map._mac + "' name='"
+ map._name + "' ip='" + map._ip + "'/>\n");
}
netBuilder.append("</dhcp>\n");
}
netBuilder.append("</ip>\n");
}
netBuilder.append("</network>\n");
return netBuilder.toString();
}
if (!ipranges.isEmpty() || !dhcpMaps.isEmpty()) {
netBuilder.append("<dhcp>\n");
for (IPRange ip : ipranges ) {
netBuilder.append("<range start='" + ip._start + "'" + " end='" + ip._end + "'/>\n");
}
for (dhcpMapping map : dhcpMaps) {
netBuilder.append("<host mac='" + map._mac + "' name='" + map._name + "' ip='" + map._ip + "'/>\n");
}
netBuilder.append("</dhcp>\n");
}
netBuilder.append("</ip>\n");
}
netBuilder.append("</network>\n");
return netBuilder.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
LibvirtNetworkDef net = new LibvirtNetworkDef("cloudPrivate", null, "cloud.com");
net.defNATNetwork("cloudbr0", false, 0, null, "192.168.168.1", "255.255.255.0");
LibvirtNetworkDef net = new LibvirtNetworkDef("cloudPrivate", null,
"cloud.com");
net.defNATNetwork("cloudbr0", false, 0, null, "192.168.168.1",
"255.255.255.0");
net.adddhcpIPRange("192.168.168.100", "192.168.168.220");
net.adddhcpIPRange("192.168.168.10", "192.168.168.50");
net.adddhcpMapping("branch0.cloud.com", "00:16:3e:77:e2:ed", "192.168.168.100");
net.adddhcpMapping("branch1.cloud.com", "00:16:3e:77:e2:ef", "192.168.168.101");
net.adddhcpMapping("branch2.cloud.com", "00:16:3e:77:e2:f0", "192.168.168.102");
net.adddhcpMapping("branch0.cloud.com", "00:16:3e:77:e2:ed",
"192.168.168.100");
net.adddhcpMapping("branch1.cloud.com", "00:16:3e:77:e2:ef",
"192.168.168.101");
net.adddhcpMapping("branch2.cloud.com", "00:16:3e:77:e2:f0",
"192.168.168.102");
System.out.println(net.toString());
}

View File

@ -20,19 +20,19 @@ package com.cloud.agent.resource.computing;
public class LibvirtStoragePoolDef {
public enum poolType {
ISCSI("iscsi"),
NETFS("netfs"),
LOGICAL("logical"),
DIR("dir");
ISCSI("iscsi"), NETFS("netfs"), LOGICAL("logical"), DIR("dir");
String _poolType;
poolType(String poolType) {
_poolType = poolType;
}
@Override
public String toString() {
return _poolType;
}
}
private poolType _poolType;
private String _poolName;
private String _uuid;
@ -40,7 +40,8 @@ public class LibvirtStoragePoolDef {
private String _sourceDir;
private String _targetPath;
public LibvirtStoragePoolDef(poolType type, String poolName, String uuid, String host, String dir, String targetPath) {
public LibvirtStoragePoolDef(poolType type, String poolName, String uuid,
String host, String dir, String targetPath) {
_poolType = type;
_poolName = poolName;
_uuid = uuid;
@ -50,26 +51,26 @@ public class LibvirtStoragePoolDef {
}
public String getPoolName() {
return _poolName;
return _poolName;
}
public poolType getPoolType() {
return _poolType;
return _poolType;
}
public String getSourceHost() {
return _sourceHost;
return _sourceHost;
}
public String getSourceDir() {
return _sourceDir;
return _sourceDir;
}
public String getTargetPath() {
return _targetPath;
return _targetPath;
}
@Override
@Override
public String toString() {
StringBuilder storagePoolBuilder = new StringBuilder();
storagePoolBuilder.append("<pool type='" + _poolType + "'>\n");

View File

@ -30,86 +30,82 @@ import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class LibvirtStoragePoolXMLParser {
private static final Logger s_logger = Logger
.getLogger(LibvirtStoragePoolXMLParser.class);
public LibvirtStoragePoolDef parseStoragePoolXML(String poolXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
public class LibvirtStoragePoolXMLParser{
private static final Logger s_logger = Logger.getLogger(LibvirtStoragePoolXMLParser.class);
public LibvirtStoragePoolDef parseStoragePoolXML(String poolXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(poolXML));
Document doc = builder.parse(is);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(poolXML));
Document doc = builder.parse(is);
Element rootElement = doc.getDocumentElement();
String type = rootElement.getAttribute("type");
Element rootElement = doc.getDocumentElement();
String type = rootElement.getAttribute("type");
String uuid = getTagValue("uuid", rootElement);
String uuid = getTagValue("uuid", rootElement);
String poolName = getTagValue("name", rootElement);
String poolName = getTagValue("name", rootElement);
Element source = (Element) rootElement.getElementsByTagName(
"source").item(0);
String host = getAttrValue("host", "name", source);
String path = getAttrValue("dir", "path", source);
Element source = (Element)rootElement.getElementsByTagName("source").item(0);
String host = getAttrValue("host", "name", source);
String path = getAttrValue("dir", "path", source);
Element target = (Element) rootElement.getElementsByTagName(
"target").item(0);
String targetPath = getTagValue("path", target);
Element target = (Element)rootElement.getElementsByTagName("target").item(0);
String targetPath = getTagValue("path", target);
return new LibvirtStoragePoolDef(
LibvirtStoragePoolDef.poolType.valueOf(type.toUpperCase()),
poolName, uuid, host, path, targetPath);
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return null;
}
return new LibvirtStoragePoolDef(LibvirtStoragePoolDef.poolType.valueOf(type.toUpperCase()), poolName, uuid, host, path, targetPath);
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return null;
}
private static String getTagValue(String tag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(tag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
private static String getTagValue(String tag, Element eElement){
NodeList nlList= eElement.getElementsByTagName(tag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
return nValue.getNodeValue();
}
private static String getAttrValue(String tag, String attr, Element eElement) {
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element) tagNode.item(0);
return node.getAttribute(attr);
}
private static String getAttrValue(String tag, String attr, Element eElement){
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element)tagNode.item(0);
return node.getAttribute(attr);
}
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(
new org.apache.log4j.PatternLayout(), "System.out"));
String storagePool = "<pool type='dir'>" + "<name>test</name>"
+ "<uuid>bf723c83-4b95-259c-7089-60776e61a11f</uuid>"
+ "<capacity>20314165248</capacity>"
+ "<allocation>1955450880</allocation>"
+ "<available>18358714368</available>" + "<source>"
+ "<host name='nfs1.lab.vmops.com'/>"
+ "<dir path='/export/home/edison/kvm/primary'/>"
+ "<format type='auto'/>" + "</source>" + "<target>"
+ "<path>/media</path>" + "<permissions>" + "<mode>0700</mode>"
+ "<owner>0</owner>" + "<group>0</group>" + "</permissions>"
+ "</target>" + "</pool>";
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new org.apache.log4j.PatternLayout(), "System.out"));
String storagePool = "<pool type='dir'>" +
"<name>test</name>" +
"<uuid>bf723c83-4b95-259c-7089-60776e61a11f</uuid>" +
"<capacity>20314165248</capacity>" +
"<allocation>1955450880</allocation>" +
"<available>18358714368</available>" +
"<source>" +
"<host name='nfs1.lab.vmops.com'/>" +
"<dir path='/export/home/edison/kvm/primary'/>" +
"<format type='auto'/>" +
"</source>" +
"<target>" +
"<path>/media</path>" +
"<permissions>" +
"<mode>0700</mode>" +
"<owner>0</owner>" +
"<group>0</group>" +
"</permissions>" +
"</target>" +
"</pool>";
LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser();
LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool);
s_logger.debug(pool.toString());
}
LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser();
LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool);
s_logger.debug(pool.toString());
}
}

View File

@ -20,13 +20,13 @@ package com.cloud.agent.resource.computing;
public class LibvirtStorageVolumeDef {
public enum volFormat {
RAW("raw"),
QCOW2("qcow2"),
DIR("dir");
RAW("raw"), QCOW2("qcow2"), DIR("dir");
private String _format;
volFormat(String format) {
_format = format;
}
@Override
public String toString() {
return _format;
@ -44,13 +44,15 @@ public class LibvirtStorageVolumeDef {
return null;
}
}
private String _volName;
private Long _volSize;
private volFormat _volFormat;
private String _backingPath;
private volFormat _backingFormat;
public LibvirtStorageVolumeDef(String volName, Long size, volFormat format, String tmplPath, volFormat tmplFormat) {
public LibvirtStorageVolumeDef(String volName, Long size, volFormat format,
String tmplPath, volFormat tmplFormat) {
_volName = volName;
_volSize = size;
_volFormat = format;
@ -61,13 +63,15 @@ public class LibvirtStorageVolumeDef {
public volFormat getFormat() {
return this._volFormat;
}
@Override
public String toString() {
StringBuilder storageVolBuilder = new StringBuilder();
storageVolBuilder.append("<volume>\n");
storageVolBuilder.append("<name>" + _volName + "</name>\n");
if (_volSize != null) {
storageVolBuilder.append("<capacity >" + _volSize + "</capacity>\n");
storageVolBuilder
.append("<capacity >" + _volSize + "</capacity>\n");
}
storageVolBuilder.append("<target>\n");
storageVolBuilder.append("<format type='" + _volFormat + "'/>\n");
@ -78,7 +82,8 @@ public class LibvirtStorageVolumeDef {
if (_backingPath != null) {
storageVolBuilder.append("<backingStore>\n");
storageVolBuilder.append("<path>" + _backingPath + "</path>\n");
storageVolBuilder.append("<format type='" + _backingFormat + "'/>\n");
storageVolBuilder.append("<format type='" + _backingFormat
+ "'/>\n");
storageVolBuilder.append("</backingStore>\n");
}
storageVolBuilder.append("</volume>\n");

View File

@ -15,76 +15,74 @@ import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class LibvirtStorageVolumeXMLParser{
private static final Logger s_logger = Logger.getLogger(LibvirtStorageVolumeXMLParser.class);
public LibvirtStorageVolumeDef parseStorageVolumeXML(String volXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
public class LibvirtStorageVolumeXMLParser {
private static final Logger s_logger = Logger
.getLogger(LibvirtStorageVolumeXMLParser.class);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(volXML));
Document doc = builder.parse(is);
public LibvirtStorageVolumeDef parseStorageVolumeXML(String volXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Element rootElement = doc.getDocumentElement();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(volXML));
Document doc = builder.parse(is);
String VolName = getTagValue("name", rootElement);
Element target = (Element)rootElement.getElementsByTagName("target").item(0);
String format = getAttrValue("type", "format", target);
Long capacity = Long.parseLong(getTagValue("capacity", rootElement));
return new LibvirtStorageVolumeDef(VolName, capacity, LibvirtStorageVolumeDef.volFormat.getFormat(format), null, null);
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return null;
}
Element rootElement = doc.getDocumentElement();
private static String getTagValue(String tag, Element eElement){
NodeList nlList= eElement.getElementsByTagName(tag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String VolName = getTagValue("name", rootElement);
Element target = (Element) rootElement.getElementsByTagName(
"target").item(0);
String format = getAttrValue("type", "format", target);
Long capacity = Long
.parseLong(getTagValue("capacity", rootElement));
return new LibvirtStorageVolumeDef(VolName, capacity,
LibvirtStorageVolumeDef.volFormat.getFormat(format), null,
null);
} catch (ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (SAXException e) {
s_logger.debug(e.toString());
} catch (IOException e) {
s_logger.debug(e.toString());
}
return null;
}
return nValue.getNodeValue();
}
private static String getTagValue(String tag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(tag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
private static String getAttrValue(String tag, String attr, Element eElement){
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element)tagNode.item(0);
return node.getAttribute(attr);
}
return nValue.getNodeValue();
}
private static String getAttrValue(String tag, String attr, Element eElement) {
NodeList tagNode = eElement.getElementsByTagName(tag);
if (tagNode.getLength() == 0) {
return null;
}
Element node = (Element) tagNode.item(0);
return node.getAttribute(attr);
}
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new org.apache.log4j.PatternLayout(), "System.out"));
String storagePool = "<pool type='dir'>" +
"<name>test</name>" +
"<uuid>bf723c83-4b95-259c-7089-60776e61a11f</uuid>" +
"<capacity>20314165248</capacity>" +
"<allocation>1955450880</allocation>" +
"<available>18358714368</available>" +
"<source>" +
"<host name='nfs1.lab.vmops.com'/>" +
"<dir path='/export/home/edison/kvm/primary'/>" +
"<format type='auto'/>" +
"</source>" +
"<target>" +
"<path>/media</path>" +
"<permissions>" +
"<mode>0700</mode>" +
"<owner>0</owner>" +
"<group>0</group>" +
"</permissions>" +
"</target>" +
"</pool>";
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(
new org.apache.log4j.PatternLayout(), "System.out"));
String storagePool = "<pool type='dir'>" + "<name>test</name>"
+ "<uuid>bf723c83-4b95-259c-7089-60776e61a11f</uuid>"
+ "<capacity>20314165248</capacity>"
+ "<allocation>1955450880</allocation>"
+ "<available>18358714368</available>" + "<source>"
+ "<host name='nfs1.lab.vmops.com'/>"
+ "<dir path='/export/home/edison/kvm/primary'/>"
+ "<format type='auto'/>" + "</source>" + "<target>"
+ "<path>/media</path>" + "<permissions>" + "<mode>0700</mode>"
+ "<owner>0</owner>" + "<group>0</group>" + "</permissions>"
+ "</target>" + "</pool>";
LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser();
LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool);
s_logger.debug(pool.toString());
}
LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser();
LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool);
s_logger.debug(pool.toString());
}
}

View File

@ -30,28 +30,27 @@ public class LibvirtVMDef {
private String _domName;
private String _domUUID;
private String _desc;
private final Map<String, Object> components = new HashMap<String,Object>();
private final Map<String, Object> components = new HashMap<String, Object>();
public static class GuestDef {
enum guestType {
KVM,
XEN,
EXE
KVM, XEN, EXE
}
enum bootOrder {
HARDISK("hd"),
CDROM("cdrom"),
FLOOPY("fd"),
NETWORK("network");
HARDISK("hd"), CDROM("cdrom"), FLOOPY("fd"), NETWORK("network");
String _order;
bootOrder(String order) {
_order = order;
}
@Override
public String toString() {
public String toString() {
return _order;
}
}
private guestType _type;
private String _arch;
private String _loader;
@ -61,29 +60,37 @@ public class LibvirtVMDef {
private String _cmdline;
private List<bootOrder> _bootdevs = new ArrayList<bootOrder>();
private String _machine;
public void setGuestType (guestType type) {
public void setGuestType(guestType type) {
_type = type;
}
public void setGuestArch (String arch) {
public void setGuestArch(String arch) {
_arch = arch;
}
public void setMachineType (String machine) {
public void setMachineType(String machine) {
_machine = machine;
}
public void setLoader (String loader) {
public void setLoader(String loader) {
_loader = loader;
}
public void setBootKernel(String kernel, String initrd, String rootdev, String cmdline) {
public void setBootKernel(String kernel, String initrd, String rootdev,
String cmdline) {
_kernel = kernel;
_initrd = initrd;
_root = rootdev;
_cmdline = cmdline;
}
public void setBootOrder(bootOrder order) {
_bootdevs.add(order);
}
@Override
public String toString () {
public String toString() {
if (_type == guestType.KVM) {
StringBuilder guestDef = new StringBuilder();
guestDef.append("<os>\n");
@ -112,27 +119,34 @@ public class LibvirtVMDef {
private int _currentMem = -1;
private String _memBacking;
private int _vcpu = -1;
public void setMemorySize(long mem) {
_mem = mem;
}
public void setCurrentMem(int currMem) {
_currentMem = currMem;
}
public void setMemBacking(String memBacking) {
_memBacking = memBacking;
}
public void setVcpuNum(int vcpu) {
_vcpu = vcpu;
}
@Override
public String toString(){
public String toString() {
StringBuilder resBuidler = new StringBuilder();
resBuidler.append("<memory>" + _mem + "</memory>\n");
if (_currentMem != -1) {
resBuidler.append("<currentMemory>" + _currentMem + "</currentMemory>\n");
resBuidler.append("<currentMemory>" + _currentMem
+ "</currentMemory>\n");
}
if (_memBacking != null) {
resBuidler.append("<memoryBacking>" + "<" + _memBacking + "/>" + "</memoryBacking>\n");
resBuidler.append("<memoryBacking>" + "<" + _memBacking + "/>"
+ "</memoryBacking>\n");
}
if (_vcpu != -1) {
resBuidler.append("<vcpu>" + _vcpu + "</vcpu>\n");
@ -143,11 +157,13 @@ public class LibvirtVMDef {
public static class FeaturesDef {
private final List<String> _features = new ArrayList<String>();
public void addFeatures(String feature) {
_features.add(feature);
}
@Override
public String toString() {
public String toString() {
StringBuilder feaBuilder = new StringBuilder();
feaBuilder.append("<features>\n");
for (String feature : _features) {
@ -157,24 +173,30 @@ public class LibvirtVMDef {
return feaBuilder.toString();
}
}
public static class TermPolicy {
private String _reboot;
private String _powerOff;
private String _crash;
public TermPolicy() {
_reboot = _powerOff = _crash = "destroy";
}
public void setRebootPolicy(String rbPolicy) {
_reboot = rbPolicy;
}
public void setPowerOffPolicy(String poPolicy) {
_powerOff = poPolicy;
}
public void setCrashPolicy(String crashPolicy) {
_crash = crashPolicy;
}
@Override
public String toString() {
public String toString() {
StringBuilder term = new StringBuilder();
term.append("<on_reboot>" + _reboot + "</on_reboot>\n");
term.append("<on_poweroff>" + _powerOff + "</on_poweroff>\n");
@ -185,20 +207,21 @@ public class LibvirtVMDef {
public static class ClockDef {
public enum ClockOffset {
UTC("utc"),
LOCALTIME("localtime"),
TIMEZONE("timezone"),
VARIABLE("variable");
UTC("utc"), LOCALTIME("localtime"), TIMEZONE("timezone"), VARIABLE(
"variable");
private String _offset;
private ClockOffset(String offset) {
_offset = offset;
}
@Override
public String toString() {
return _offset;
}
}
private ClockOffset _offset;
private String _timerName;
private String _tickPolicy;
@ -252,6 +275,7 @@ public class LibvirtVMDef {
public static class DevicesDef {
private String _emulator;
private final Map<String, List<?>> devices = new HashMap<String, List<?>>();
public boolean addDevice(Object device) {
Object dev = devices.get(device.getClass().toString());
if (dev == null) {
@ -259,20 +283,23 @@ public class LibvirtVMDef {
devs.add(device);
devices.put(device.getClass().toString(), devs);
} else {
List<Object> devs = (List<Object>)dev;
List<Object> devs = (List<Object>) dev;
devs.add(device);
}
return true;
}
public void setEmulatorPath(String emulator) {
_emulator = emulator;
}
@Override
public String toString() {
public String toString() {
StringBuilder devicesBuilder = new StringBuilder();
devicesBuilder.append("<devices>\n");
if (_emulator != null) {
devicesBuilder.append("<emulator>" + _emulator + "</emulator>\n");
devicesBuilder.append("<emulator>" + _emulator
+ "</emulator>\n");
}
for (List<?> devs : devices.values()) {
@ -283,84 +310,92 @@ public class LibvirtVMDef {
devicesBuilder.append("</devices>\n");
return devicesBuilder.toString();
}
public List<DiskDef> getDisks() {
return (List<DiskDef>)devices.get(DiskDef.class.toString());
return (List<DiskDef>) devices.get(DiskDef.class.toString());
}
public List<InterfaceDef> getInterfaces() {
return (List<InterfaceDef>)devices.get(InterfaceDef.class.toString());
return (List<InterfaceDef>) devices.get(InterfaceDef.class
.toString());
}
}
public static class DiskDef {
enum deviceType {
FLOOPY("floopy"),
DISK("disk"),
CDROM("cdrom");
FLOOPY("floopy"), DISK("disk"), CDROM("cdrom");
String _type;
deviceType(String type) {
_type = type;
}
@Override
public String toString() {
public String toString() {
return _type;
}
}
enum diskType {
FILE("file"),
BLOCK("block"),
DIRECTROY("dir");
FILE("file"), BLOCK("block"), DIRECTROY("dir");
String _diskType;
diskType(String type) {
_diskType = type;
}
@Override
public String toString() {
public String toString() {
return _diskType;
}
}
enum diskBus {
IDE("ide"),
SCSI("scsi"),
VIRTIO("virtio"),
XEN("xen"),
USB("usb"),
UML("uml"),
FDC("fdc");
IDE("ide"), SCSI("scsi"), VIRTIO("virtio"), XEN("xen"), USB("usb"), UML(
"uml"), FDC("fdc");
String _bus;
diskBus(String bus) {
_bus = bus;
}
@Override
public String toString() {
public String toString() {
return _bus;
}
}
enum diskFmtType {
RAW("raw"),
QCOW2("qcow2");
RAW("raw"), QCOW2("qcow2");
String _fmtType;
diskFmtType(String fmt) {
_fmtType = fmt;
}
@Override
public String toString() {
public String toString() {
return _fmtType;
}
}
private deviceType _deviceType; /*floppy, disk, cdrom*/
private deviceType _deviceType; /* floppy, disk, cdrom */
private diskType _diskType;
private String _sourcePath;
private String _diskLabel;
private diskBus _bus;
private diskFmtType _diskFmtType; /*qcow2, raw etc.*/
private diskFmtType _diskFmtType; /* qcow2, raw etc. */
private boolean _readonly = false;
private boolean _shareable = false;
private boolean _deferAttach = false;
public void setDeviceType(deviceType deviceType) {
_deviceType = deviceType;
}
public void defFileBasedDisk(String filePath, String diskLabel, diskBus bus, diskFmtType diskFmtType) {
public void defFileBasedDisk(String filePath, String diskLabel,
diskBus bus, diskFmtType diskFmtType) {
_diskType = diskType.FILE;
_deviceType = deviceType.DISK;
_sourcePath = filePath;
@ -369,13 +404,14 @@ public class LibvirtVMDef {
_bus = bus;
}
/*skip iso label*/
/* skip iso label */
private String getDevLabel(int devId, diskBus bus) {
if ( devId == 2 ) {
if (devId == 2) {
devId++;
}
char suffix = (char)('a' + devId);
char suffix = (char) ('a' + devId);
if (bus == diskBus.SCSI) {
return "sd" + suffix;
} else if (bus == diskBus.VIRTIO) {
@ -385,7 +421,8 @@ public class LibvirtVMDef {
}
public void defFileBasedDisk(String filePath, int devId, diskBus bus, diskFmtType diskFmtType) {
public void defFileBasedDisk(String filePath, int devId, diskBus bus,
diskFmtType diskFmtType) {
_diskType = diskType.FILE;
_deviceType = deviceType.DISK;
@ -395,6 +432,7 @@ public class LibvirtVMDef {
_bus = bus;
}
public void defISODisk(String volPath) {
_diskType = diskType.FILE;
_deviceType = deviceType.CDROM;
@ -403,6 +441,7 @@ public class LibvirtVMDef {
_diskFmtType = diskFmtType.RAW;
_bus = diskBus.IDE;
}
public void defBlockBasedDisk(String diskName, int devId, diskBus bus) {
_diskType = diskType.BLOCK;
_deviceType = deviceType.DISK;
@ -411,7 +450,9 @@ public class LibvirtVMDef {
_diskLabel = getDevLabel(devId, bus);
_bus = bus;
}
public void defBlockBasedDisk(String diskName, String diskLabel, diskBus bus) {
public void defBlockBasedDisk(String diskName, String diskLabel,
diskBus bus) {
_diskType = diskType.BLOCK;
_deviceType = deviceType.DISK;
_diskFmtType = diskFmtType.RAW;
@ -419,39 +460,50 @@ public class LibvirtVMDef {
_diskLabel = diskLabel;
_bus = bus;
}
public void setReadonly() {
_readonly = true;
}
public void setSharable() {
_shareable = true;
}
public void setAttachDeferred(boolean deferAttach) {
_deferAttach = deferAttach;
}
public boolean isAttachDeferred() {
return _deferAttach;
}
public String getDiskPath() {
return _sourcePath;
}
public String getDiskLabel() {
return _diskLabel;
}
public deviceType getDeviceType() {
return _deviceType;
}
public void setDiskPath(String volPath) {
this._sourcePath = volPath;
}
public diskBus getBusType() {
return _bus;
}
public int getDiskSeq() {
char suffix = this._diskLabel.charAt(this._diskLabel.length() - 1);
return suffix - 'a';
}
@Override
public String toString() {
public String toString() {
StringBuilder diskBuilder = new StringBuilder();
diskBuilder.append("<disk ");
if (_deviceType != null) {
@ -459,7 +511,8 @@ public class LibvirtVMDef {
}
diskBuilder.append(" type='" + _diskType + "'");
diskBuilder.append(">\n");
diskBuilder.append("<driver name='qemu'" + " type='" + _diskFmtType + "' cache='none' " +"/>\n");
diskBuilder.append("<driver name='qemu'" + " type='" + _diskFmtType
+ "' cache='none' " + "/>\n");
if (_diskType == diskType.FILE) {
diskBuilder.append("<source ");
if (_sourcePath != null) {
@ -487,56 +540,62 @@ public class LibvirtVMDef {
public static class InterfaceDef {
enum guestNetType {
BRIDGE("bridge"),
NETWORK("network"),
USER("user"),
ETHERNET("ethernet"),
INTERNAL("internal");
BRIDGE("bridge"), NETWORK("network"), USER("user"), ETHERNET(
"ethernet"), INTERNAL("internal");
String _type;
guestNetType(String type) {
_type = type;
}
@Override
public String toString() {
public String toString() {
return _type;
}
}
enum nicModel {
E1000("e1000"),
VIRTIO("virtio"),
RTL8139("rtl8139"),
NE2KPCI("ne2k_pci");
E1000("e1000"), VIRTIO("virtio"), RTL8139("rtl8139"), NE2KPCI(
"ne2k_pci");
String _model;
nicModel(String model) {
_model = model;
}
@Override
public String toString() {
public String toString() {
return _model;
}
}
enum hostNicType {
DIRECT_ATTACHED_WITHOUT_DHCP,
DIRECT_ATTACHED_WITH_DHCP,
VNET,
VLAN;
DIRECT_ATTACHED_WITHOUT_DHCP, DIRECT_ATTACHED_WITH_DHCP, VNET, VLAN;
}
private guestNetType _netType; /*bridge, ethernet, network, user, internal*/
private hostNicType _hostNetType; /*Only used by agent java code*/
private guestNetType _netType; /*
* bridge, ethernet, network, user,
* internal
*/
private hostNicType _hostNetType; /* Only used by agent java code */
private String _sourceName;
private String _networkName;
private String _macAddr;
private String _ipAddr;
private String _scriptPath;
private nicModel _model;
public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) {
public void defBridgeNet(String brName, String targetBrName,
String macAddr, nicModel model) {
_netType = guestNetType.BRIDGE;
_sourceName = brName;
_networkName = targetBrName;
_macAddr = macAddr;
_model = model;
}
public void defPrivateNet(String networkName, String targetName, String macAddr, nicModel model) {
public void defPrivateNet(String networkName, String targetName,
String macAddr, nicModel model) {
_netType = guestNetType.NETWORK;
_sourceName = networkName;
_networkName = targetName;
@ -555,51 +614,57 @@ public class LibvirtVMDef {
public String getBrName() {
return _sourceName;
}
public guestNetType getNetType() {
return _netType;
}
public String getDevName() {
return _networkName;
return _networkName;
}
public String getMacAddress() {
return _macAddr;
return _macAddr;
}
@Override
public String toString() {
public String toString() {
StringBuilder netBuilder = new StringBuilder();
netBuilder.append("<interface type='" + _netType +"'>\n");
netBuilder.append("<interface type='" + _netType + "'>\n");
if (_netType == guestNetType.BRIDGE) {
netBuilder.append("<source bridge='" + _sourceName +"'/>\n");
netBuilder.append("<source bridge='" + _sourceName + "'/>\n");
} else if (_netType == guestNetType.NETWORK) {
netBuilder.append("<source network='" + _sourceName +"'/>\n");
netBuilder.append("<source network='" + _sourceName + "'/>\n");
}
if (_networkName !=null) {
if (_networkName != null) {
netBuilder.append("<target dev='" + _networkName + "'/>\n");
}
if (_macAddr !=null) {
if (_macAddr != null) {
netBuilder.append("<mac address='" + _macAddr + "'/>\n");
}
if (_model !=null) {
if (_model != null) {
netBuilder.append("<model type='" + _model + "'/>\n");
}
netBuilder.append("</interface>\n");
return netBuilder.toString();
}
}
public static class ConsoleDef {
private final String _ttyPath;
private final String _type;
private final String _source;
private short _port = -1;
public ConsoleDef(String type, String path, String source, short port) {
_type = type;
_ttyPath = path;
_source = source;
_port = port;
}
@Override
public String toString() {
public String toString() {
StringBuilder consoleBuilder = new StringBuilder();
consoleBuilder.append("<console ");
consoleBuilder.append("type='" + _type + "'");
@ -617,17 +682,20 @@ public class LibvirtVMDef {
return consoleBuilder.toString();
}
}
public static class SerialDef {
private final String _type;
private final String _source;
private short _port = -1;
public SerialDef(String type, String source, short port) {
_type = type;
_source = source;
_port = port;
}
@Override
public String toString() {
public String toString() {
StringBuilder serialBuidler = new StringBuilder();
serialBuidler.append("<serial type='" + _type + "'>\n");
if (_source != null) {
@ -640,14 +708,17 @@ public class LibvirtVMDef {
return serialBuidler.toString();
}
}
public static class GraphicDef {
public static class GraphicDef {
private final String _type;
private short _port = -2;
private boolean _autoPort = false;
private final String _listenAddr;
private final String _passwd;
private final String _keyMap;
public GraphicDef(String type, short port, boolean auotPort, String listenAddr, String passwd, String keyMap) {
public GraphicDef(String type, short port, boolean auotPort,
String listenAddr, String passwd, String keyMap) {
_type = type;
_port = port;
_autoPort = auotPort;
@ -655,13 +726,14 @@ public class LibvirtVMDef {
_passwd = passwd;
_keyMap = keyMap;
}
@Override
public String toString() {
public String toString() {
StringBuilder graphicBuilder = new StringBuilder();
graphicBuilder.append("<graphics type='" + _type + "'");
if (_autoPort) {
graphicBuilder.append(" autoport='yes'");
} else if (_port != -2){
} else if (_port != -2) {
graphicBuilder.append(" port='" + _port + "'");
}
if (_listenAddr != null) {
@ -678,15 +750,18 @@ public class LibvirtVMDef {
return graphicBuilder.toString();
}
}
public static class InputDef {
private final String _type; /*tablet, mouse*/
private final String _bus; /*ps2, usb, xen*/
public static class InputDef {
private final String _type; /* tablet, mouse */
private final String _bus; /* ps2, usb, xen */
public InputDef(String type, String bus) {
_type = type;
_bus = bus;
}
@Override
public String toString() {
public String toString() {
StringBuilder inputBuilder = new StringBuilder();
inputBuilder.append("<input type='" + _type + "'");
if (_bus != null) {
@ -696,40 +771,48 @@ public class LibvirtVMDef {
return inputBuilder.toString();
}
}
public void setHvsType(String hvs) {
_hvsType = hvs;
}
public void setDomainName(String domainName) {
_domName = domainName;
}
public void setDomUUID(String uuid) {
_domUUID = uuid;
}
public void setDomDescription(String desc) {
_desc = desc;
}
public String getGuestOSType() {
return _desc;
}
public void addComp(Object comp) {
components.put(comp.getClass().toString(), comp);
}
public DevicesDef getDevices() {
Object o = components.get(DevicesDef.class.toString());
if (o != null) {
return (DevicesDef)o;
return (DevicesDef) o;
}
return null;
}
@Override
public String toString() {
public String toString() {
StringBuilder vmBuilder = new StringBuilder();
vmBuilder.append("<domain type='" + _hvsType + "'>\n");
vmBuilder.append("<name>" + _domName + "</name>\n");
if (_domUUID != null) {
vmBuilder.append("<uuid>" + _domUUID + "</uuid>\n");
}
if (_desc != null ) {
if (_desc != null) {
vmBuilder.append("<description>" + _desc + "</description>\n");
}
for (Object o : components.values()) {
@ -739,7 +822,7 @@ public class LibvirtVMDef {
return vmBuilder.toString();
}
public static void main(String [] args){
public static void main(String[] args) {
System.out.println("testing");
LibvirtVMDef vm = new LibvirtVMDef();
vm.setHvsType("kvm");
@ -754,7 +837,7 @@ public class LibvirtVMDef {
vm.addComp(guest);
GuestResourceDef grd = new GuestResourceDef();
grd.setMemorySize(512*1024);
grd.setMemorySize(512 * 1024);
grd.setVcpuNum(1);
vm.addComp(grd);
@ -774,32 +857,38 @@ public class LibvirtVMDef {
devices.setEmulatorPath("/usr/bin/cloud-qemu-system-x86_64");
DiskDef hda = new DiskDef();
hda.defFileBasedDisk("/path/to/hda1", 0, DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
hda.defFileBasedDisk("/path/to/hda1", 0, DiskDef.diskBus.VIRTIO,
DiskDef.diskFmtType.QCOW2);
devices.addDevice(hda);
DiskDef hdb = new DiskDef();
hdb.defFileBasedDisk("/path/to/hda2", 1, DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
hdb.defFileBasedDisk("/path/to/hda2", 1, DiskDef.diskBus.VIRTIO,
DiskDef.diskFmtType.QCOW2);
devices.addDevice(hdb);
InterfaceDef pubNic = new InterfaceDef();
pubNic.defBridgeNet("cloudbr0", "vnet1", "00:16:3e:77:e2:a1", InterfaceDef.nicModel.VIRTIO);
pubNic.defBridgeNet("cloudbr0", "vnet1", "00:16:3e:77:e2:a1",
InterfaceDef.nicModel.VIRTIO);
devices.addDevice(pubNic);
InterfaceDef privNic = new InterfaceDef();
privNic.defPrivateNet("cloud-private", null, "00:16:3e:77:e2:a2", InterfaceDef.nicModel.VIRTIO);
privNic.defPrivateNet("cloud-private", null, "00:16:3e:77:e2:a2",
InterfaceDef.nicModel.VIRTIO);
devices.addDevice(privNic);
InterfaceDef vlanNic = new InterfaceDef();
vlanNic.defBridgeNet("vnbr1000", "tap1", "00:16:3e:77:e2:a2", InterfaceDef.nicModel.VIRTIO);
vlanNic.defBridgeNet("vnbr1000", "tap1", "00:16:3e:77:e2:a2",
InterfaceDef.nicModel.VIRTIO);
devices.addDevice(vlanNic);
SerialDef serial = new SerialDef("pty", null, (short)0);
SerialDef serial = new SerialDef("pty", null, (short) 0);
devices.addDevice(serial);
ConsoleDef console = new ConsoleDef("pty", null, null, (short)0);
ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
devices.addDevice(console);
GraphicDef grap = new GraphicDef("vnc", (short)0, true, null, null, null);
GraphicDef grap = new GraphicDef("vnc", (short) 0, true, null, null,
null);
devices.addDevice(grap);
InputDef input = new InputDef("tablet", "usb");

View File

@ -29,57 +29,46 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class LibvirtXMLParser extends DefaultHandler{
private static final Logger s_logger = Logger.getLogger(LibvirtXMLParser.class);
protected static SAXParserFactory s_spf;
public class LibvirtXMLParser extends DefaultHandler {
private static final Logger s_logger = Logger
.getLogger(LibvirtXMLParser.class);
protected static SAXParserFactory s_spf;
static {
s_spf = SAXParserFactory.newInstance();
static {
s_spf = SAXParserFactory.newInstance();
}
protected SAXParser _sp;
protected boolean _initialized = false;
}
protected SAXParser _sp;
protected boolean _initialized = false;
public LibvirtXMLParser() {
public LibvirtXMLParser(){
try {
try {
_sp = s_spf.newSAXParser();
_initialized = true;
} catch(Exception ex) {
} catch (Exception ex) {
}
}
public boolean parseDomainXML(String domXML) {
if (!_initialized){
public boolean parseDomainXML(String domXML) {
if (!_initialized) {
return false;
}
try {
_sp.parse(new InputSource(new StringReader(domXML)), this);
return true;
}catch(SAXException se) {
} catch (SAXException se) {
s_logger.warn(se.getMessage());
}catch (IOException ie) {
} catch (IOException ie) {
s_logger.error(ie.getMessage());
}
return false;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
public void characters(char[] ch, int start, int length)
throws SAXException {
}
}