incubator-cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From alena1...@apache.org
Subject [3/43] Merge branch 'master' into vpc
Date Wed, 08 Aug 2012 18:55:23 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/048c5e50/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 7bff023,359497e..1f831f9
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@@ -2661,1462 -2659,1452 +2661,1452 @@@ public class LibvirtComputingResource e
                                                                   pool.getAuthUserName(), pool.getUuid(),
                                                                   devId, diskBusType, diskProtocol.RBD);
                                  } else if (volume.getType() == Volume.Type.DATADISK) {
 -                                        disk.defFileBasedDisk(physicalDisk.getPath(), devId,
 -                                                        DiskDef.diskBus.VIRTIO,
 -                                                        DiskDef.diskFmtType.QCOW2);
 -                } else {
 -                    disk.defFileBasedDisk(physicalDisk.getPath(), devId,
 -                            diskBusType, DiskDef.diskFmtType.QCOW2);
 -                }
 -
 -            }
 -
 -            vm.getDevices().addDevice(disk);
 -        }
 -
 -        if (vmSpec.getType() != VirtualMachine.Type.User) {
 -            if (_sysvmISOPath != null) {
 -                DiskDef iso = new DiskDef();
 -                iso.defISODisk(_sysvmISOPath);
 -                vm.getDevices().addDevice(iso);
 -            }
 -
 -            createPatchVbd(conn, vmName, vm, vmSpec);
 -        }
 -    }
 -
 -    private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) {
 -        VolumeTO volumes[] = vmSpec.getDisks();
 -        for (VolumeTO volume : volumes) {
 -            if (volume.getType() == type) {
 -                return volume;
 -            }
 -        }
 -        return null;
 -    }
 -
 -    private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm,
 -            VirtualMachineTO vmSpec) throws LibvirtException,
 -            InternalErrorException {
 -
 -        List<DiskDef> disks = vm.getDevices().getDisks();
 -        DiskDef rootDisk = disks.get(0);
 -        VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT);
 -        KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol
 -                .getPoolUuid());
 -        KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID()
 -                .toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW,
 -                10L * 1024 * 1024);
 -        /* Format/create fs on this disk */
 -        final Script command = new Script(_createvmPath, _timeout, s_logger);
 -        command.add("-f", disk.getPath());
 -        String result = command.execute();
 -        if (result != null) {
 -            s_logger.debug("Failed to create data disk: " + result);
 -            throw new InternalErrorException("Failed to create data disk: "
 -                    + result);
 -        }
 -        String datadiskPath = disk.getPath();
 -
 -        /* add patch disk */
 -        DiskDef patchDisk = new DiskDef();
 -
 -        patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(),
 -                DiskDef.diskFmtType.RAW);
 -        
 -        disks.add(patchDisk);
 -
 -        String bootArgs = vmSpec.getBootArgs();
 -
 -        patchSystemVm(bootArgs, datadiskPath, vmName);
 -    }
 -
 -    private String createVlanBr(String vlanId, String nic)
 -            throws InternalErrorException {
 -        String brName = setVnetBrName(vlanId);
 -        createVnet(vlanId, nic);
 -        return brName;
 -    }
 +					disk.defFileBasedDisk(physicalDisk.getPath(), devId,
 +							DiskDef.diskBus.VIRTIO,
 +							DiskDef.diskFmtType.QCOW2);
 +				} else {
 +					disk.defFileBasedDisk(physicalDisk.getPath(), devId,
 +							diskBusType, DiskDef.diskFmtType.QCOW2);
 +				}
 +
 +			}
 +
 +			vm.getDevices().addDevice(disk);
 +		}
 +
 +		if (vmSpec.getType() != VirtualMachine.Type.User) {
 +			if (_sysvmISOPath != null) {
 +				DiskDef iso = new DiskDef();
 +				iso.defISODisk(_sysvmISOPath);
 +				vm.getDevices().addDevice(iso);
 +			}
 +
 +			createPatchVbd(conn, vmName, vm, vmSpec);
 +		}
 +	}
 +
 +	private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) {
 +		VolumeTO volumes[] = vmSpec.getDisks();
 +		for (VolumeTO volume : volumes) {
 +			if (volume.getType() == type) {
 +				return volume;
 +			}
 +		}
 +		return null;
 +	}
 +
 +	private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm,
 +			VirtualMachineTO vmSpec) throws LibvirtException,
 +			InternalErrorException {
 +
 +		List<DiskDef> disks = vm.getDevices().getDisks();
 +		DiskDef rootDisk = disks.get(0);
 +		VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT);
 +		KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol
 +				.getPoolUuid());
 +		KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID()
 +				.toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW,
 +				10L * 1024 * 1024);
 +		/* Format/create fs on this disk */
 +		final Script command = new Script(_createvmPath, _timeout, s_logger);
 +		command.add("-f", disk.getPath());
 +		String result = command.execute();
 +		if (result != null) {
 +			s_logger.debug("Failed to create data disk: " + result);
 +			throw new InternalErrorException("Failed to create data disk: "
 +					+ result);
 +		}
 +		String datadiskPath = disk.getPath();
 +
 +		/* add patch disk */
 +		DiskDef patchDisk = new DiskDef();
 +
 +		patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(),
 +				DiskDef.diskFmtType.RAW);
 +		
 +		disks.add(patchDisk);
 +
 +		String bootArgs = vmSpec.getBootArgs();
 +
 +		patchSystemVm(bootArgs, datadiskPath, vmName);
 +	}
 +
 +	private String createVlanBr(String vlanId, String nic)
 +			throws InternalErrorException {
 +		String brName = setVnetBrName(vlanId);
 +		createVnet(vlanId, nic);
 +		return brName;
 +	}
  
      private InterfaceDef createVif(NicTO nic,
 -                                   InterfaceDef.nicModel model) throws InternalErrorException,
 -            LibvirtException {
 -        InterfaceDef intf = new InterfaceDef();
 -
 -        String vlanId = null;
 -        if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
 -            URI broadcastUri = nic.getBroadcastUri();
 -            vlanId = broadcastUri.getHost();
 -        }
 -
 -        if (nic.getType() == TrafficType.Guest) {
 -            if (nic.getBroadcastType() == BroadcastDomainType.Vlan
 -                    && !vlanId.equalsIgnoreCase("untagged")) {
 -                String brName = createVlanBr(vlanId, _pifs.first());
 -                intf.defBridgeNet(brName, null, nic.getMac(), model);
 -            } else {
 -                intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model);
 -            }
 -        } else if (nic.getType() == TrafficType.Control) {
 -            /* Make sure the network is still there */
 +			InterfaceDef.nicModel model) throws InternalErrorException,
 +			LibvirtException {
 +		InterfaceDef intf = new InterfaceDef();
 +
 +		String vlanId = null;
 +		if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
 +			URI broadcastUri = nic.getBroadcastUri();
 +			vlanId = broadcastUri.getHost();
 +		}
 +
 +		if (nic.getType() == TrafficType.Guest) {
 +			if (nic.getBroadcastType() == BroadcastDomainType.Vlan
 +					&& !vlanId.equalsIgnoreCase("untagged")) {
 +				String brName = createVlanBr(vlanId, _pifs.first());
 +				intf.defBridgeNet(brName, null, nic.getMac(), model);
 +			} else {
 +				intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model);
 +			}
 +		} else if (nic.getType() == TrafficType.Control) {
 +			/* Make sure the network is still there */
              createControlNetwork();
 -            intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model);
 -        } else if (nic.getType() == TrafficType.Public) {
 -            if (nic.getBroadcastType() == BroadcastDomainType.Vlan
 -                    && !vlanId.equalsIgnoreCase("untagged")) {
 -                String brName = createVlanBr(vlanId, _pifs.second());
 -                intf.defBridgeNet(brName, null, nic.getMac(), model);
 -            } else {
 -                intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model);
 -            }
 -        } else if (nic.getType() == TrafficType.Management) {
 -            intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model);
 -        } else if (nic.getType() == TrafficType.Storage) {
 -            String storageBrName = nic.getName() == null ? _privBridgeName
 -                    : nic.getName();
 -            intf.defBridgeNet(storageBrName, null, nic.getMac(), model);
 -        }
 -
 -        return intf;
 -    }
 +			intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model);
 +		} else if (nic.getType() == TrafficType.Public) {
 +			if (nic.getBroadcastType() == BroadcastDomainType.Vlan
 +					&& !vlanId.equalsIgnoreCase("untagged")) {
 +				String brName = createVlanBr(vlanId, _pifs.second());
 +				intf.defBridgeNet(brName, null, nic.getMac(), model);
 +			} else {
 +				intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model);
 +			}
 +		} else if (nic.getType() == TrafficType.Management) {
 +			intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model);
 +		} else if (nic.getType() == TrafficType.Storage) {
 +			String storageBrName = nic.getName() == null ? _privBridgeName
 +					: nic.getName();
 +			intf.defBridgeNet(storageBrName, null, nic.getMac(), model);
 +		}
 +
 +		return intf;
 +	}
  
      private void createVif(LibvirtVMDef vm, NicTO nic)
 -            throws InternalErrorException, LibvirtException {
 -        vm.getDevices().addDevice(
 +			throws InternalErrorException, LibvirtException {
 +		vm.getDevices().addDevice(
                  createVif(nic, getGuestNicModel(vm.getGuestOSType())));
 -    }
 -
 -    protected CheckSshAnswer execute(CheckSshCommand cmd) {
 -        String vmName = cmd.getName();
 -        String privateIp = cmd.getIp();
 -        int cmdPort = cmd.getPort();
 -
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
 -        }
 -
 -        try {
 -            String result = _virtRouterResource.connect(privateIp, cmdPort);
 -            if (result != null) {
 -                return new CheckSshAnswer(cmd, "Can not ping System vm "
 -                        + vmName + "due to:" + result);
 -            }
 -        } catch (Exception e) {
 -            return new CheckSshAnswer(cmd, e);
 -        }
 -
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Ping command port succeeded for vm " + vmName);
 -        }
 -
 -        return new CheckSshAnswer(cmd);
 -    }
 -
 -    private boolean cleanupDisk(Connect conn, DiskDef disk) {
 -        // need to umount secondary storage
 -        String path = disk.getDiskPath();
 -        String poolUuid = null;
 -        if (path != null) {
 -            String[] token = path.split("/");
 -            if (token.length > 3) {
 -                poolUuid = token[2];
 -            }
 -        }
 -
 -        if (poolUuid == null) {
 -            return true;
 -        }
 -
 -        try {
 -            KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid);
 -            if (pool != null) {
 -                pool.delete();
 -            }
 -            return true;
 -        } catch (CloudRuntimeException e) {
 -            return false;
 -        }
 -    }
 -
 -    protected synchronized String attachOrDetachISO(Connect conn,
 -            String vmName, String isoPath, boolean isAttach)
 -            throws LibvirtException, URISyntaxException, InternalErrorException {
 -        String isoXml = null;
 -        if (isoPath != null && isAttach) {
 -            int index = isoPath.lastIndexOf("/");
 -            String path = isoPath.substring(0, index);
 -            String name = isoPath.substring(index + 1);
 -            KVMStoragePool secondaryPool = _storagePoolMgr
 -                    .getStoragePoolByURI(path);
 -            KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
 -            isoPath = isoVol.getPath();
 -
 -            DiskDef iso = new DiskDef();
 -            iso.defISODisk(isoPath);
 -            isoXml = iso.toString();
 -        } else {
 -            DiskDef iso = new DiskDef();
 -            iso.defISODisk(null);
 -            isoXml = iso.toString();
 -        }
 -
 -        List<DiskDef> disks = getDisks(conn, vmName);
 -        String result = attachOrDetachDevice(conn, true, vmName, isoXml);
 -        if (result == null && !isAttach) {
 -            for (DiskDef disk : disks) {
 -                if (disk.getDeviceType() == DiskDef.deviceType.CDROM) {
 -                    cleanupDisk(conn, disk);
 -                }
 -            }
 -
 -        }
 -        return result;
 -    }
 -
 -    protected synchronized String attachOrDetachDisk(Connect conn,
 -            boolean attach, String vmName, KVMPhysicalDisk attachingDisk,
 -            int devId) throws LibvirtException, InternalErrorException {
 -        List<DiskDef> disks = null;
 -        Domain dm = null;
 -        DiskDef diskdef = null;
 -        try {
 -            if (!attach) {
 -                dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                        .getBytes()));
 -                LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 -                String xml = dm.getXMLDesc(0);
 -                parser.parseDomainXML(xml);
 -                disks = parser.getDisks();
 -
 -                for (DiskDef disk : disks) {
 -                    String file = disk.getDiskPath();
 -                    if (file != null
 -                            && file.equalsIgnoreCase(attachingDisk.getPath())) {
 -                        diskdef = disk;
 -                        break;
 -                    }
 -                }
 -                if (diskdef == null) {
 -                    throw new InternalErrorException("disk: "
 -                            + attachingDisk.getPath()
 -                            + " is not attached before");
 -                }
 -            } else {
 -                diskdef = new DiskDef();
 -                if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
 -                    diskdef.defFileBasedDisk(attachingDisk.getPath(), devId,
 -                            DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
 -                } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
 -                    diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId,
 -                            DiskDef.diskBus.VIRTIO);
 -                }
 -            }
 -
 -            String xml = diskdef.toString();
 -            return attachOrDetachDevice(conn, attach, vmName, xml);
 -        } finally {
 -            if (dm != null) {
 -                dm.free();
 -            }
 -        }
 -    }
 -
 -    protected synchronized String attachOrDetachDevice(Connect conn,
 -            boolean attach, String vmName, String xml) throws LibvirtException,
 -            InternalErrorException {
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName
 -                    .getBytes())));
 -
 -            if (attach) {
 -                s_logger.debug("Attaching device: " + xml);
 -                dm.attachDevice(xml);
 -            } else {
 -                s_logger.debug("Detaching device: " + xml);
 -                dm.detachDevice(xml);
 -            }
 -        } catch (LibvirtException e) {
 -            if (attach) {
 -                s_logger.warn("Failed to attach device to " + vmName + ": "
 -                        + e.getMessage());
 -            } else {
 -                s_logger.warn("Failed to detach device from " + vmName + ": "
 -                        + e.getMessage());
 -            }
 -            throw e;
 -        } catch (Exception e) {
 -            throw new InternalErrorException(e.toString());
 -        } finally {
 -            if (dm != null) {
 -                try {
 -                    dm.free();
 -                } catch (LibvirtException l) {
 -
 -                }
 -            }
 -        }
 -
 -        return null;
 -    }
 -
 -    @Override
 -    public PingCommand getCurrentStatus(long id) {
 -        final HashMap<String, State> newStates = sync();
 -
 -        if (!_can_bridge_firewall) {
 -            return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id,
 -                    newStates);
 -        } else {
 -            HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id);
 -            return new PingRoutingWithNwGroupsCommand(getType(), id, newStates,
 -                    nwGrpStates);
 -        }
 -    }
 -
 -    @Override
 -    public Type getType() {
 -        return Type.Routing;
 -    }
 -
 -    private Map<String, String> getVersionStrings() {
 -        final Script command = new Script(_versionstringpath, _timeout,
 -                s_logger);
 -        KeyValueInterpreter kvi = new KeyValueInterpreter();
 -        String result = command.execute(kvi);
 -        if (result == null) {
 -            return kvi.getKeyValues();
 -        } else {
 -            return new HashMap<String, String>(1);
 -        }
 -    }
 -
 -    @Override
 -    public StartupCommand[] initialize() {
 -        Map<String, State> changes = null;
 -
 -        synchronized (_vms) {
 -            _vms.clear();
 -            changes = sync();
 -        }
 -
 -        final List<Object> info = getHostInfo();
 -
 -        final StartupRoutingCommand cmd = new StartupRoutingCommand(
 -                (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2),
 -                (Long) info.get(4), (String) info.get(3), HypervisorType.KVM,
 -                RouterPrivateIpStrategy.HostLocal);
 -        cmd.setStateChanges(changes);
 -        fillNetworkInformation(cmd);
 -        _privateIp = cmd.getPrivateIpAddress();
 -        cmd.getHostDetails().putAll(getVersionStrings());
 -        cmd.setPool(_pool);
 -        cmd.setCluster(_clusterId);
 -        cmd.setGatewayIpAddress(_localGateway);
 -
 -        StartupStorageCommand sscmd = null;
 -        try {
 -
 -            KVMStoragePool localStoragePool = _storagePoolMgr
 +	}
 +
 +	protected CheckSshAnswer execute(CheckSshCommand cmd) {
 +		String vmName = cmd.getName();
 +		String privateIp = cmd.getIp();
 +		int cmdPort = cmd.getPort();
 +
 +		if (s_logger.isDebugEnabled()) {
 +			s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
 +		}
 +
 +		try {
 +			String result = _virtRouterResource.connect(privateIp, cmdPort);
 +			if (result != null) {
 +				return new CheckSshAnswer(cmd, "Can not ping System vm "
 +						+ vmName + "due to:" + result);
 +			}
 +		} catch (Exception e) {
 +			return new CheckSshAnswer(cmd, e);
 +		}
 +
 +		if (s_logger.isDebugEnabled()) {
 +			s_logger.debug("Ping command port succeeded for vm " + vmName);
 +		}
 +
 +		return new CheckSshAnswer(cmd);
 +	}
 +
 +	private boolean cleanupDisk(Connect conn, DiskDef disk) {
 +		// need to umount secondary storage
 +		String path = disk.getDiskPath();
 +		String poolUuid = null;
 +		if (path != null) {
 +			String[] token = path.split("/");
 +			if (token.length > 3) {
 +				poolUuid = token[2];
 +			}
 +		}
 +
 +		if (poolUuid == null) {
 +			return true;
 +		}
 +
 +		try {
 +			KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid);
 +			if (pool != null) {
 +				pool.delete();
 +			}
 +			return true;
 +		} catch (CloudRuntimeException e) {
 +			return false;
 +		}
 +	}
 +
 +	protected synchronized String attachOrDetachISO(Connect conn,
 +			String vmName, String isoPath, boolean isAttach)
 +			throws LibvirtException, URISyntaxException, InternalErrorException {
 +		String isoXml = null;
 +		if (isoPath != null && isAttach) {
 +			int index = isoPath.lastIndexOf("/");
 +			String path = isoPath.substring(0, index);
 +			String name = isoPath.substring(index + 1);
 +			KVMStoragePool secondaryPool = _storagePoolMgr
 +					.getStoragePoolByURI(path);
 +			KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
 +			isoPath = isoVol.getPath();
 +
 +			DiskDef iso = new DiskDef();
 +			iso.defISODisk(isoPath);
 +			isoXml = iso.toString();
 +		} else {
 +			DiskDef iso = new DiskDef();
 +			iso.defISODisk(null);
 +			isoXml = iso.toString();
 +		}
 +
 +		List<DiskDef> disks = getDisks(conn, vmName);
 +		String result = attachOrDetachDevice(conn, true, vmName, isoXml);
 +		if (result == null && !isAttach) {
 +			for (DiskDef disk : disks) {
 +				if (disk.getDeviceType() == DiskDef.deviceType.CDROM) {
 +					cleanupDisk(conn, disk);
 +				}
 +			}
 +
 +		}
 +		return result;
 +	}
 +
 +	protected synchronized String attachOrDetachDisk(Connect conn,
 +			boolean attach, String vmName, KVMPhysicalDisk attachingDisk,
 +			int devId) throws LibvirtException, InternalErrorException {
 +		List<DiskDef> disks = null;
 +		Domain dm = null;
 +		DiskDef diskdef = null;
 +		try {
 +			if (!attach) {
 +				dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +						.getBytes()));
 +				LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 +				String xml = dm.getXMLDesc(0);
 +				parser.parseDomainXML(xml);
 +				disks = parser.getDisks();
 +
 +				for (DiskDef disk : disks) {
 +					String file = disk.getDiskPath();
 +					if (file != null
 +							&& file.equalsIgnoreCase(attachingDisk.getPath())) {
 +						diskdef = disk;
 +						break;
 +					}
 +				}
 +				if (diskdef == null) {
 +					throw new InternalErrorException("disk: "
 +							+ attachingDisk.getPath()
 +							+ " is not attached before");
 +				}
 +			} else {
 +				diskdef = new DiskDef();
 +				if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
 +					diskdef.defFileBasedDisk(attachingDisk.getPath(), devId,
 +							DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
 +				} else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
 +					diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId,
 +							DiskDef.diskBus.VIRTIO);
 +				}
 +			}
 +
 +			String xml = diskdef.toString();
 +			return attachOrDetachDevice(conn, attach, vmName, xml);
 +		} finally {
 +			if (dm != null) {
 +				dm.free();
 +			}
 +		}
 +	}
 +
 +	protected synchronized String attachOrDetachDevice(Connect conn,
 +			boolean attach, String vmName, String xml) throws LibvirtException,
 +			InternalErrorException {
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName
 +					.getBytes())));
 +
 +			if (attach) {
 +				s_logger.debug("Attaching device: " + xml);
 +				dm.attachDevice(xml);
 +			} else {
 +				s_logger.debug("Detaching device: " + xml);
 +				dm.detachDevice(xml);
 +			}
 +		} catch (LibvirtException e) {
 +			if (attach) {
 +				s_logger.warn("Failed to attach device to " + vmName + ": "
 +						+ e.getMessage());
 +			} else {
 +				s_logger.warn("Failed to detach device from " + vmName + ": "
 +						+ e.getMessage());
 +			}
 +			throw e;
 +		} catch (Exception e) {
 +			throw new InternalErrorException(e.toString());
 +		} finally {
 +			if (dm != null) {
 +				try {
 +					dm.free();
 +				} catch (LibvirtException l) {
 +
 +				}
 +			}
 +		}
 +
 +		return null;
 +	}
 +
 +	@Override
 +	public PingCommand getCurrentStatus(long id) {
 +		final HashMap<String, State> newStates = sync();
 +
 +		if (!_can_bridge_firewall) {
 +			return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id,
 +					newStates);
 +		} else {
 +			HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id);
 +			return new PingRoutingWithNwGroupsCommand(getType(), id, newStates,
 +					nwGrpStates);
 +		}
 +	}
 +
 +	@Override
 +	public Type getType() {
 +		return Type.Routing;
 +	}
 +
 +	private Map<String, String> getVersionStrings() {
 +		final Script command = new Script(_versionstringpath, _timeout,
 +				s_logger);
 +		KeyValueInterpreter kvi = new KeyValueInterpreter();
 +		String result = command.execute(kvi);
 +		if (result == null) {
 +			return kvi.getKeyValues();
 +		} else {
 +			return new HashMap<String, String>(1);
 +		}
 +	}
 +
 +	@Override
 +	public StartupCommand[] initialize() {
 +		Map<String, State> changes = null;
 +
 +		synchronized (_vms) {
 +			_vms.clear();
 +			changes = sync();
 +		}
 +
 +		final List<Object> info = getHostInfo();
 +
 +		final StartupRoutingCommand cmd = new StartupRoutingCommand(
 +				(Integer) info.get(0), (Long) info.get(1), (Long) info.get(2),
 +				(Long) info.get(4), (String) info.get(3), HypervisorType.KVM,
 +				RouterPrivateIpStrategy.HostLocal);
 +		cmd.setStateChanges(changes);
 +		fillNetworkInformation(cmd);
 +		_privateIp = cmd.getPrivateIpAddress();
 +		cmd.getHostDetails().putAll(getVersionStrings());
 +		cmd.setPool(_pool);
 +		cmd.setCluster(_clusterId);
 +		cmd.setGatewayIpAddress(_localGateway);
 +
 +		StartupStorageCommand sscmd = null;
 +		try {
 +
 +			KVMStoragePool localStoragePool = _storagePoolMgr
                      .createStoragePool(_localStorageUUID, "localhost", -1,
                              _localStoragePath, "", StoragePoolType.Filesystem);
 -            com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(
 -                    localStoragePool.getUuid(), cmd.getPrivateIpAddress(),
 -                    _localStoragePath, _localStoragePath,
 -                    StoragePoolType.Filesystem, localStoragePool.getCapacity(),
 -                    localStoragePool.getUsed());
 -
 -            sscmd = new StartupStorageCommand();
 -            sscmd.setPoolInfo(pi);
 -            sscmd.setGuid(pi.getUuid());
 -            sscmd.setDataCenter(_dcId);
 -            sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
 -        } catch (CloudRuntimeException e) {
 -
 -        }
 -
 -        if (sscmd != null) {
 -            return new StartupCommand[] { cmd, sscmd };
 -        } else {
 -            return new StartupCommand[] { cmd };
 -        }
 -    }
 -
 -    protected HashMap<String, State> sync() {
 -        HashMap<String, State> newStates;
 -        HashMap<String, State> oldStates = null;
 -
 -        final HashMap<String, State> changes = new HashMap<String, State>();
 -
 -        synchronized (_vms) {
 -            newStates = getAllVms();
 -            if (newStates == null) {
 -                s_logger.debug("Unable to get the vm states so no state sync at this point.");
 -                return changes;
 -            }
 -
 -            oldStates = new HashMap<String, State>(_vms.size());
 -            oldStates.putAll(_vms);
 -
 -            for (final Map.Entry<String, State> entry : newStates.entrySet()) {
 -                final String vm = entry.getKey();
 -
 -                State newState = entry.getValue();
 -                final State oldState = oldStates.remove(vm);
 -
 -                if (newState == State.Stopped && oldState != State.Stopping
 -                        && oldState != null && oldState != State.Stopped) {
 -                    newState = getRealPowerState(vm);
 -                }
 -
 -                if (s_logger.isTraceEnabled()) {
 -                    s_logger.trace("VM " + vm + ": libvirt has state "
 -                            + newState + " and we have state "
 -                            + (oldState != null ? oldState.toString() : "null"));
 -                }
 -
 -                if (vm.startsWith("migrating")) {
 -                    s_logger.debug("Migration detected.  Skipping");
 -                    continue;
 -                }
 -                if (oldState == null) {
 -                    _vms.put(vm, newState);
 -                    s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: "
 -                            + vm);
 -                    changes.put(vm, newState);
 -                } else if (oldState == State.Starting) {
 -                    if (newState == State.Running) {
 -                        _vms.put(vm, newState);
 -                    } else if (newState == State.Stopped) {
 -                        s_logger.debug("Ignoring vm " + vm
 -                                + " because of a lag in starting the vm.");
 -                    }
 -                } else if (oldState == State.Migrating) {
 -                    if (newState == State.Running) {
 -                        s_logger.debug("Detected that an migrating VM is now running: "
 -                                + vm);
 -                        _vms.put(vm, newState);
 -                    }
 -                } else if (oldState == State.Stopping) {
 -                    if (newState == State.Stopped) {
 -                        _vms.put(vm, newState);
 -                    } else if (newState == State.Running) {
 -                        s_logger.debug("Ignoring vm " + vm
 -                                + " because of a lag in stopping the vm. ");
 -                    }
 -                } else if (oldState != newState) {
 -                    _vms.put(vm, newState);
 -                    if (newState == State.Stopped) {
 -                        if (_vmsKilled.remove(vm)) {
 -                            s_logger.debug("VM " + vm
 -                                    + " has been killed for storage. ");
 -                            newState = State.Error;
 -                        }
 -                    }
 -                    changes.put(vm, newState);
 -                }
 -            }
 -
 -            for (final Map.Entry<String, State> entry : oldStates.entrySet()) {
 -                final String vm = entry.getKey();
 -                final State oldState = entry.getValue();
 -
 -                if (s_logger.isTraceEnabled()) {
 -                    s_logger.trace("VM "
 -                            + vm
 -                            + " is now missing from libvirt so reporting stopped");
 -                }
 -
 -                if (oldState == State.Stopping) {
 -                    s_logger.debug("Ignoring VM " + vm
 -                            + " in transition state stopping.");
 -                    _vms.remove(vm);
 -                } else if (oldState == State.Starting) {
 -                    s_logger.debug("Ignoring VM " + vm
 -                            + " in transition state starting.");
 -                } else if (oldState == State.Stopped) {
 -                    _vms.remove(vm);
 -                } else if (oldState == State.Migrating) {
 -                    s_logger.debug("Ignoring VM " + vm + " in migrating state.");
 -                } else {
 -                    _vms.remove(vm);
 -                    State state = State.Stopped;
 -                    if (_vmsKilled.remove(entry.getKey())) {
 -                        s_logger.debug("VM " + vm
 -                                + " has been killed by storage monitor");
 -                        state = State.Error;
 -                    }
 -                    changes.put(entry.getKey(), state);
 -                }
 -            }
 -        }
 -
 -        return changes;
 -    }
 -
 -    protected State getRealPowerState(String vm) {
 -        int i = 0;
 -        s_logger.trace("Checking on the HALTED State");
 -        Domain dm = null;
 -        for (; i < 5; i++) {
 -            try {
 -                Connect conn = LibvirtConnection.getConnection();
 -                dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm
 -                        .getBytes()));
 -                DomainInfo.DomainState vps = dm.getInfo().state;
 -                if (vps != null
 -                        && vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF
 -                        && vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) {
 -                    return convertToState(vps);
 -                }
 -            } catch (final LibvirtException e) {
 -                s_logger.trace(e.getMessage());
 -            } catch (Exception e) {
 -                s_logger.trace(e.getMessage());
 -            } finally {
 -                try {
 -                    if (dm != null) {
 -                        dm.free();
 -                    }
 -                } catch (final LibvirtException e) {
 -
 -                }
 -            }
 -
 -            try {
 -                Thread.sleep(1000);
 -            } catch (InterruptedException e) {
 -            }
 -        }
 -        return State.Stopped;
 -    }
 -
 -    protected List<String> getAllVmNames(Connect conn) {
 -        ArrayList<String> la = new ArrayList<String>();
 -        try {
 -            final String names[] = conn.listDefinedDomains();
 -            for (int i = 0; i < names.length; i++) {
 -                la.add(names[i]);
 -            }
 -        } catch (final LibvirtException e) {
 -            s_logger.warn("Failed to list Defined domains", e);
 -        }
 -
 -        int[] ids = null;
 -        try {
 -            ids = conn.listDomains();
 -        } catch (final LibvirtException e) {
 -            s_logger.warn("Failed to list domains", e);
 -            return la;
 -        }
 -
 -        Domain dm = null;
 -        for (int i = 0; i < ids.length; i++) {
 -            try {
 -                dm = conn.domainLookupByID(ids[i]);
 -                la.add(dm.getName());
 -            } catch (final LibvirtException e) {
 -                s_logger.warn("Unable to get vms", e);
 -            } finally {
 -                try {
 -                    if (dm != null) {
 -                        dm.free();
 -                    }
 -                } catch (final LibvirtException e) {
 -
 -                }
 -            }
 -        }
 -
 -        return la;
 -    }
 -
 -    private HashMap<String, State> getAllVms() {
 -        final HashMap<String, State> vmStates = new HashMap<String, State>();
 -
 -        String[] vms = null;
 -        int[] ids = null;
 -        Connect conn = null;
 -        try {
 -            conn = LibvirtConnection.getConnection();
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to get connection: " + e.getMessage());
 -            return vmStates;
 -        }
 -
 -        try {
 -            ids = conn.listDomains();
 -        } catch (final LibvirtException e) {
 -            s_logger.warn("Unable to listDomains", e);
 -            return null;
 -        }
 -        try {
 -            vms = conn.listDefinedDomains();
 -        } catch (final LibvirtException e) {
 -            s_logger.warn("Unable to listDomains", e);
 -            return null;
 -        }
 -
 -        Domain dm = null;
 -        for (int i = 0; i < ids.length; i++) {
 -            try {
 -                dm = conn.domainLookupByID(ids[i]);
 -
 -                DomainInfo.DomainState ps = dm.getInfo().state;
 -
 -                final State state = convertToState(ps);
 -
 -                s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps
 -                        + "; vm state=" + state.toString());
 -                String vmName = dm.getName();
 -                vmStates.put(vmName, state);
 -            } catch (final LibvirtException e) {
 -                s_logger.warn("Unable to get vms", e);
 -            } finally {
 -                try {
 -                    if (dm != null) {
 -                        dm.free();
 -                    }
 -                } catch (LibvirtException e) {
 -
 -                }
 -            }
 -        }
 -
 -        for (int i = 0; i < vms.length; i++) {
 -            try {
 -
 -                dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i]
 -                        .getBytes()));
 -
 -                DomainInfo.DomainState ps = dm.getInfo().state;
 -                final State state = convertToState(ps);
 -                String vmName = dm.getName();
 -                s_logger.trace("VM " + vmName + ": powerstate = " + ps
 -                        + "; vm state=" + state.toString());
 -
 -                vmStates.put(vmName, state);
 -            } catch (final LibvirtException e) {
 -                s_logger.warn("Unable to get vms", e);
 -            } catch (Exception e) {
 -                s_logger.warn("Unable to get vms", e);
 -            } finally {
 -                try {
 -                    if (dm != null) {
 -                        dm.free();
 -                    }
 -                } catch (LibvirtException e) {
 -
 -                }
 -            }
 -        }
 -
 -        return vmStates;
 -    }
 -
 -    protected List<Object> getHostInfo() {
 -        final ArrayList<Object> info = new ArrayList<Object>();
 -        long speed = 0;
 -        long cpus = 0;
 -        long ram = 0;
 -        String cap = null;
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            final NodeInfo hosts = conn.nodeInfo();
 -            boolean result = false;
 -            try {
 -                BufferedReader in = new BufferedReader(
 -                        new FileReader(
 -                                "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"));
 -                speed = Long.parseLong(in.readLine()) / 1000;
 -                result = true;
 -            } catch (FileNotFoundException e) {
 -
 -            } catch (IOException e) {
 -
 -            } catch (NumberFormatException e) {
 -
 -            }
 -
 -            if (!result) {
 -                speed = hosts.mhz;
 -            }
 -
 -            cpus = hosts.cpus;
 -            ram = hosts.memory * 1024L;
 -            LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 -            parser.parseCapabilitiesXML(conn.getCapabilities());
 -            ArrayList<String> oss = parser.getGuestOsType();
 -            for (String s : oss) {
 -                /*
 -                 * Even host supports guest os type more than hvm, we only
 -                 * report hvm to management server
 -                 */
 -                if (s.equalsIgnoreCase("hvm")) {
 -                    cap = "hvm";
 -                }
 -            }
 -        } catch (LibvirtException e) {
 -
 -        }
 -
 -        if (isSnapshotSupported()) {
 -            cap = cap + ",snapshot";
 -        }
 -
 -        info.add((int) cpus);
 -        info.add(speed);
 -        info.add(ram);
 -        info.add(cap);
 -        long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum
 -                                                                // of 10% of
 -                                                                // system ram or
 -                                                                // 768M
 -        dom0ram = Math.max(dom0ram, _dom0MinMem);
 -        info.add(dom0ram);
 -        s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram
 -                + ", dom0ram=" + dom0ram);
 -
 -        return info;
 -    }
 -
 -    protected void cleanupVM(Connect conn, final String vmName,
 -            final String vnet) {
 -        s_logger.debug("Trying to cleanup the vnet: " + vnet);
 -        if (vnet != null) {
 -            cleanupVnet(conn, vnet);
 -        }
 -
 -        _vmStats.remove(vmName);
 -    }
 -
 -    protected String rebootVM(Connect conn, String vmName) {
 -        Domain dm = null;
 -        String msg = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            String vmDef = dm.getXMLDesc(0);
 -            s_logger.debug(vmDef);
 -            msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
 -            msg = startDomain(conn, vmName, vmDef);
 -            return null;
 -        } catch (LibvirtException e) {
 -            s_logger.warn("Failed to create vm", e);
 -            msg = e.getMessage();
 -        } catch (Exception e) {
 -            s_logger.warn("Failed to create vm", e);
 -            msg = e.getMessage();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException e) {
 -
 -            }
 -        }
 -
 -        return msg;
 -    }
 -
 -    protected String stopVM(Connect conn, String vmName, defineOps df) {
 -        DomainInfo.DomainState state = null;
 -        Domain dm = null;
 -
 -        s_logger.debug("Try to stop the vm at first");
 -        String ret = stopVM(conn, vmName, false);
 -        if (ret == Script.ERR_TIMEOUT) {
 -            ret = stopVM(conn, vmName, true);
 -        } else if (ret != null) {
 -            /*
 -             * There is a race condition between libvirt and qemu: libvirt
 -             * listens on qemu's monitor fd. If qemu is shutdown, while libvirt
 -             * is reading on the fd, then libvirt will report an error.
 -             */
 -            /* Retry 3 times, to make sure we can get the vm's status */
 -            for (int i = 0; i < 3; i++) {
 -                try {
 -                    dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                            .getBytes()));
 -                    state = dm.getInfo().state;
 -                    break;
 -                } catch (LibvirtException e) {
 -                    s_logger.debug("Failed to get vm status:" + e.getMessage());
 -                } catch (Exception e) {
 -                    s_logger.debug("Failed to get vm status:" + e.getMessage());
 -                } finally {
 -                    try {
 -                        if (dm != null) {
 -                            dm.free();
 -                        }
 -                    } catch (LibvirtException l) {
 -
 -                    }
 -                }
 -            }
 -
 -            if (state == null) {
 -                s_logger.debug("Can't get vm's status, assume it's dead already");
 -                return null;
 -            }
 -
 -            if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 -                s_logger.debug("Try to destroy the vm");
 -                ret = stopVM(conn, vmName, true);
 -                if (ret != null) {
 -                    return ret;
 -                }
 -            }
 -        }
 -
 -        if (df == defineOps.UNDEFINE_VM) {
 -            try {
 -                dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                        .getBytes()));
 -                dm.undefine();
 -            } catch (LibvirtException e) {
 -
 -            } finally {
 -                try {
 -                    if (dm != null) {
 -                        dm.free();
 -                    }
 -                } catch (LibvirtException l) {
 -
 -                }
 -            }
 -        }
 -        return null;
 -    }
 -
 -    protected String stopVM(Connect conn, String vmName, boolean force) {
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            if (force) {
 -                if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 -                    dm.destroy();
 -                }
 -            } else {
 -                if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 -                    return null;
 -                }
 -                dm.shutdown();
 -                int retry = _stopTimeout / 2000;
 -                /* Wait for the domain gets into shutoff state */
 -                while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF)
 -                        && (retry >= 0)) {
 -                    Thread.sleep(2000);
 -                    retry--;
 -                }
 -                if (retry < 0) {
 -                    s_logger.warn("Timed out waiting for domain " + vmName
 -                            + " to shutdown gracefully");
 -                    return Script.ERR_TIMEOUT;
 -                }
 -            }
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to stop VM :" + vmName + " :", e);
 -            return e.getMessage();
 -        } catch (InterruptedException ie) {
 -            s_logger.debug("Interrupted sleep");
 -            return ie.getMessage();
 -        } catch (Exception e) {
 -            s_logger.debug("Failed to stop VM :" + vmName + " :", e);
 -            return e.getMessage();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException e) {
 -            }
 -        }
 -
 -        return null;
 -    }
 -
 -    public synchronized String cleanupVnet(Connect conn, final String vnetId) {
 -        // VNC proxy VMs do not have vnet
 -        if (vnetId == null || vnetId.isEmpty()
 -                || isDirectAttachedNetwork(vnetId)) {
 -            return null;
 -        }
 -
 -        final List<String> names = getAllVmNames(conn);
 -
 -        if (!names.isEmpty()) {
 -            for (final String name : names) {
 -                if (VirtualMachineName.getVnet(name).equals(vnetId)) {
 -                    return null; // Can't remove the vnet yet.
 -                }
 -            }
 -        }
 -
 -        final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
 -        command.add("-o", "delete");
 -        command.add("-v", vnetId);
 -        return command.execute();
 -    }
 -
 -    protected Integer getVncPort(Connect conn, String vmName)
 -            throws LibvirtException {
 -        LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            String xmlDesc = dm.getXMLDesc(0);
 -            parser.parseDomainXML(xmlDesc);
 -            return parser.getVncPort();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException l) {
 -
 -            }
 -        }
 -    }
 -
 -    private boolean IsHVMEnabled(Connect conn) {
 -        LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 -        try {
 -            parser.parseCapabilitiesXML(conn.getCapabilities());
 -            ArrayList<String> osTypes = parser.getGuestOsType();
 -            for (String o : osTypes) {
 -                if (o.equalsIgnoreCase("hvm")) {
 -                    return true;
 -                }
 -            }
 -        } catch (LibvirtException e) {
 -
 -        }
 -        return false;
 -    }
 -
 -    private String getHypervisorPath(Connect conn) {
 -        LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 -        try {
 -            parser.parseCapabilitiesXML(conn.getCapabilities());
 -        } catch (LibvirtException e) {
 +			com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(
 +					localStoragePool.getUuid(), cmd.getPrivateIpAddress(),
 +					_localStoragePath, _localStoragePath,
 +					StoragePoolType.Filesystem, localStoragePool.getCapacity(),
 +					localStoragePool.getUsed());
 +
 +			sscmd = new StartupStorageCommand();
 +			sscmd.setPoolInfo(pi);
 +			sscmd.setGuid(pi.getUuid());
 +			sscmd.setDataCenter(_dcId);
 +			sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
 +		} catch (CloudRuntimeException e) {
 +
 +		}
 +
 +		if (sscmd != null) {
 +			return new StartupCommand[] { cmd, sscmd };
 +		} else {
 +			return new StartupCommand[] { cmd };
 +		}
 +	}
 +
 +	protected HashMap<String, State> sync() {
 +		HashMap<String, State> newStates;
 +		HashMap<String, State> oldStates = null;
 +
 +		final HashMap<String, State> changes = new HashMap<String, State>();
 +
 +		synchronized (_vms) {
 +			newStates = getAllVms();
 +			if (newStates == null) {
 +				s_logger.debug("Unable to get the vm states so no state sync at this point.");
 +				return changes;
 +			}
 +
 +			oldStates = new HashMap<String, State>(_vms.size());
 +			oldStates.putAll(_vms);
 +
 +			for (final Map.Entry<String, State> entry : newStates.entrySet()) {
 +				final String vm = entry.getKey();
 +
 +				State newState = entry.getValue();
 +				final State oldState = oldStates.remove(vm);
 +
 +				if (newState == State.Stopped && oldState != State.Stopping
 +						&& oldState != null && oldState != State.Stopped) {
 +					newState = getRealPowerState(vm);
 +				}
 +
 +				if (s_logger.isTraceEnabled()) {
 +					s_logger.trace("VM " + vm + ": libvirt has state "
 +							+ newState + " and we have state "
 +							+ (oldState != null ? oldState.toString() : "null"));
 +				}
 +
 +				if (vm.startsWith("migrating")) {
 +					s_logger.debug("Migration detected.  Skipping");
 +					continue;
 +				}
 +				if (oldState == null) {
 +					_vms.put(vm, newState);
 +					s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: "
 +							+ vm);
 +					changes.put(vm, newState);
 +				} else if (oldState == State.Starting) {
 +					if (newState == State.Running) {
 +						_vms.put(vm, newState);
 +					} else if (newState == State.Stopped) {
 +						s_logger.debug("Ignoring vm " + vm
 +								+ " because of a lag in starting the vm.");
 +					}
 +				} else if (oldState == State.Migrating) {
 +					if (newState == State.Running) {
 +						s_logger.debug("Detected that an migrating VM is now running: "
 +								+ vm);
 +						_vms.put(vm, newState);
 +					}
 +				} else if (oldState == State.Stopping) {
 +					if (newState == State.Stopped) {
 +						_vms.put(vm, newState);
 +					} else if (newState == State.Running) {
 +						s_logger.debug("Ignoring vm " + vm
 +								+ " because of a lag in stopping the vm. ");
 +					}
 +				} else if (oldState != newState) {
 +					_vms.put(vm, newState);
 +					if (newState == State.Stopped) {
 +						if (_vmsKilled.remove(vm)) {
 +							s_logger.debug("VM " + vm
 +									+ " has been killed for storage. ");
 +							newState = State.Error;
 +						}
 +					}
 +					changes.put(vm, newState);
 +				}
 +			}
 +
 +			for (final Map.Entry<String, State> entry : oldStates.entrySet()) {
 +				final String vm = entry.getKey();
 +				final State oldState = entry.getValue();
 +
 +				if (s_logger.isTraceEnabled()) {
 +					s_logger.trace("VM "
 +							+ vm
 +							+ " is now missing from libvirt so reporting stopped");
 +				}
 +
 +				if (oldState == State.Stopping) {
 +					s_logger.debug("Ignoring VM " + vm
 +							+ " in transition state stopping.");
 +					_vms.remove(vm);
 +				} else if (oldState == State.Starting) {
 +					s_logger.debug("Ignoring VM " + vm
 +							+ " in transition state starting.");
 +				} else if (oldState == State.Stopped) {
 +					_vms.remove(vm);
 +				} else if (oldState == State.Migrating) {
 +					s_logger.debug("Ignoring VM " + vm + " in migrating state.");
 +				} else {
 +					_vms.remove(vm);
 +					State state = State.Stopped;
 +					if (_vmsKilled.remove(entry.getKey())) {
 +						s_logger.debug("VM " + vm
 +								+ " has been killed by storage monitor");
 +						state = State.Error;
 +					}
 +					changes.put(entry.getKey(), state);
 +				}
 +			}
 +		}
 +
 +		return changes;
 +	}
 +
 +	protected State getRealPowerState(String vm) {
 +		int i = 0;
 +		s_logger.trace("Checking on the HALTED State");
 +		Domain dm = null;
 +		for (; i < 5; i++) {
 +			try {
 +				Connect conn = LibvirtConnection.getConnection();
 +				dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm
 +						.getBytes()));
 +				DomainInfo.DomainState vps = dm.getInfo().state;
 +				if (vps != null
 +						&& vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF
 +						&& vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) {
 +					return convertToState(vps);
 +				}
 +			} catch (final LibvirtException e) {
 +				s_logger.trace(e.getMessage());
 +			} catch (Exception e) {
 +				s_logger.trace(e.getMessage());
 +			} finally {
 +				try {
 +					if (dm != null) {
 +						dm.free();
 +					}
 +				} catch (final LibvirtException e) {
 +
 +				}
 +			}
 +
 +			try {
 +				Thread.sleep(1000);
 +			} catch (InterruptedException e) {
 +			}
 +		}
 +		return State.Stopped;
 +	}
 +
 +	protected List<String> getAllVmNames(Connect conn) {
 +		ArrayList<String> la = new ArrayList<String>();
 +		try {
 +			final String names[] = conn.listDefinedDomains();
 +			for (int i = 0; i < names.length; i++) {
 +				la.add(names[i]);
 +			}
 +		} catch (final LibvirtException e) {
 +			s_logger.warn("Failed to list Defined domains", e);
 +		}
 +
 +		int[] ids = null;
 +		try {
 +			ids = conn.listDomains();
 +		} catch (final LibvirtException e) {
 +			s_logger.warn("Failed to list domains", e);
 +			return la;
 +		}
 +
 +		Domain dm = null;
 +		for (int i = 0; i < ids.length; i++) {
 +			try {
 +				dm = conn.domainLookupByID(ids[i]);
 +				la.add(dm.getName());
 +			} catch (final LibvirtException e) {
 +				s_logger.warn("Unable to get vms", e);
 +			} finally {
 +				try {
 +					if (dm != null) {
 +						dm.free();
 +					}
 +				} catch (final LibvirtException e) {
 +
 +				}
 +			}
 +		}
 +
 +		return la;
 +	}
 +
 +	private HashMap<String, State> getAllVms() {
 +		final HashMap<String, State> vmStates = new HashMap<String, State>();
 +
 +		String[] vms = null;
 +		int[] ids = null;
 +		Connect conn = null;
 +		try {
 +			conn = LibvirtConnection.getConnection();
 +		} catch (LibvirtException e) {
 +			s_logger.debug("Failed to get connection: " + e.getMessage());
 +			return vmStates;
 +		}
 +
 +		try {
 +			ids = conn.listDomains();
 +		} catch (final LibvirtException e) {
 +			s_logger.warn("Unable to listDomains", e);
 +			return null;
 +		}
 +		try {
 +			vms = conn.listDefinedDomains();
 +		} catch (final LibvirtException e) {
 +			s_logger.warn("Unable to listDomains", e);
 +			return null;
 +		}
 +
 +		Domain dm = null;
 +		for (int i = 0; i < ids.length; i++) {
 +			try {
 +				dm = conn.domainLookupByID(ids[i]);
 +
 +				DomainInfo.DomainState ps = dm.getInfo().state;
 +
 +				final State state = convertToState(ps);
 +
 +				s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps
 +						+ "; vm state=" + state.toString());
 +				String vmName = dm.getName();
 +				vmStates.put(vmName, state);
 +			} catch (final LibvirtException e) {
 +				s_logger.warn("Unable to get vms", e);
 +			} finally {
 +				try {
 +					if (dm != null) {
 +						dm.free();
 +					}
 +				} catch (LibvirtException e) {
 +
 +				}
 +			}
 +		}
 +
 +		for (int i = 0; i < vms.length; i++) {
 +			try {
 +
 +				dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i]
 +						.getBytes()));
 +
 +				DomainInfo.DomainState ps = dm.getInfo().state;
 +				final State state = convertToState(ps);
 +				String vmName = dm.getName();
 +				s_logger.trace("VM " + vmName + ": powerstate = " + ps
 +						+ "; vm state=" + state.toString());
 +
 +				vmStates.put(vmName, state);
 +			} catch (final LibvirtException e) {
 +				s_logger.warn("Unable to get vms", e);
 +			} catch (Exception e) {
 +				s_logger.warn("Unable to get vms", e);
 +			} finally {
 +				try {
 +					if (dm != null) {
 +						dm.free();
 +					}
 +				} catch (LibvirtException e) {
 +
 +				}
 +			}
 +		}
 +
 +		return vmStates;
 +	}
 +
 +	protected List<Object> getHostInfo() {
 +		final ArrayList<Object> info = new ArrayList<Object>();
 +		long speed = 0;
 +		long cpus = 0;
 +		long ram = 0;
 +		String cap = null;
 +		try {
 +			Connect conn = LibvirtConnection.getConnection();
 +			final NodeInfo hosts = conn.nodeInfo();
 +			boolean result = false;
 +			try {
 +				BufferedReader in = new BufferedReader(
 +						new FileReader(
 +								"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"));
 +				speed = Long.parseLong(in.readLine()) / 1000;
 +				result = true;
 +			} catch (FileNotFoundException e) {
 +
 +			} catch (IOException e) {
 +
 +			} catch (NumberFormatException e) {
 +
 +			}
 +
 +			if (!result) {
 +				speed = hosts.mhz;
 +			}
 +
 +			cpus = hosts.cpus;
 +			ram = hosts.memory * 1024L;
 +			LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 +			parser.parseCapabilitiesXML(conn.getCapabilities());
 +			ArrayList<String> oss = parser.getGuestOsType();
 +			for (String s : oss) {
 +				/*
 +				 * Even host supports guest os type more than hvm, we only
 +				 * report hvm to management server
 +				 */
 +				if (s.equalsIgnoreCase("hvm")) {
 +					cap = "hvm";
 +				}
 +			}
 +		} catch (LibvirtException e) {
 +
 +		}
 +
 +		if (isSnapshotSupported()) {
 +			cap = cap + ",snapshot";
 +		}
 +
 +		info.add((int) cpus);
 +		info.add(speed);
 +		info.add(ram);
 +		info.add(cap);
 +		long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum
 +																// of 10% of
 +																// system ram or
 +																// 768M
 +		dom0ram = Math.max(dom0ram, _dom0MinMem);
 +		info.add(dom0ram);
 +		s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram
 +				+ ", dom0ram=" + dom0ram);
 +
 +		return info;
 +	}
 +
 +	protected void cleanupVM(Connect conn, final String vmName,
 +			final String vnet) {
 +		s_logger.debug("Trying to cleanup the vnet: " + vnet);
 +		if (vnet != null) {
 +			cleanupVnet(conn, vnet);
 +		}
 +
 +		_vmStats.remove(vmName);
 +	}
 +
 +	protected String rebootVM(Connect conn, String vmName) {
 +		Domain dm = null;
 +		String msg = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			String vmDef = dm.getXMLDesc(0);
 +			s_logger.debug(vmDef);
 +			msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
 +			msg = startDomain(conn, vmName, vmDef);
 +			return null;
 +		} catch (LibvirtException e) {
 +			s_logger.warn("Failed to create vm", e);
 +			msg = e.getMessage();
 +		} catch (Exception e) {
 +			s_logger.warn("Failed to create vm", e);
 +			msg = e.getMessage();
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException e) {
 +
 +			}
 +		}
 +
 +		return msg;
 +	}
 +
 +	protected String stopVM(Connect conn, String vmName, defineOps df) {
 +		DomainInfo.DomainState state = null;
 +		Domain dm = null;
 +
 +		s_logger.debug("Try to stop the vm at first");
 +		String ret = stopVM(conn, vmName, false);
 +		if (ret == Script.ERR_TIMEOUT) {
 +			ret = stopVM(conn, vmName, true);
 +		} else if (ret != null) {
 +			/*
 +			 * There is a race condition between libvirt and qemu: libvirt
 +			 * listens on qemu's monitor fd. If qemu is shutdown, while libvirt
 +			 * is reading on the fd, then libvirt will report an error.
 +			 */
 +			/* Retry 3 times, to make sure we can get the vm's status */
 +			for (int i = 0; i < 3; i++) {
 +				try {
 +					dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +							.getBytes()));
 +					state = dm.getInfo().state;
 +					break;
 +				} catch (LibvirtException e) {
 +					s_logger.debug("Failed to get vm status:" + e.getMessage());
 +				} catch (Exception e) {
 +					s_logger.debug("Failed to get vm status:" + e.getMessage());
 +				} finally {
 +					try {
 +						if (dm != null) {
 +							dm.free();
 +						}
 +					} catch (LibvirtException l) {
 +
 +					}
 +				}
 +			}
 +
 +			if (state == null) {
 +				s_logger.debug("Can't get vm's status, assume it's dead already");
 +				return null;
 +			}
 +
 +			if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 +				s_logger.debug("Try to destroy the vm");
 +				ret = stopVM(conn, vmName, true);
 +				if (ret != null) {
 +					return ret;
 +				}
 +			}
 +		}
 +
 +		if (df == defineOps.UNDEFINE_VM) {
 +			try {
 +				dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +						.getBytes()));
 +				dm.undefine();
 +			} catch (LibvirtException e) {
 +
 +			} finally {
 +				try {
 +					if (dm != null) {
 +						dm.free();
 +					}
 +				} catch (LibvirtException l) {
 +
 +				}
 +			}
 +		}
 +		return null;
 +	}
 +
 +	protected String stopVM(Connect conn, String vmName, boolean force) {
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			if (force) {
 +				if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 +					dm.destroy();
 +				}
 +			} else {
 +				if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
 +					return null;
 +				}
 +				dm.shutdown();
 +				int retry = _stopTimeout / 2000;
 +				/* Wait for the domain gets into shutoff state */
 +				while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF)
 +						&& (retry >= 0)) {
 +					Thread.sleep(2000);
 +					retry--;
 +				}
 +				if (retry < 0) {
 +					s_logger.warn("Timed out waiting for domain " + vmName
 +							+ " to shutdown gracefully");
 +					return Script.ERR_TIMEOUT;
 +				}
 +			}
 +		} catch (LibvirtException e) {
 +			s_logger.debug("Failed to stop VM :" + vmName + " :", e);
 +			return e.getMessage();
 +		} catch (InterruptedException ie) {
 +			s_logger.debug("Interrupted sleep");
 +			return ie.getMessage();
 +		} catch (Exception e) {
 +			s_logger.debug("Failed to stop VM :" + vmName + " :", e);
 +			return e.getMessage();
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException e) {
 +			}
 +		}
 +
 +		return null;
 +	}
 +
 +	public synchronized String cleanupVnet(Connect conn, final String vnetId) {
 +		// VNC proxy VMs do not have vnet
 +		if (vnetId == null || vnetId.isEmpty()
 +				|| isDirectAttachedNetwork(vnetId)) {
 +			return null;
 +		}
 +
 +		final List<String> names = getAllVmNames(conn);
 +
 +		if (!names.isEmpty()) {
 +			for (final String name : names) {
 +				if (VirtualMachineName.getVnet(name).equals(vnetId)) {
 +					return null; // Can't remove the vnet yet.
 +				}
 +			}
 +		}
 +
 +		final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
 +		command.add("-o", "delete");
 +		command.add("-v", vnetId);
 +		return command.execute();
 +	}
 +
 +	protected Integer getVncPort(Connect conn, String vmName)
 +			throws LibvirtException {
 +		LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			String xmlDesc = dm.getXMLDesc(0);
 +			parser.parseDomainXML(xmlDesc);
 +			return parser.getVncPort();
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException l) {
 +
 +			}
 +		}
 +	}
 +
 +	private boolean IsHVMEnabled(Connect conn) {
 +		LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 +		try {
 +			parser.parseCapabilitiesXML(conn.getCapabilities());
 +			ArrayList<String> osTypes = parser.getGuestOsType();
 +			for (String o : osTypes) {
 +				if (o.equalsIgnoreCase("hvm")) {
 +					return true;
 +				}
 +			}
 +		} catch (LibvirtException e) {
 +
 +		}
 +		return false;
 +	}
 +
 +	private String getHypervisorPath(Connect conn) {
- 		File f = new File("/usr/bin/cloud-qemu-kvm");
- 		if (f.exists()) {
- 			return "/usr/bin/cloud-qemu-kvm";
- 		} else {
- 			f = new File("/usr/libexec/cloud-qemu-kvm");
- 			if (f.exists()) {
- 				return "/usr/libexec/cloud-qemu-kvm";
- 			}
- 
 +			LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
 +			try {
 +				parser.parseCapabilitiesXML(conn.getCapabilities());
 +			} catch (LibvirtException e) {
- 
+             s_logger.debug(e.getMessage());
 -        }
 -        return parser.getEmulator();
 -    }
 -
 -    private String getGuestType(Connect conn, String vmName) {
 -        LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            String xmlDesc = dm.getXMLDesc(0);
 -            parser.parseDomainXML(xmlDesc);
 -            return parser.getDescription();
 -        } catch (LibvirtException e) {
 -            return null;
 -        } catch (Exception e) {
 -            return null;
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException l) {
 -
 -            }
 -        }
 -    }
 -
 -    private boolean isGuestPVEnabled(String guestOS) {
 -        if (guestOS == null) {
 -            return false;
 -        }
 -        String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS);
 -        if (guestOS.startsWith("Ubuntu")
 -                || guestOSName.startsWith("Fedora 13")
 -                || guestOSName.startsWith("Fedora 12")
 -                || guestOSName.startsWith("Fedora 11")
 -                || guestOSName.startsWith("Fedora 10")
 -                || guestOSName.startsWith("Fedora 9")
 -                || guestOSName.startsWith("CentOS 5.3")
 -                || guestOSName.startsWith("CentOS 5.4")
 -                || guestOSName.startsWith("CentOS 5.5")
 -                || guestOS.startsWith("CentOS")
 -                || guestOS.startsWith("Fedora")
 -                || guestOSName.startsWith("Red Hat Enterprise Linux 5.3")
 -                || guestOSName.startsWith("Red Hat Enterprise Linux 5.4")
 -                || guestOSName.startsWith("Red Hat Enterprise Linux 5.5")
 -                || guestOSName.startsWith("Red Hat Enterprise Linux 6")
 -                || guestOS.startsWith("Debian GNU/Linux")
 -                || guestOSName.startsWith("Other PV")) {
 -            return true;
 -        } else {
 -            return false;
 -        }
 -    }
 -
 -    public boolean isCentosHost() {
 -        if (_hvVersion <= 9) {
 -            return true;
 -        } else {
 -            return false;
 -        }
 -    }
 -
 -    private InterfaceDef.nicModel getGuestNicModel(String guestOSType) {
 -        if (isGuestPVEnabled(guestOSType)) {
 -            return InterfaceDef.nicModel.VIRTIO;
 -        } else {
 -            return InterfaceDef.nicModel.E1000;
 -        }
 -    }
 -
 -    private DiskDef.diskBus getGuestDiskModel(String guestOSType) {
 -        if (isGuestPVEnabled(guestOSType)) {
 -            return DiskDef.diskBus.VIRTIO;
 -        } else {
 -            return DiskDef.diskBus.IDE;
 -        }
 -    }
 -
 -    private String setVnetBrName(String vnetId) {
 -        return "cloudVirBr" + vnetId;
 -    }
 -
 -    private String getVnetIdFromBrName(String vnetBrName) {
 -        return vnetBrName.replaceAll("cloudVirBr", "");
 -    }
 -
 -    private void cleanupVMNetworks(Connect conn, List<InterfaceDef> nics) {
 -        for (InterfaceDef nic : nics) {
 -            if (nic.getHostNetType() == hostNicType.VNET) {
 -                cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName()));
 -            }
 -        }
 -    }
 -
 -    private Domain getDomain(Connect conn, String vmName)
 -            throws LibvirtException {
 -        return conn
 -                .domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
 -    }
 -
 -    protected List<InterfaceDef> getInterfaces(Connect conn, String vmName) {
 -        LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            parser.parseDomainXML(dm.getXMLDesc(0));
 -            return parser.getInterfaces();
 -
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to get dom xml: " + e.toString());
 -            return new ArrayList<InterfaceDef>();
 -        } catch (Exception e) {
 -            s_logger.debug("Failed to get dom xml: " + e.toString());
 -            return new ArrayList<InterfaceDef>();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException e) {
 -
 -            }
 -        }
 -    }
 -
 -    protected List<DiskDef> getDisks(Connect conn, String vmName) {
 -        LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            parser.parseDomainXML(dm.getXMLDesc(0));
 -            return parser.getDisks();
 -
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to get dom xml: " + e.toString());
 -            return new ArrayList<DiskDef>();
 -        } catch (Exception e) {
 -            s_logger.debug("Failed to get dom xml: " + e.toString());
 -            return new ArrayList<DiskDef>();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (LibvirtException e) {
 -
 -            }
 -        }
 -    }
 -
 -    private String executeBashScript(String script) {
 -        Script command = new Script("/bin/bash", _timeout, s_logger);
 -        command.add("-c");
 -        command.add(script);
 -        return command.execute();
 -    }
 -
 -    private String executeBashScript(String script, OutputInterpreter parser) {
 -        Script command = new Script("/bin/bash", _timeout, s_logger);
 -        command.add("-c");
 -        command.add(script);
 -        return command.execute(parser);
 -    }
 -
 -    private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
 -        Script command = new Script("/bin/bash", _timeout);
 -        command.add("-c");
 -        command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
 -        OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
 -        String result = command.execute(parser);
 -        boolean foundLinkLocalBr = false;
 -        if (result == null && parser.getLines() != null) {
 -            String[] lines = parser.getLines().split("\\n");
 -            for (String line : lines) {
 -                String[] tokens = line.split(" ");
 -                if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
 -                    Script.runSimpleBashScript("ip route del "
 -                            + NetUtils.getLinkLocalCIDR());
 -                } else {
 -                    foundLinkLocalBr = true;
 -                }
 -            }
 -        }
 -        if (!foundLinkLocalBr) {
 -            Script.runSimpleBashScript("ip route add "
 -                    + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr
 -                    + " src " + NetUtils.getLinkLocalGateway());
 -        }
 -    }
 -
 -    private class vmStats {
 -        long _usedTime;
 -        long _tx;
 -        long _rx;
 -        Calendar _timestamp;
 -    }
 -
 -    private VmStatsEntry getVmStat(Connect conn, String vmName)
 -            throws LibvirtException {
 -        Domain dm = null;
 -        try {
 -            dm = getDomain(conn, vmName);
 -            DomainInfo info = dm.getInfo();
 -
 -            VmStatsEntry stats = new VmStatsEntry();
 -            stats.setNumCPUs(info.nrVirtCpu);
 -            stats.setEntityType("vm");
 -
 -            /* get cpu utilization */
 -            vmStats oldStats = null;
 -
 -            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);
 -
 -                NodeInfo node = conn.nodeInfo();
 -                utilization = utilization / node.cpus;
 -                stats.setCPUUtilization(utilization * 100);
 -            }
 -
 -            /* get network stats */
 -
 -            List<InterfaceDef> vifs = getInterfaces(conn, vmName);
 -            long rx = 0;
 -            long tx = 0;
 -            for (InterfaceDef vif : vifs) {
 -                DomainInterfaceStats ifStats = dm.interfaceStats(vif
 -                        .getDevName());
 -                rx += ifStats.rx_bytes;
 -                tx += ifStats.tx_bytes;
 -            }
 -
 -            if (oldStats != null) {
 -                long deltarx = rx - oldStats._rx;
 -                if (deltarx > 0)
 -                    stats.setNetworkReadKBs(deltarx / 1000);
 -                long deltatx = tx - oldStats._tx;
 -                if (deltatx > 0)
 -                    stats.setNetworkWriteKBs(deltatx / 1000);
 -            }
 -
 -            vmStats newStat = new vmStats();
 -            newStat._usedTime = info.cpuTime;
 -            newStat._rx = rx;
 -            newStat._tx = tx;
 -            newStat._timestamp = now;
 -            _vmStats.put(vmName, newStat);
 -            return stats;
 -        } finally {
 -            if (dm != null) {
 -                dm.free();
 -            }
 -        }
 -    }
 -
 -    private boolean can_bridge_firewall(String prvNic) {
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("can_bridge_firewall");
 -        cmd.add(prvNic);
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -        String vif = null;
 -        List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 -        if (intfs.size() > 0) {
 -            InterfaceDef intf = intfs.get(0);
 -            vif = intf.getDevName();
 -        }
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("destroy_network_rules_for_vm");
 -        cmd.add("--vmname", vmName);
 -        if (vif != null) {
 -            cmd.add("--vif", vif);
 -        }
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    protected boolean default_network_rules(Connect conn, String vmName,
 -            NicTO nic, Long vmId) {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -
 -        List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 -        if (intfs.size() < nic.getDeviceId()) {
 -            return false;
 -        }
 -
 -        InterfaceDef intf = intfs.get(nic.getDeviceId());
 -        String brname = intf.getBrName();
 -        String vif = intf.getDevName();
 -
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("default_network_rules");
 -        cmd.add("--vmname", vmName);
 -        cmd.add("--vmid", vmId.toString());
 -        if (nic.getIp() != null) {
 -            cmd.add("--vmip", nic.getIp());
 -        }
 -        cmd.add("--vmmac", nic.getMac());
 -        cmd.add("--vif", vif);
 -        cmd.add("--brname", brname);
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    protected boolean post_default_network_rules(Connect conn, String vmName,
 -            NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp,
 -            String hostMacAddr) {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -
 -        List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 -        if (intfs.size() < nic.getDeviceId()) {
 -            return false;
 -        }
 -
 -        InterfaceDef intf = intfs.get(nic.getDeviceId());
 -        String brname = intf.getBrName();
 -        String vif = intf.getDevName();
 -
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("post_default_network_rules");
 -        cmd.add("--vmname", vmName);
 -        cmd.add("--vmid", vmId.toString());
 -        cmd.add("--vmip", nic.getIp());
 -        cmd.add("--vmmac", nic.getMac());
 -        cmd.add("--vif", vif);
 -        cmd.add("--brname", brname);
 -        if (dhcpServerIp != null)
 -            cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress());
 -
 -        cmd.add("--hostIp", hostIp);
 -        cmd.add("--hostMacAddr", hostMacAddr);
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    protected boolean default_network_rules_for_systemvm(Connect conn,
 -            String vmName) {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("default_network_rules_systemvm");
 -        cmd.add("--vmname", vmName);
 +			}
 +			return parser.getEmulator();
 +		}
- 	}
 +
 +	private String getGuestType(Connect conn, String vmName) {
 +		LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			String xmlDesc = dm.getXMLDesc(0);
 +			parser.parseDomainXML(xmlDesc);
 +			return parser.getDescription();
 +		} catch (LibvirtException e) {
 +			return null;
 +		} catch (Exception e) {
 +			return null;
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException l) {
 +
 +			}
 +		}
 +	}
 +
 +	private boolean isGuestPVEnabled(String guestOS) {
 +		if (guestOS == null) {
 +			return false;
 +		}
 +		String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS);
 +		if (guestOS.startsWith("Ubuntu")
 +				|| guestOSName.startsWith("Fedora 13")
 +				|| guestOSName.startsWith("Fedora 12")
 +				|| guestOSName.startsWith("Fedora 11")
 +				|| guestOSName.startsWith("Fedora 10")
 +				|| guestOSName.startsWith("Fedora 9")
 +				|| guestOSName.startsWith("CentOS 5.3")
 +				|| guestOSName.startsWith("CentOS 5.4")
 +				|| guestOSName.startsWith("CentOS 5.5")
 +				|| guestOS.startsWith("CentOS")
 +				|| guestOS.startsWith("Fedora")
 +				|| guestOSName.startsWith("Red Hat Enterprise Linux 5.3")
 +				|| guestOSName.startsWith("Red Hat Enterprise Linux 5.4")
 +				|| guestOSName.startsWith("Red Hat Enterprise Linux 5.5")
 +				|| guestOSName.startsWith("Red Hat Enterprise Linux 6")
 +				|| guestOS.startsWith("Debian GNU/Linux")
 +				|| guestOSName.startsWith("Other PV")) {
 +			return true;
 +		} else {
 +			return false;
 +		}
 +	}
 +
 +	public boolean isCentosHost() {
 +		if (_hvVersion <= 9) {
 +			return true;
 +		} else {
 +			return false;
 +		}
 +	}
 +
 +	private InterfaceDef.nicModel getGuestNicModel(String guestOSType) {
 +		if (isGuestPVEnabled(guestOSType)) {
 +			return InterfaceDef.nicModel.VIRTIO;
 +		} else {
 +			return InterfaceDef.nicModel.E1000;
 +		}
 +	}
 +
 +	private DiskDef.diskBus getGuestDiskModel(String guestOSType) {
 +		if (isGuestPVEnabled(guestOSType)) {
 +			return DiskDef.diskBus.VIRTIO;
 +		} else {
 +			return DiskDef.diskBus.IDE;
 +		}
 +	}
 +
 +	private String setVnetBrName(String vnetId) {
 +		return "cloudVirBr" + vnetId;
 +	}
 +
 +	private String getVnetIdFromBrName(String vnetBrName) {
 +		return vnetBrName.replaceAll("cloudVirBr", "");
 +	}
 +
 +	private void cleanupVMNetworks(Connect conn, List<InterfaceDef> nics) {
 +		for (InterfaceDef nic : nics) {
 +			if (nic.getHostNetType() == hostNicType.VNET) {
 +				cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName()));
 +			}
 +		}
 +	}
 +
 +	private Domain getDomain(Connect conn, String vmName)
 +			throws LibvirtException {
 +		return conn
 +				.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
 +	}
 +
 +	protected List<InterfaceDef> getInterfaces(Connect conn, String vmName) {
 +		LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			parser.parseDomainXML(dm.getXMLDesc(0));
 +			return parser.getInterfaces();
 +
 +		} catch (LibvirtException e) {
 +			s_logger.debug("Failed to get dom xml: " + e.toString());
 +			return new ArrayList<InterfaceDef>();
 +		} catch (Exception e) {
 +			s_logger.debug("Failed to get dom xml: " + e.toString());
 +			return new ArrayList<InterfaceDef>();
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException e) {
 +
 +			}
 +		}
 +	}
 +
 +	protected List<DiskDef> getDisks(Connect conn, String vmName) {
 +		LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
 +		Domain dm = null;
 +		try {
 +			dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 +					.getBytes()));
 +			parser.parseDomainXML(dm.getXMLDesc(0));
 +			return parser.getDisks();
 +
 +		} catch (LibvirtException e) {
 +			s_logger.debug("Failed to get dom xml: " + e.toString());
 +			return new ArrayList<DiskDef>();
 +		} catch (Exception e) {
 +			s_logger.debug("Failed to get dom xml: " + e.toString());
 +			return new ArrayList<DiskDef>();
 +		} finally {
 +			try {
 +				if (dm != null) {
 +					dm.free();
 +				}
 +			} catch (LibvirtException e) {
 +
 +			}
 +		}
 +	}
 +
 +	private String executeBashScript(String script) {
 +		Script command = new Script("/bin/bash", _timeout, s_logger);
 +		command.add("-c");
 +		command.add(script);
 +		return command.execute();
 +	}
 +
 +	private String executeBashScript(String script, OutputInterpreter parser) {
 +		Script command = new Script("/bin/bash", _timeout, s_logger);
 +		command.add("-c");
 +		command.add(script);
 +		return command.execute(parser);
 +	}
 +
 +	private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
 +		Script command = new Script("/bin/bash", _timeout);
 +		command.add("-c");
 +		command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
 +		OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
 +		String result = command.execute(parser);
 +		boolean foundLinkLocalBr = false;
 +		if (result == null && parser.getLines() != null) {
 +			String[] lines = parser.getLines().split("\\n");
 +			for (String line : lines) {
 +				String[] tokens = line.split(" ");
 +				if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
 +					Script.runSimpleBashScript("ip route del "
 +							+ NetUtils.getLinkLocalCIDR());
 +				} else {
 +					foundLinkLocalBr = true;
 +				}
 +			}
 +		}
 +		if (!foundLinkLocalBr) {
 +			Script.runSimpleBashScript("ip route add "
 +					+ NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr
 +					+ " src " + NetUtils.getLinkLocalGateway());
 +		}
 +	}
 +
 +	private class vmStats {
 +		long _usedTime;
 +		long _tx;
 +		long _rx;
 +		Calendar _timestamp;
 +	}
 +
 +	private VmStatsEntry getVmStat(Connect conn, String vmName)
 +			throws LibvirtException {
 +		Domain dm = null;
 +		try {
 +			dm = getDomain(conn, vmName);
 +			DomainInfo info = dm.getInfo();
 +
 +			VmStatsEntry stats = new VmStatsEntry();
 +			stats.setNumCPUs(info.nrVirtCpu);
 +			stats.setEntityType("vm");
 +
 +			/* get cpu utilization */
 +			vmStats oldStats = null;
 +
 +			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);
 +
 +				NodeInfo node = conn.nodeInfo();
 +				utilization = utilization / node.cpus;
 +				stats.setCPUUtilization(utilization * 100);
 +			}
 +
 +			/* get network stats */
 +
 +			List<InterfaceDef> vifs = getInterfaces(conn, vmName);
 +			long rx = 0;
 +			long tx = 0;
 +			for (InterfaceDef vif : vifs) {
 +				DomainInterfaceStats ifStats = dm.interfaceStats(vif
 +						.getDevName());
 +				rx += ifStats.rx_bytes;
 +				tx += ifStats.tx_bytes;
 +			}
 +
 +			if (oldStats != null) {
 +				long deltarx = rx - oldStats._rx;
 +				if (deltarx > 0)
 +					stats.setNetworkReadKBs(deltarx / 1000);
 +				long deltatx = tx - oldStats._tx;
 +				if (deltatx > 0)
 +					stats.setNetworkWriteKBs(deltatx / 1000);
 +			}
 +
 +			vmStats newStat = new vmStats();
 +			newStat._usedTime = info.cpuTime;
 +			newStat._rx = rx;
 +			newStat._tx = tx;
 +			newStat._timestamp = now;
 +			_vmStats.put(vmName, newStat);
 +			return stats;
 +		} finally {
 +			if (dm != null) {
 +				dm.free();
 +			}
 +		}
 +	}
 +
 +	private boolean can_bridge_firewall(String prvNic) {
 +		Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 +		cmd.add("can_bridge_firewall");
 +		cmd.add(prvNic);
 +		String result = cmd.execute();
 +		if (result != null) {
 +			return false;
 +		}
 +		return true;
 +	}
 +
 +	protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) {
 +		if (!_can_bridge_firewall) {
 +			return false;
 +		}
 +		String vif = null;
 +		List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 +		if (intfs.size() > 0) {
 +			InterfaceDef intf = intfs.get(0);
 +			vif = intf.getDevName();
 +		}
 +		Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 +		cmd.add("destroy_network_rules_for_vm");
 +		cmd.add("--vmname", vmName);
 +		if (vif != null) {
 +			cmd.add("--vif", vif);
 +		}
 +		String result = cmd.execute();
 +		if (result != null) {
 +			return false;
 +		}
 +		return true;
 +	}
 +
 +	protected boolean default_network_rules(Connect conn, String vmName,
 +			NicTO nic, Long vmId) {
 +		if (!_can_bridge_firewall) {
 +			return false;
 +		}
 +
 +		List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 +		if (intfs.size() < nic.getDeviceId()) {
 +			return false;
 +		}
 +
 +		InterfaceDef intf = intfs.get(nic.getDeviceId());
 +		String brname = intf.getBrName();
 +		String vif = intf.getDevName();
 +
 +		Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 +		cmd.add("default_network_rules");
 +		cmd.add("--vmname", vmName);
 +		cmd.add("--vmid", vmId.toString());
 +		if (nic.getIp() != null) {
 +			cmd.add("--vmip", nic.getIp());
 +		}
 +		cmd.add("--vmmac", nic.getMac());
 +		cmd.add("--vif", vif);
 +		cmd.add("--brname", brname);
 +		String result = cmd.execute();
 +		if (result != null) {
 +			return false;
 +		}
 +		return true;
 +	}
 +
 +	protected boolean post_default_network_rules(Connect conn, String vmName,
 +			NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp,
 +			String hostMacAddr) {
 +		if (!_can_bridge_firewall) {
 +			return false;
 +		}
 +
 +		List<InterfaceDef> intfs = getInterfaces(conn, vmName);
 +		if (intfs.size() < nic.getDeviceId()) {
 +			return false;
 +		}
 +
 +		InterfaceDef intf = intfs.get(nic.getDeviceId());
 +		String brname = intf.getBrName();
 +		String vif = intf.getDevName();
 +
 +		Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 +		cmd.add("post_default_network_rules");
 +		cmd.add("--vmname", vmName);
 +		cmd.add("--vmid", vmId.toString());
 +		cmd.add("--vmip", nic.getIp());
 +		cmd.add("--vmmac", nic.getMac());
 +		cmd.add("--vif", vif);
 +		cmd.add("--brname", brname);
 +		if (dhcpServerIp != null)
 +			cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress());
 +
 +		cmd.add("--hostIp", hostIp);
 +		cmd.add("--hostMacAddr", hostMacAddr);
 +		String result = cmd.execute();
 +		if (result != null) {
 +			return false;
 +		}
 +		return true;
 +	}
 +
 +	protected boolean default_network_rules_for_systemvm(Connect conn,
 +			String vmName) {
 +		if (!_can_bridge_firewall) {
 +			return false;
 +		}
 +
 +		Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 +		cmd.add("default_network_rules_systemvm");
 +		cmd.add("--vmname", vmName);
          cmd.add("--localbrname", _linkLocalBridgeName);
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    private boolean add_network_rules(String vmName, String vmId,
 -            String guestIP, String sig, String seq, String mac, String rules,
 -            String vif, String brname) {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -
 -        String newRules = rules.replace(" ", ";");
 -        Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
 -        cmd.add("add_network_rules");
 -        cmd.add("--vmname", vmName);
 -        cmd.add("--vmid", vmId);
 -        cmd.add("--vmip", guestIP);
 -        cmd.add("--sig", sig);
 -        cmd.add("--seq", seq);
 -        cmd.add("--vmmac", mac);
 -        cmd.add("--vif", vif);
 -        cmd.add("--brname", brname);
 -        if (rules != null) {
 -            cmd.add("--rules", newRules);
 -        }
 -        String result = cmd.execute();
 -        if (result != null) {
 -            return false;
 -        }
 -        return true;
 -    }
 -
 -    private boolean cleanup_rules() {
 -        if (!_can_bridge_firewall) {
 -            return false;
 -        }
 -      

<TRUNCATED>
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/048c5e50/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/048c5e50/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------


Mime
View raw message