use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef in project cloudstack by apache.
the class LibvirtSecurityGroupRulesCommandWrapper method execute.
@Override
public Answer execute(final SecurityGroupRulesCmd command, final LibvirtComputingResource libvirtComputingResource) {
String vif = null;
String brname = null;
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());
vif = nics.get(0).getDevName();
brname = nics.get(0).getBrName();
} catch (final LibvirtException e) {
return new SecurityGroupRuleAnswer(command, false, e.toString());
}
final boolean result = libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getGuestIp6(), command.getSignature(), Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString());
if (!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.debug("Programmed network rules for vm " + command.getVmName() + " guestIp=" + command.getGuestIp() + ",ingress numrules=" + command.getIngressRuleSet().size() + ",egress numrules=" + command.getEgressRuleSet().size());
return new SecurityGroupRuleAnswer(command);
}
}
use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef in project cloudstack by apache.
the class LibvirtDomainXMLParser method parseDomainXML.
public boolean parseDomainXML(String domXML) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(domXML));
Document doc = builder.parse(is);
Element rootElement = doc.getDocumentElement();
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 type = disk.getAttribute("type");
DiskDef def = new DiskDef();
if (type.equalsIgnoreCase("network")) {
String diskFmtType = getAttrValue("driver", "type", disk);
String diskCacheMode = getAttrValue("driver", "cache", disk);
String diskPath = getAttrValue("source", "name", disk);
String protocol = getAttrValue("source", "protocol", disk);
String authUserName = getAttrValue("auth", "username", disk);
String poolUuid = getAttrValue("secret", "uuid", disk);
String host = getAttrValue("host", "name", disk);
int port = Integer.parseInt(getAttrValue("host", "port", disk));
String diskLabel = getAttrValue("target", "dev", disk);
String bus = getAttrValue("target", "bus", disk);
DiskDef.DiskFmtType fmt = null;
if (diskFmtType != null) {
fmt = DiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase());
}
def.defNetworkBasedDisk(diskPath, host, port, authUserName, poolUuid, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase()), DiskDef.DiskProtocol.valueOf(protocol.toUpperCase()), fmt);
def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
} else {
String diskFmtType = getAttrValue("driver", "type", disk);
String diskCacheMode = getAttrValue("driver", "cache", 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 device = disk.getAttribute("device");
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()));
}
if (diskCacheMode != null) {
def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
}
}
NodeList iotune = disk.getElementsByTagName("iotune");
if ((iotune != null) && (iotune.getLength() != 0)) {
String bytesReadRateStr = getTagValue("read_bytes_sec", (Element) iotune.item(0));
if (bytesReadRateStr != null) {
Long bytesReadRate = Long.parseLong(bytesReadRateStr);
def.setBytesReadRate(bytesReadRate);
}
String bytesWriteRateStr = getTagValue("write_bytes_sec", (Element) iotune.item(0));
if (bytesWriteRateStr != null) {
Long bytesWriteRate = Long.parseLong(bytesWriteRateStr);
def.setBytesWriteRate(bytesWriteRate);
}
String iopsReadRateStr = getTagValue("read_iops_sec", (Element) iotune.item(0));
if (iopsReadRateStr != null) {
Long iopsReadRate = Long.parseLong(iopsReadRateStr);
def.setIopsReadRate(iopsReadRate);
}
String iopsWriteRateStr = getTagValue("write_iops_sec", (Element) iotune.item(0));
if (iopsWriteRateStr != null) {
Long iopsWriteRate = Long.parseLong(iopsWriteRateStr);
def.setIopsWriteRate(iopsWriteRate);
}
}
diskDefs.add(def);
}
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();
NodeList bandwidth = nic.getElementsByTagName("bandwidth");
Integer networkRateKBps = 0;
if ((bandwidth != null) && (bandwidth.getLength() != 0)) {
Integer inbound = Integer.valueOf(getAttrValue("inbound", "average", (Element) bandwidth.item(0)));
Integer outbound = Integer.valueOf(getAttrValue("outbound", "average", (Element) bandwidth.item(0)));
if (inbound.equals(outbound)) {
networkRateKBps = inbound;
}
}
if (type.equalsIgnoreCase("network")) {
String network = getAttrValue("source", "network", nic);
def.defPrivateNet(network, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
} else if (type.equalsIgnoreCase("bridge")) {
String bridge = getAttrValue("source", "bridge", nic);
def.defBridgeNet(bridge, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
} else if (type.equalsIgnoreCase("ethernet")) {
String scriptPath = getAttrValue("script", "path", nic);
def.defEthernet(dev, mac, NicModel.valueOf(model.toUpperCase()), scriptPath, networkRateKBps);
}
interfaces.add(def);
}
NodeList ports = devices.getElementsByTagName("channel");
for (int i = 0; i < ports.getLength(); i++) {
Element channel = (Element) ports.item(i);
String type = channel.getAttribute("type");
String path = getAttrValue("source", "path", channel);
String name = getAttrValue("target", "name", channel);
String state = getAttrValue("target", "state", channel);
ChannelDef def = null;
if (!StringUtils.isNotBlank(state)) {
def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()), new File(path));
} else {
def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()), ChannelDef.ChannelState.valueOf(state.toUpperCase()), new File(path));
}
channels.add(def);
}
Element graphic = (Element) devices.getElementsByTagName("graphics").item(0);
if (graphic != null) {
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;
}
}
}
NodeList rngs = devices.getElementsByTagName("rng");
for (int i = 0; i < rngs.getLength(); i++) {
RngDef def = null;
Element rng = (Element) rngs.item(i);
String backendModel = getAttrValue("backend", "model", rng);
String path = getTagValue("backend", rng);
String bytes = getAttrValue("rate", "bytes", rng);
String period = getAttrValue("rate", "period", rng);
if (Strings.isNullOrEmpty(backendModel)) {
def = new RngDef(path, Integer.parseInt(bytes), Integer.parseInt(period));
} else {
def = new RngDef(path, RngBackendModel.valueOf(backendModel.toUpperCase()), Integer.parseInt(bytes), Integer.parseInt(period));
}
rngDefs.add(def);
}
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;
}
use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef in project cloudstack by apache.
the class LibvirtComputingResource method prepareNetworkElementCommand.
protected ExecutionResult prepareNetworkElementCommand(final SetSourceNatCommand cmd) {
Connect conn;
final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
final IpAddressTO pubIP = cmd.getIpAddress();
try {
conn = LibvirtConnection.getConnectionByVmName(routerName);
Integer devNum = 0;
final String pubVlan = pubIP.getBroadcastUri();
final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName);
for (final InterfaceDef pluggedNic : pluggedNics) {
final String pluggedVlanBr = pluggedNic.getBrName();
final String pluggedVlanId = getBroadcastUriFromBridge(pluggedVlanBr);
if (pubVlan.equalsIgnoreCase(Vlan.UNTAGGED) && pluggedVlanBr.equalsIgnoreCase(_publicBridgeName)) {
break;
} else if (pluggedVlanBr.equalsIgnoreCase(_linkLocalBridgeName)) {
/*skip over, no physical bridge device exists*/
} else if (pluggedVlanId == null) {
/*this should only be true in the case of link local bridge*/
return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan + " on router " + routerName);
} else if (pluggedVlanId.equals(pubVlan)) {
break;
}
devNum++;
}
pubIP.setNicDevId(devNum);
return new ExecutionResult(true, "success");
} catch (final LibvirtException e) {
final String msg = "Ip SNAT failure due to " + e.toString();
s_logger.error(msg, e);
return new ExecutionResult(false, msg);
}
}
use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef in project cloudstack by apache.
the class LibvirtComputingResource method getVmStat.
public VmStatsEntry getVmStat(final Connect conn, final String vmName) throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
if (dm == null) {
return null;
}
DomainInfo info = dm.getInfo();
final VmStatsEntry stats = new VmStatsEntry();
stats.setNumCPUs(info.nrVirtCpu);
stats.setEntityType("vm");
stats.setMemoryKBs(info.maxMem);
stats.setTargetMemoryKBs(info.memory);
stats.setIntFreeMemoryKBs(getMemoryFreeInKBs(dm));
/* get cpu utilization */
VmStats oldStats = null;
final Calendar now = Calendar.getInstance();
oldStats = _vmStats.get(vmName);
long elapsedTime = 0;
if (oldStats != null) {
elapsedTime = now.getTimeInMillis() - oldStats._timestamp.getTimeInMillis();
double utilization = (info.cpuTime - oldStats._usedTime) / ((double) elapsedTime * 1000000);
final NodeInfo node = conn.nodeInfo();
utilization = utilization / node.cpus;
if (utilization > 0) {
stats.setCPUUtilization(utilization * 100);
}
}
/* get network stats */
final List<InterfaceDef> vifs = getInterfaces(conn, vmName);
long rx = 0;
long tx = 0;
for (final InterfaceDef vif : vifs) {
final DomainInterfaceStats ifStats = dm.interfaceStats(vif.getDevName());
rx += ifStats.rx_bytes;
tx += ifStats.tx_bytes;
}
if (oldStats != null) {
final double deltarx = rx - oldStats._rx;
if (deltarx > 0) {
stats.setNetworkReadKBs(deltarx / 1024);
}
final double deltatx = tx - oldStats._tx;
if (deltatx > 0) {
stats.setNetworkWriteKBs(deltatx / 1024);
}
}
/* get disk stats */
final List<DiskDef> disks = getDisks(conn, vmName);
long io_rd = 0;
long io_wr = 0;
long bytes_rd = 0;
long bytes_wr = 0;
for (final DiskDef disk : disks) {
final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel());
io_rd += blockStats.rd_req;
io_wr += blockStats.wr_req;
bytes_rd += blockStats.rd_bytes;
bytes_wr += blockStats.wr_bytes;
}
if (oldStats != null) {
final long deltaiord = io_rd - oldStats._ioRead;
if (deltaiord > 0) {
stats.setDiskReadIOs(deltaiord);
}
final long deltaiowr = io_wr - oldStats._ioWrote;
if (deltaiowr > 0) {
stats.setDiskWriteIOs(deltaiowr);
}
final double deltabytesrd = bytes_rd - oldStats._bytesRead;
if (deltabytesrd > 0) {
stats.setDiskReadKBs(deltabytesrd / 1024);
}
final double deltabyteswr = bytes_wr - oldStats._bytesWrote;
if (deltabyteswr > 0) {
stats.setDiskWriteKBs(deltabyteswr / 1024);
}
}
/* save to Hashmap */
final VmStats newStat = new VmStats();
newStat._usedTime = info.cpuTime;
newStat._rx = rx;
newStat._tx = tx;
newStat._ioRead = io_rd;
newStat._ioWrote = io_wr;
newStat._bytesRead = bytes_rd;
newStat._bytesWrote = bytes_wr;
newStat._timestamp = now;
_vmStats.put(vmName, newStat);
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}
use of com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef in project cloudstack by apache.
the class LibvirtComputingResource method prepareNetworkElementCommand.
public ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) {
final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
Connect conn;
try {
conn = LibvirtConnection.getConnectionByVmName(routerName);
final List<InterfaceDef> nics = getInterfaces(conn, routerName);
final Map<String, Integer> broadcastUriAllocatedToVM = new HashMap<String, Integer>();
Integer nicPos = 0;
for (final InterfaceDef nic : nics) {
if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) {
broadcastUriAllocatedToVM.put("LinkLocal", nicPos);
} else {
if (nic.getBrName().equalsIgnoreCase(_publicBridgeName) || nic.getBrName().equalsIgnoreCase(_privBridgeName) || nic.getBrName().equalsIgnoreCase(_guestBridgeName)) {
broadcastUriAllocatedToVM.put(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED).toString(), nicPos);
} else {
final String broadcastUri = getBroadcastUriFromBridge(nic.getBrName());
broadcastUriAllocatedToVM.put(broadcastUri, nicPos);
}
}
nicPos++;
}
final IpAddressTO[] ips = cmd.getIpAddresses();
int nicNum = 0;
for (final IpAddressTO ip : ips) {
boolean newNic = false;
if (!broadcastUriAllocatedToVM.containsKey(ip.getBroadcastUri())) {
/* plug a vif into router */
VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress());
broadcastUriAllocatedToVM.put(ip.getBroadcastUri(), nicPos++);
newNic = true;
}
nicNum = broadcastUriAllocatedToVM.get(ip.getBroadcastUri());
networkUsage(routerIp, "addVif", "eth" + nicNum);
ip.setNicDevId(nicNum);
ip.setNewNic(newNic);
}
return new ExecutionResult(true, null);
} catch (final LibvirtException e) {
s_logger.error("ipassoccmd failed", e);
return new ExecutionResult(false, e.getMessage());
} catch (final InternalErrorException e) {
s_logger.error("ipassoccmd failed", e);
return new ExecutionResult(false, e.getMessage());
}
}
Aggregations