You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by al...@apache.org on 2012/06/29 02:45:06 UTC

[6/50] [abbrv] Merge branch 'master' into vpc

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/634cd78b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --cc agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
index 9cdd863,112ab61..e7e19c9
--- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
+++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
@@@ -227,3875 -227,3861 +227,3863 @@@ import com.cloud.vm.VirtualMachineName
   **/
  @Local(value = { ServerResource.class })
  public class LibvirtComputingResource extends ServerResourceBase implements
 -        ServerResource {
 -    private static final Logger s_logger = Logger
 -            .getLogger(LibvirtComputingResource.class);
 -
 -    private String _modifyVlanPath;
 -    private String _versionstringpath;
 -    private String _patchdomrPath;
 -    private String _createvmPath;
 -    private String _manageSnapshotPath;
 -    private String _createTmplPath;
 -    private String _heartBeatPath;
 -    private String _securityGroupPath;
 -    private String _networkUsagePath;
 -    private String _host;
 -    private String _dcId;
 -    private String _pod;
 -    private String _clusterId;
 -    private int _migrateSpeed;
 -
 -    private long _hvVersion;
 -    private KVMHAMonitor _monitor;
 -    private final String _SSHKEYSPATH = "/root/.ssh";
 -    private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator
 -            + "id_rsa.cloud";
 -    private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator
 -            + "id_rsa.pub.cloud";
 -    private String _mountPoint = "/mnt";
 -    StorageLayer _storage;
 -    private KVMStoragePoolManager _storagePoolMgr;
 -
 -    private static final class KeyValueInterpreter extends OutputInterpreter {
 -        private final Map<String, String> map = new HashMap<String, String>();
 -
 -        @Override
 -        public String interpret(BufferedReader reader) throws IOException {
 -            String line = null;
 -            int numLines = 0;
 -            while ((line = reader.readLine()) != null) {
 -                String[] toks = line.trim().split("=");
 -                if (toks.length < 2) {
 -                    s_logger.warn("Failed to parse Script output: " + line);
 -                } else {
 -                    map.put(toks[0].trim(), toks[1].trim());
 -                }
 -                numLines++;
 -            }
 -            if (numLines == 0) {
 -                s_logger.warn("KeyValueInterpreter: no output lines?");
 -            }
 -            return null;
 -        }
 -
 -        public Map<String, String> getKeyValues() {
 -            return map;
 -        }
 -    }
 -
 -    @Override
 -    protected String getDefaultScriptsDir() {
 -        return null;
 -    }
 -
 -    protected static MessageFormat SnapshotXML = new MessageFormat(
 -            "   <domainsnapshot>" + "       <name>{0}</name>" + "          <domain>"
 -                    + "            <uuid>{1}</uuid>" + "        </domain>"
 -                    + "    </domainsnapshot>");
 -
 -    protected String _hypervisorType;
 -    protected String _hypervisorURI;
 -    protected String _hypervisorPath;
 -    protected String _sysvmISOPath;
 -    protected String _privNwName;
 -    protected String _privBridgeName;
 -    protected String _linkLocalBridgeName;
 -    protected String _publicBridgeName;
 -    protected String _guestBridgeName;
 -    protected String _privateIp;
 -    protected String _pool;
 -    protected String _localGateway;
 -    private boolean _can_bridge_firewall;
 -    protected String _localStoragePath;
 -    protected String _localStorageUUID;
 -    private Pair<String, String> _pifs;
 -    private final Map<String, vmStats> _vmStats = new ConcurrentHashMap<String, vmStats>();
 -
 -    protected boolean _disconnected = true;
 -    protected int _timeout;
 -    protected int _cmdsTimeout;
 -    protected int _stopTimeout;
 -    protected static HashMap<DomainInfo.DomainState, State> s_statesTable;
 -    static {
 -        s_statesTable = new HashMap<DomainInfo.DomainState, State>();
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF,
 -                State.Stopped);
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED,
 -                State.Running);
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING,
 -                State.Running);
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED,
 -                State.Running);
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE,
 -                State.Unknown);
 -        s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN,
 -                State.Stopping);
 -    }
 -
 -    protected HashMap<String, State> _vms = new HashMap<String, State>(20);
 -    protected List<String> _vmsKilled = new ArrayList<String>();
 -
 -    private VirtualRoutingResource _virtRouterResource;
 -
 -    private String _pingTestPath;
 -
 -    private int _dom0MinMem;
 -
 -    protected enum defineOps {
 -        UNDEFINE_VM, DEFINE_VM
 -    }
 -
 -    private String getEndIpFromStartIp(String startIp, int numIps) {
 -        String[] tokens = startIp.split("[.]");
 -        assert (tokens.length == 4);
 -        int lastbyte = Integer.parseInt(tokens[3]);
 -        lastbyte = lastbyte + numIps;
 -        tokens[3] = Integer.toString(lastbyte);
 -        StringBuilder end = new StringBuilder(15);
 -        end.append(tokens[0]).append(".").append(tokens[1]).append(".")
 -                .append(tokens[2]).append(".").append(tokens[3]);
 -        return end.toString();
 -    }
 -
 -    private Map<String, Object> getDeveloperProperties()
 -            throws ConfigurationException {
 -        final File file = PropertiesUtil.findConfigFile("developer.properties");
 -        if (file == null) {
 -            throw new ConfigurationException(
 -                    "Unable to find developer.properties.");
 -        }
 -
 -        s_logger.info("developer.properties found at " + file.getAbsolutePath());
 -        Properties properties = new Properties();
 -        try {
 -            properties.load(new FileInputStream(file));
 -
 -            String startMac = (String) properties.get("private.macaddr.start");
 -            if (startMac == null) {
 -                throw new ConfigurationException(
 -                        "Developers must specify start mac for private ip range");
 -            }
 -
 -            String startIp = (String) properties.get("private.ipaddr.start");
 -            if (startIp == null) {
 -                throw new ConfigurationException(
 -                        "Developers must specify start ip for private ip range");
 -            }
 -            final Map<String, Object> params = PropertiesUtil.toMap(properties);
 -
 -            String endIp = (String) properties.get("private.ipaddr.end");
 -            if (endIp == null) {
 -                endIp = getEndIpFromStartIp(startIp, 16);
 -                params.put("private.ipaddr.end", endIp);
 -            }
 -            return params;
 -        } catch (final FileNotFoundException ex) {
 -            throw new CloudRuntimeException("Cannot find the file: "
 -                    + file.getAbsolutePath(), ex);
 -        } catch (final IOException ex) {
 -            throw new CloudRuntimeException("IOException in reading "
 -                    + file.getAbsolutePath(), ex);
 -        }
 -    }
 -
 -    protected String getDefaultNetworkScriptsDir() {
 -        return "scripts/vm/network/vnet";
 -    }
 -
 -    protected String getDefaultStorageScriptsDir() {
 -        return "scripts/storage/qcow2";
 -    }
 -
 -    private void saveProperties(Map<String, Object> params)
 -            throws ConfigurationException {
 -        final File file = PropertiesUtil.findConfigFile("agent.properties");
 -        if (file == null) {
 -            throw new ConfigurationException("Unable to find agent.properties.");
 -        }
 -
 -        s_logger.info("agent.properties found at " + file.getAbsolutePath());
 -
 -        try {
 -            Properties _properties = new Properties();
 -            _properties.load(new FileInputStream(file));
 -            Set<String> names = _properties.stringPropertyNames();
 -            for (String key : params.keySet()) {
 -                if (!names.contains(key)) {
 -                    _properties.setProperty(key, (String) params.get(key));
 -                }
 -            }
 -            _properties.store(new FileOutputStream(file), "");
 -        } catch (final FileNotFoundException ex) {
 -            throw new CloudRuntimeException("Cannot find the file: "
 -                    + file.getAbsolutePath(), ex);
 -        } catch (final IOException ex) {
 -            throw new CloudRuntimeException("IOException in reading "
 -                    + file.getAbsolutePath(), ex);
 -        }
 -    }
 -
 -    @Override
 -    public boolean configure(String name, Map<String, Object> params)
 -            throws ConfigurationException {
 -        boolean success = super.configure(name, params);
 -        if (!success) {
 -            return false;
 -        }
 -
 -        try {
 -            Class<?> clazz = Class
 -                    .forName("com.cloud.storage.JavaStorageLayer");
 -            _storage = (StorageLayer) ComponentLocator.inject(clazz);
 -            _storage.configure("StorageLayer", params);
 -        } catch (ClassNotFoundException e) {
 -            throw new ConfigurationException("Unable to find class "
 -                    + "com.cloud.storage.JavaStorageLayer");
 -        }
 -
 -        _virtRouterResource = new VirtualRoutingResource();
 -
 -        // Set the domr scripts directory
 -        params.put("domr.scripts.dir", "scripts/network/domr/kvm");
 -
 -        success = _virtRouterResource.configure(name, params);
 -
 -        String kvmScriptsDir = (String) params.get("kvm.scripts.dir");
 -        if (kvmScriptsDir == null) {
 -            kvmScriptsDir = "scripts/vm/hypervisor/kvm";
 -        }
 -
 -        String networkScriptsDir = (String) params.get("network.scripts.dir");
 -        if (networkScriptsDir == null) {
 -            networkScriptsDir = getDefaultNetworkScriptsDir();
 -        }
 -
 -        String storageScriptsDir = (String) params.get("storage.scripts.dir");
 -        if (storageScriptsDir == null) {
 -            storageScriptsDir = getDefaultStorageScriptsDir();
 -        }
 -
 -        if (!success) {
 -            return false;
 -        }
 -
 -        _host = (String) params.get("host");
 -        if (_host == null) {
 -            _host = "localhost";
 -        }
 -
 -        _dcId = (String) params.get("zone");
 -        if (_dcId == null) {
 -            _dcId = "default";
 -        }
 -
 -        _pod = (String) params.get("pod");
 -        if (_pod == null) {
 -            _pod = "default";
 -        }
 -
 -        _clusterId = (String) params.get("cluster");
 -
 -        _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
 -        if (_modifyVlanPath == null) {
 -            throw new ConfigurationException("Unable to find modifyvlan.sh");
 -        }
 -
 -        _versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh");
 -        if (_versionstringpath == null) {
 -            throw new ConfigurationException("Unable to find versions.sh");
 -        }
 -
 -        _patchdomrPath = Script.findScript(kvmScriptsDir + "/patch/",
 -                "rundomrpre.sh");
 -        if (_patchdomrPath == null) {
 -            throw new ConfigurationException("Unable to find rundomrpre.sh");
 -        }
 -
 -        _heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh");
 -        if (_heartBeatPath == null) {
 -            throw new ConfigurationException("Unable to find kvmheartbeat.sh");
 -        }
 -
 -        _createvmPath = Script.findScript(storageScriptsDir, "createvm.sh");
 -        if (_createvmPath == null) {
 -            throw new ConfigurationException("Unable to find the createvm.sh");
 -        }
 -
 -        _manageSnapshotPath = Script.findScript(storageScriptsDir,
 -                "managesnapshot.sh");
 -        if (_manageSnapshotPath == null) {
 -            throw new ConfigurationException(
 -                    "Unable to find the managesnapshot.sh");
 -        }
 -
 -        _createTmplPath = Script
 -                .findScript(storageScriptsDir, "createtmplt.sh");
 -        if (_createTmplPath == null) {
 -            throw new ConfigurationException(
 -                    "Unable to find the createtmplt.sh");
 -        }
 -
 -        _securityGroupPath = Script.findScript(networkScriptsDir,
 -                "security_group.py");
 -        if (_securityGroupPath == null) {
 -            throw new ConfigurationException(
 -                    "Unable to find the security_group.py");
 -        }
 -
 -        _networkUsagePath = Script.findScript("scripts/network/domr/",
 -                "networkUsage.sh");
 -        if (_networkUsagePath == null) {
 -            throw new ConfigurationException(
 -                    "Unable to find the networkUsage.sh");
 -        }
 -
 -        String value = (String) params.get("developer");
 -        boolean isDeveloper = Boolean.parseBoolean(value);
 -
 -        if (isDeveloper) {
 -            params.putAll(getDeveloperProperties());
 -        }
 -
 -        _pool = (String) params.get("pool");
 -        if (_pool == null) {
 -            _pool = "/root";
 -        }
 -
 -        String instance = (String) params.get("instance");
 -
 -        _hypervisorType = (String) params.get("hypervisor.type");
 -        if (_hypervisorType == null) {
 -            _hypervisorType = "kvm";
 -        }
 -
 -        _hypervisorURI = (String) params.get("hypervisor.uri");
 -        if (_hypervisorURI == null) {
 -            _hypervisorURI = "qemu:///system";
 -        }
 -        String startMac = (String) params.get("private.macaddr.start");
 -        if (startMac == null) {
 -            startMac = "00:16:3e:77:e2:a0";
 -        }
 -
 -        String startIp = (String) params.get("private.ipaddr.start");
 -        if (startIp == null) {
 -            startIp = "192.168.166.128";
 -        }
 -
 -        _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh");
 -        if (_pingTestPath == null) {
 -            throw new ConfigurationException("Unable to find the pingtest.sh");
 -        }
 -
 -        _linkLocalBridgeName = (String) params.get("private.bridge.name");
 -        if (_linkLocalBridgeName == null) {
 -            if (isDeveloper) {
 -                _linkLocalBridgeName = "cloud-" + instance + "-0";
 -            } else {
 -                _linkLocalBridgeName = "cloud0";
 -            }
 -        }
 -
 -        _publicBridgeName = (String) params.get("public.network.device");
 -        if (_publicBridgeName == null) {
 -            _publicBridgeName = "cloudbr0";
 -        }
 -
 -        _privBridgeName = (String) params.get("private.network.device");
 -        if (_privBridgeName == null) {
 -            _privBridgeName = "cloudbr1";
 -        }
 -
 -        _guestBridgeName = (String) params.get("guest.network.device");
 -        if (_guestBridgeName == null) {
 -            _guestBridgeName = _privBridgeName;
 -        }
 -
 -        _privNwName = (String) params.get("private.network.name");
 -        if (_privNwName == null) {
 -            if (isDeveloper) {
 -                _privNwName = "cloud-" + instance + "-private";
 -            } else {
 -                _privNwName = "cloud-private";
 -            }
 -        }
 -
 -        _localStoragePath = (String) params.get("local.storage.path");
 -        if (_localStoragePath == null) {
 -            _localStoragePath = "/var/lib/libvirt/images/";
 -        }
 -
 -        _localStorageUUID = (String) params.get("local.storage.uuid");
 -        if (_localStorageUUID == null) {
 -            _localStorageUUID = UUID.randomUUID().toString();
 -            params.put("local.storage.uuid", _localStorageUUID);
 -        }
 -
 -        value = (String) params.get("scripts.timeout");
 -        _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;
 -
 -        value = (String) params.get("stop.script.timeout");
 -        _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000;
 -
 -        value = (String) params.get("cmds.timeout");
 -        _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000;
 -
 -        value = (String) params.get("host.reserved.mem.mb");
 -        _dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024;
 -
 -        value = (String) params.get("debug.mode");
 -
 -        LibvirtConnection.initialize(_hypervisorURI);
 -        Connect conn = null;
 -        try {
 -            conn = LibvirtConnection.getConnection();
 -        } catch (LibvirtException e) {
 -            throw new CloudRuntimeException(e.getMessage());
 -        }
 -
 -        /* Does node support HVM guest? If not, exit */
 -        if (!IsHVMEnabled(conn)) {
 -            throw new ConfigurationException(
 -                    "NO HVM support on this machine, pls make sure: "
 -                            + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. "
 -                            + "2. kvm modules is installed");
 -        }
 -
 -        _hypervisorPath = getHypervisorPath(conn);
 -        try {
 -            _hvVersion = conn.getVersion();
 -            _hvVersion = (_hvVersion % 1000000) / 1000;
 -        } catch (LibvirtException e) {
 -
 -        }
 -
 -        String[] info = NetUtils.getNetworkParams(_privateNic);
 -
 -        _monitor = new KVMHAMonitor(null, info[0], _heartBeatPath);
 -        Thread ha = new Thread(_monitor);
 -        ha.start();
 -
 -        _storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor);
 -
 -        _sysvmISOPath = (String) params.get("systemvm.iso.path");
 -        if (_sysvmISOPath == null) {
 -            String[] isoPaths = { "/usr/lib64/cloud/agent/vms/systemvm.iso",
 -                    "/usr/lib/cloud/agent/vms/systemvm.iso" };
 -            for (String isoPath : isoPaths) {
 -                if (_storage.exists(isoPath)) {
 -                    _sysvmISOPath = isoPath;
 -                    break;
 -                }
 -            }
 -            if (_sysvmISOPath == null) {
 -                s_logger.debug("Can't find system vm ISO");
 -            }
 -        }
 -
 -        try {
 -            createControlNetwork(conn);
 -        } catch (LibvirtException e) {
 -            throw new ConfigurationException(e.getMessage());
 -        }
 -
 -        _pifs = getPifs();
 -        if (_pifs.first() == null) {
 -            s_logger.debug("Failed to get private nic name");
 -            throw new ConfigurationException("Failed to get private nic name");
 -        }
 -
 -        if (_pifs.second() == null) {
 -            s_logger.debug("Failed to get public nic name");
 -            throw new ConfigurationException("Failed to get public nic name");
 -        }
 -        s_logger.debug("Found pif: " + _pifs.first() + " on " + _privBridgeName
 -                + ", pif: " + _pifs.second() + " on " + _publicBridgeName);
 -
 -        _can_bridge_firewall = can_bridge_firewall(_pifs.second());
 -
 -        _localGateway = Script
 -                .runSimpleBashScript("ip route |grep default|awk '{print $3}'");
 -        if (_localGateway == null) {
 -            s_logger.debug("Failed to found the local gateway");
 -        }
 -
 -        _mountPoint = (String) params.get("mount.path");
 -        if (_mountPoint == null) {
 -            _mountPoint = "/mnt";
 -        }
 -        
 -        value = (String) params.get("vm.migrate.speed");
 -        _migrateSpeed = NumbersUtil.parseInt(value, -1);
 -        if (_migrateSpeed == -1) {
 -            //get guest network device speed
 -            _migrateSpeed = 0;
 -            String speed = Script.runSimpleBashScript("ethtool " + _pifs.second() + " |grep Speed | cut -d \\  -f 2");
 -            if (speed != null) {
 -                String[] tokens = speed.split("M");
 -                if (tokens.length == 2) {
 -                    try {
 -                        _migrateSpeed = Integer.parseInt(tokens[0]);
 -                    } catch (Exception e) {
 -                        
 -                    }
 -                    s_logger.debug("device " + _pifs.second() + " has speed: " + String.valueOf(_migrateSpeed));
 -                }
 -            }
 -            params.put("vm.migrate.speed", String.valueOf(_migrateSpeed));
 -        }
 -        saveProperties(params);
 -
 -        return true;
 -    }
 -
 -    private Pair<String, String> getPifs() {
 -        /* get pifs from bridge */
 -        String pubPif = null;
 -        String privPif = null;
 -        String vlan = null;
 -        if (_publicBridgeName != null) {
 -            pubPif = Script.runSimpleBashScript("brctl show | grep "
 -                    + _publicBridgeName + " | awk '{print $4}'");
 -            vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pubPif);
 -            if (vlan != null && !vlan.isEmpty()) {
 -                pubPif = Script
 -                        .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
 -                                + pubPif + " | awk {'print $2'}");
 -            }
 -        }
 -        if (_guestBridgeName != null) {
 -            privPif = Script.runSimpleBashScript("brctl show | grep "
 -                    + _guestBridgeName + " | awk '{print $4}'");
 -            vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + privPif);
 -            if (vlan != null && !vlan.isEmpty()) {
 -                privPif = Script
 -                        .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
 -                                + privPif + " | awk {'print $2'}");
 -            }
 -        }
 -        return new Pair<String, String>(privPif, pubPif);
 -    }
 -
 -    private boolean checkNetwork(String networkName) {
 -        if (networkName == null) {
 -            return true;
 -        }
 -
 -        String name = Script.runSimpleBashScript("brctl show | grep "
 -                + networkName + " | awk '{print $4}'");
 -        if (name == null) {
 -            return false;
 -        } else {
 -            return true;
 -        }
 -    }
 -
 -    private String getVnetId(String vnetId) {
 -        return vnetId;
 -    }
 -
 -    private void patchSystemVm(String cmdLine, String dataDiskPath,
 -            String vmName) throws InternalErrorException {
 -        String result;
 -        final Script command = new Script(_patchdomrPath, _timeout, s_logger);
 -        command.add("-l", vmName);
 -        command.add("-t", "all");
 -        command.add("-d", dataDiskPath);
 -        command.add("-p", cmdLine.replaceAll(" ", "%"));
 -        result = command.execute();
 -        if (result != null) {
 -            throw new InternalErrorException(result);
 -        }
 -    }
 -
 -    boolean isDirectAttachedNetwork(String type) {
 -        if ("untagged".equalsIgnoreCase(type)) {
 -            return true;
 -        } else {
 -            try {
 -                Long.valueOf(type);
 -            } catch (NumberFormatException e) {
 -                return true;
 -            }
 -            return false;
 -        }
 -    }
 -
 -    protected String startDomain(Connect conn, String vmName, String domainXML)
 -            throws LibvirtException, InternalErrorException {
 -        /* No duplicated vm, we will success, or failed */
 -        boolean failed = false;
 -        Domain dm = null;
 -        try {
 -            dm = conn.domainDefineXML(domainXML);
 -        } catch (final LibvirtException e) {
 -            /* Duplicated defined vm */
 -            s_logger.warn("Failed to define domain " + vmName + ": "
 -                    + e.getMessage());
 -            failed = true;
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (final LibvirtException e) {
 -
 -            }
 -        }
 -
 -        /* If failed, undefine the vm */
 -        Domain dmOld = null;
 -        Domain dmNew = null;
 -        try {
 -            if (failed) {
 -                dmOld = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                        .getBytes()));
 -                dmOld.undefine();
 -                dmNew = conn.domainDefineXML(domainXML);
 -            }
 -        } catch (final LibvirtException e) {
 -            s_logger.warn("Failed to define domain (second time) " + vmName
 -                    + ": " + e.getMessage());
 -            throw e;
 -        } catch (Exception e) {
 -            s_logger.warn("Failed to define domain (second time) " + vmName
 -                    + ": " + e.getMessage());
 -            throw new InternalErrorException(e.toString());
 -        } finally {
 -            try {
 -                if (dmOld != null) {
 -                    dmOld.free();
 -                }
 -                if (dmNew != null) {
 -                    dmNew.free();
 -                }
 -            } catch (final LibvirtException e) {
 -
 -            }
 -        }
 -
 -        /* Start the VM */
 -        try {
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            dm.create();
 -        } catch (LibvirtException e) {
 -            s_logger.warn("Failed to start domain: " + vmName + ": "
 -                    + e.getMessage());
 -            throw e;
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -            } catch (final LibvirtException e) {
 -
 -            }
 -        }
 -        return null;
 -    }
 -
 -    @Override
 -    public boolean stop() {
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            conn.close();
 -        } catch (LibvirtException e) {
 -        }
 -
 -        return true;
 -    }
 -
 -    public static void main(String[] args) {
 -        s_logger.addAppender(new org.apache.log4j.ConsoleAppender(
 -                new org.apache.log4j.PatternLayout(), "System.out"));
 -        LibvirtComputingResource test = new LibvirtComputingResource();
 -        Map<String, Object> params = new HashMap<String, Object>();
 -        try {
 -            test.configure("test", params);
 -        } catch (ConfigurationException e) {
 -            System.out.println(e.getMessage());
 -            e.printStackTrace();
 -        }
 -        String result = null;
 -        // String result = test.startDomainRouter("domr1",
 -        // "/var/lib/images/centos.5-4.x86-64/centos-small.img", 128, "0064",
 -        // "02:00:30:00:01:01", "00:16:3e:77:e2:a1", "02:00:30:00:64:01");
 -        boolean created = (result == null);
 -        s_logger.info("Domain " + (created ? " " : " not ") + " created");
 -
 -        s_logger.info("Rule " + (created ? " " : " not ") + " created");
 -        test.stop();
 -    }
 -
 -    @Override
 -    public Answer executeRequest(Command cmd) {
 -
 -        try {
 -            if (cmd instanceof StopCommand) {
 -                return execute((StopCommand) cmd);
 -            } else if (cmd instanceof GetVmStatsCommand) {
 -                return execute((GetVmStatsCommand) cmd);
 -            } else if (cmd instanceof RebootRouterCommand) {
 -                return execute((RebootRouterCommand) cmd);
 -            } else if (cmd instanceof RebootCommand) {
 -                return execute((RebootCommand) cmd);
 -            } else if (cmd instanceof GetHostStatsCommand) {
 -                return execute((GetHostStatsCommand) cmd);
 -            } else if (cmd instanceof CheckStateCommand) {
 -                return executeRequest(cmd);
 -            } else if (cmd instanceof CheckHealthCommand) {
 -                return execute((CheckHealthCommand) cmd);
 -            } else if (cmd instanceof PrepareForMigrationCommand) {
 -                return execute((PrepareForMigrationCommand) cmd);
 -            } else if (cmd instanceof MigrateCommand) {
 -                return execute((MigrateCommand) cmd);
 -            } else if (cmd instanceof PingTestCommand) {
 -                return execute((PingTestCommand) cmd);
 -            } else if (cmd instanceof CheckVirtualMachineCommand) {
 -                return execute((CheckVirtualMachineCommand) cmd);
 -            } else if (cmd instanceof ReadyCommand) {
 -                return execute((ReadyCommand) cmd);
 -            } else if (cmd instanceof AttachIsoCommand) {
 -                return execute((AttachIsoCommand) cmd);
 -            } else if (cmd instanceof AttachVolumeCommand) {
 -                return execute((AttachVolumeCommand) cmd);
 -            } else if (cmd instanceof StopCommand) {
 -                return execute((StopCommand) cmd);
 -            } else if (cmd instanceof CheckConsoleProxyLoadCommand) {
 -                return execute((CheckConsoleProxyLoadCommand) cmd);
 -            } else if (cmd instanceof WatchConsoleProxyLoadCommand) {
 -                return execute((WatchConsoleProxyLoadCommand) cmd);
 -            } else if (cmd instanceof GetVncPortCommand) {
 -                return execute((GetVncPortCommand) cmd);
 -            } else if (cmd instanceof ModifySshKeysCommand) {
 -                return execute((ModifySshKeysCommand) cmd);
 -            } else if (cmd instanceof MaintainCommand) {
 -                return execute((MaintainCommand) cmd);
 -            } else if (cmd instanceof CreateCommand) {
 -                return execute((CreateCommand) cmd);
 -            } else if (cmd instanceof DestroyCommand) {
 -                return execute((DestroyCommand) cmd);
 -            } else if (cmd instanceof PrimaryStorageDownloadCommand) {
 -                return execute((PrimaryStorageDownloadCommand) cmd);
 -            } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
 -                return execute((CreatePrivateTemplateFromVolumeCommand) cmd);
 -            } else if (cmd instanceof GetStorageStatsCommand) {
 -                return execute((GetStorageStatsCommand) cmd);
 -            } else if (cmd instanceof ManageSnapshotCommand) {
 -                return execute((ManageSnapshotCommand) cmd);
 -            } else if (cmd instanceof BackupSnapshotCommand) {
 -                return execute((BackupSnapshotCommand) cmd);
 -            } else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
 -                return execute((CreateVolumeFromSnapshotCommand) cmd);
 -            } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
 -                return execute((CreatePrivateTemplateFromSnapshotCommand) cmd);
 -            } else if (cmd instanceof UpgradeSnapshotCommand) {
 -                return execute((UpgradeSnapshotCommand) cmd);
 -            } else if (cmd instanceof CreateStoragePoolCommand) {
 -                return execute((CreateStoragePoolCommand) cmd);
 -            } else if (cmd instanceof ModifyStoragePoolCommand) {
 -                return execute((ModifyStoragePoolCommand) cmd);
 -            } else if (cmd instanceof SecurityGroupRulesCmd) {
 -                return execute((SecurityGroupRulesCmd) cmd);
 -            } else if (cmd instanceof DeleteStoragePoolCommand) {
 -                return execute((DeleteStoragePoolCommand) cmd);
 -            } else if (cmd instanceof FenceCommand) {
 -                return execute((FenceCommand) cmd);
 -            } else if (cmd instanceof StartCommand) {
 -                return execute((StartCommand) cmd);
 -            } else if (cmd instanceof IpAssocCommand) {
 -                return execute((IpAssocCommand) cmd);
 -            } else if (cmd instanceof NetworkElementCommand) {
 -                return _virtRouterResource.executeRequest(cmd);
 -            } else if (cmd instanceof CheckSshCommand) {
 -                return execute((CheckSshCommand) cmd);
 -            } else if (cmd instanceof NetworkUsageCommand) {
 -                return execute((NetworkUsageCommand) cmd);
 -            } else if (cmd instanceof NetworkRulesSystemVmCommand) {
 -                return execute((NetworkRulesSystemVmCommand) cmd);
 -            } else if (cmd instanceof CleanupNetworkRulesCmd) {
 -                return execute((CleanupNetworkRulesCmd) cmd);
 -            } else if (cmd instanceof CopyVolumeCommand) {
 -                return execute((CopyVolumeCommand) cmd);
 -            } else if (cmd instanceof CheckNetworkCommand) {
 -                return execute((CheckNetworkCommand) cmd);
 -            } else {
 -                s_logger.warn("Unsupported command ");
 -                return Answer.createUnsupportedCommandAnswer(cmd);
 -            }
 -        } catch (final IllegalArgumentException e) {
 -            return new Answer(cmd, false, e.getMessage());
 -        }
 -    }
 -
 -    private CheckNetworkAnswer execute(CheckNetworkCommand cmd) {
 -        List<PhysicalNetworkSetupInfo> phyNics = cmd
 -                .getPhysicalNetworkInfoList();
 -        String errMsg = null;
 -        for (PhysicalNetworkSetupInfo nic : phyNics) {
 -            if (!checkNetwork(nic.getGuestNetworkName())) {
 -                errMsg = "Can not find network: " + nic.getGuestNetworkName();
 -                break;
 -            } else if (!checkNetwork(nic.getPrivateNetworkName())) {
 -                errMsg = "Can not find network: " + nic.getPrivateNetworkName();
 -                break;
 -            } else if (!checkNetwork(nic.getPublicNetworkName())) {
 -                errMsg = "Can not find network: " + nic.getPublicNetworkName();
 -                break;
 -            }
 -        }
 -
 -        if (errMsg != null) {
 -            return new CheckNetworkAnswer(cmd, false, errMsg);
 -        } else {
 -            return new CheckNetworkAnswer(cmd, true, null);
 -        }
 -    }
 -
 -    private CopyVolumeAnswer execute(CopyVolumeCommand cmd) {
 -        boolean copyToSecondary = cmd.toSecondaryStorage();
 -        String volumePath = cmd.getVolumePath();
 -        StorageFilerTO pool = cmd.getPool();
 -        String secondaryStorageUrl = cmd.getSecondaryStorageURL();
 -        KVMStoragePool secondaryStoragePool = null;
 -        try {
 -            KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool
 -                    .getUuid());
 -            String volumeName = UUID.randomUUID().toString();
 -
 -            if (copyToSecondary) {
 -                String destVolumeName = volumeName + ".qcow2";
 -                KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd
 -                        .getVolumePath());
 -                String volumeDestPath = "/volumes/" + cmd.getVolumeId()
 -                        + File.separator;
 -                secondaryStoragePool = _storagePoolMgr
 -                        .getStoragePoolByURI(secondaryStorageUrl);
 -                secondaryStoragePool.createFolder(volumeDestPath);
 -                secondaryStoragePool.delete();
 -                secondaryStoragePool = _storagePoolMgr
 -                        .getStoragePoolByURI(secondaryStorageUrl
 -                                + volumeDestPath);
 -                _storagePoolMgr.copyPhysicalDisk(volume, destVolumeName,
 -                        secondaryStoragePool);
 -                return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
 -            } else {
 -                volumePath = "/volumes/" + cmd.getVolumeId() + File.separator;
 -                secondaryStoragePool = _storagePoolMgr
 -                        .getStoragePoolByURI(secondaryStorageUrl + volumePath);
 -                KVMPhysicalDisk volume = secondaryStoragePool
 -                        .getPhysicalDisk(cmd.getVolumePath() + ".qcow2");
 -                _storagePoolMgr.copyPhysicalDisk(volume, volumeName,
 -                        primaryPool);
 -                return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
 -            }
 -        } catch (CloudRuntimeException e) {
 -            return new CopyVolumeAnswer(cmd, false, e.toString(), null, null);
 -        } finally {
 -            if (secondaryStoragePool != null) {
 -                secondaryStoragePool.delete();
 -            }
 -        }
 -    }
 -
 -    protected Answer execute(DeleteStoragePoolCommand cmd) {
 -        try {
 -            _storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid());
 -            return new Answer(cmd);
 -        } catch (CloudRuntimeException e) {
 -            return new Answer(cmd, false, e.toString());
 -        }
 -    }
 -
 -    protected FenceAnswer execute(FenceCommand cmd) {
 -        ExecutorService executors = Executors.newSingleThreadExecutor();
 -        List<NfsStoragePool> pools = _monitor.getStoragePools();
 -        KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp());
 -        Future<Boolean> future = executors.submit(ha);
 -        try {
 -            Boolean result = future.get();
 -            if (result) {
 -                return new FenceAnswer(cmd, false, "Heart is still beating...");
 -            } else {
 -                return new FenceAnswer(cmd);
 -            }
 -        } catch (InterruptedException e) {
 -            s_logger.warn("Unable to fence", e);
 -            return new FenceAnswer(cmd, false, e.getMessage());
 -        } catch (ExecutionException e) {
 -            s_logger.warn("Unable to fence", e);
 -            return new FenceAnswer(cmd, false, e.getMessage());
 -        }
 -
 -    }
 -
 -    protected Storage.StorageResourceType getStorageResourceType() {
 -        return Storage.StorageResourceType.STORAGE_POOL;
 -    }
 -
 -    protected Answer execute(CreateCommand cmd) {
 -        StorageFilerTO pool = cmd.getPool();
 -        DiskProfile dskch = cmd.getDiskCharacteristics();
 -        KVMPhysicalDisk BaseVol = null;
 -        KVMStoragePool primaryPool = null;
 -        KVMPhysicalDisk vol = null;
 -        long disksize;
 -        try {
 -            primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid());
 -
 -            if (cmd.getTemplateUrl() != null) {
 -
 -                BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl());
 -                vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID
 -                        .randomUUID().toString(), primaryPool);
 -
 -                if (vol == null) {
 -                    return new Answer(cmd, false,
 -                            " Can't create storage volume on storage pool");
 -                }
 -                disksize = vol.getSize();
 -            } else {
 -                disksize = dskch.getSize();
 -                vol = primaryPool.createPhysicalDisk(UUID.randomUUID()
 -                        .toString(), dskch.getSize());
 -            }
 -            VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(),
 -                    pool.getType(), pool.getUuid(), pool.getPath(),
 -                    vol.getName(), vol.getName(), disksize, null);
 -            return new CreateAnswer(cmd, volume);
 -        } catch (CloudRuntimeException e) {
 -            s_logger.debug("Failed to create volume: " + e.toString());
 -            return new CreateAnswer(cmd, e);
 -        }
 -    }
 -
 -    public Answer execute(DestroyCommand cmd) {
 -        VolumeTO vol = cmd.getVolume();
 -
 -        try {
 -            KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol
 -                    .getPoolUuid());
 -            pool.deletePhysicalDisk(vol.getPath());
 -
 -            return new Answer(cmd, true, "Success");
 -        } catch (CloudRuntimeException e) {
 -            s_logger.debug("Failed to delete volume: " + e.toString());
 -            return new Answer(cmd, false, e.toString());
 -        }
 -    }
 -
 -    private String getVlanIdFromBridge(String brName) {
 -        OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser();
 -        final Script cmd = new Script("/bin/bash", s_logger);
 -        cmd.add("-c");
 -        cmd.add("vlanid=$(brctl show |grep " + brName
 -                + " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid");
 -        String result = cmd.execute(vlanIdParser);
 -        if (result != null) {
 -            return null;
 -        }
 -        String vlanId = vlanIdParser.getLine();
 -        if (vlanId.equalsIgnoreCase("")) {
 -            return null;
 -        } else {
 -            return vlanId;
 -        }
 -    }
 -
 -    private void VifHotPlug(Connect conn, String vmName, String vlanId,
 -            String macAddr) throws InternalErrorException, LibvirtException {
 -        NicTO nicTO = new NicTO();
 -        nicTO.setMac(macAddr);
 -        nicTO.setType(TrafficType.Public);
 -        if (vlanId == null) {
 -            nicTO.setBroadcastType(BroadcastDomainType.Native);
 -        } else {
 -            nicTO.setBroadcastType(BroadcastDomainType.Vlan);
 -            nicTO.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanId));
 -        }
 -
 -        InterfaceDef nic = createVif(conn, nicTO, InterfaceDef.nicModel.VIRTIO);
 -        Domain vm = getDomain(conn, vmName);
 -        vm.attachDevice(nic.toString());
 -    }
 -
 -    public Answer execute(IpAssocCommand cmd) {
 -        String routerName = cmd
 -                .getAccessDetail(NetworkElementCommand.ROUTER_NAME);
 -        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 -        String[] results = new String[cmd.getIpAddresses().length];
 -        Connect conn;
 -        try {
 -            conn = LibvirtConnection.getConnection();
 -            List<InterfaceDef> nics = getInterfaces(conn, routerName);
 -            Map<String, Integer> vlanAllocatedToVM = new HashMap<String, Integer>();
 -            Integer nicPos = 0;
 -            for (InterfaceDef nic : nics) {
 -                if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) {
 -                    vlanAllocatedToVM.put("LinkLocal", nicPos);
 -                } else {
 -                    String vlanId = getVlanIdFromBridge(nic.getBrName());
 -                    if (vlanId != null) {
 -                        vlanAllocatedToVM.put(vlanId, nicPos);
 -                    } else {
 -                        vlanAllocatedToVM.put(Vlan.UNTAGGED, nicPos);
 -                    }
 -                }
 -                nicPos++;
 -            }
 -            IpAddressTO[] ips = cmd.getIpAddresses();
 -            int i = 0;
 -            String result = null;
 -            int nicNum = 0;
 -            for (IpAddressTO ip : ips) {
 -                if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) {
 -                    /* plug a vif into router */
 -                    VifHotPlug(conn, routerName, ip.getVlanId(),
 -                            ip.getVifMacAddress());
 -                    vlanAllocatedToVM.put(ip.getVlanId(), nicPos++);
 -                }
 -                nicNum = vlanAllocatedToVM.get(ip.getVlanId());
 -                networkUsage(routerIp, "addVif", "eth" + nicNum);
 -                result = _virtRouterResource.assignPublicIpAddress(routerName,
 -                        routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(),
 -                        ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(),
 -                        ip.getVlanNetmask(), ip.getVifMacAddress(),
 -                        ip.getGuestIp(), nicNum);
 -
 -                if (result != null) {
 -                    results[i++] = IpAssocAnswer.errorResult;
 -                } else {
 -                    results[i++] = ip.getPublicIp() + " - success";
 -                    ;
 -                }
 -            }
 -            return new IpAssocAnswer(cmd, results);
 -        } catch (LibvirtException e) {
 -            return new IpAssocAnswer(cmd, results);
 -        } catch (InternalErrorException e) {
 -            return new IpAssocAnswer(cmd, results);
 -        }
 -    }
 -
 -    protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) {
 -        String snapshotName = cmd.getSnapshotName();
 -        String snapshotPath = cmd.getSnapshotPath();
 -        String vmName = cmd.getVmName();
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            DomainInfo.DomainState state = null;
 -            Domain vm = null;
 -            if (vmName != null) {
 -                try {
 -                    vm = getDomain(conn, cmd.getVmName());
 -                    state = vm.getInfo().state;
 -                } catch (LibvirtException e) {
 -
 -                }
 -            }
 -
 -            KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
 -                    .getPool().getUuid());
 -            KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd
 -                    .getVolumePath());
 -            if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
 -                    && !primaryPool.isExternalSnapshot()) {
 -                String vmUuid = vm.getUUIDString();
 -                Object[] args = new Object[] { snapshotName, vmUuid };
 -                String snapshot = SnapshotXML.format(args);
 -                s_logger.debug(snapshot);
 -                if (cmd.getCommandSwitch().equalsIgnoreCase(
 -                        ManageSnapshotCommand.CREATE_SNAPSHOT)) {
 -                    vm.snapshotCreateXML(snapshot);
 -                } else {
 -                    DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
 -                    snap.delete(0);
 -                }
 -
 -                /*
 -                 * libvirt on RHEL6 doesn't handle resume event emitted from
 -                 * qemu
 -                 */
 -                vm = getDomain(conn, cmd.getVmName());
 -                state = vm.getInfo().state;
 -                if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
 -                    vm.resume();
 -                }
 -            } else {
 -
 -                /* VM is not running, create a snapshot by ourself */
 -                final Script command = new Script(_manageSnapshotPath,
 -                        _cmdsTimeout, s_logger);
 -                if (cmd.getCommandSwitch().equalsIgnoreCase(
 -                        ManageSnapshotCommand.CREATE_SNAPSHOT)) {
 -                    command.add("-c", disk.getPath());
 -                } else {
 -                    command.add("-d", snapshotPath);
 -                }
 -
 -                command.add("-n", snapshotName);
 -                String result = command.execute();
 -                if (result != null) {
 -                    s_logger.debug("Failed to manage snapshot: " + result);
 -                    return new ManageSnapshotAnswer(cmd, false,
 -                            "Failed to manage snapshot: " + result);
 -                }
 -            }
 -            return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(),
 -                    disk.getPath() + File.separator + snapshotName, true, null);
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to manage snapshot: " + e.toString());
 -            return new ManageSnapshotAnswer(cmd, false,
 -                    "Failed to manage snapshot: " + e.toString());
 -        }
 -
 -    }
 -
 -    protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
 -        Long dcId = cmd.getDataCenterId();
 -        Long accountId = cmd.getAccountId();
 -        Long volumeId = cmd.getVolumeId();
 -        String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl();
 -        String snapshotName = cmd.getSnapshotName();
 -        String snapshotPath = cmd.getVolumePath();
 -        String snapshotDestPath = null;
 -        String snapshotRelPath = null;
 -        String vmName = cmd.getVmName();
 -        KVMStoragePool secondaryStoragePool = null;
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -
 -            secondaryStoragePool = _storagePoolMgr
 -                    .getStoragePoolByURI(secondaryStoragePoolUrl);
 -
 -            String ssPmountPath = secondaryStoragePool.getLocalPath();
 -            snapshotRelPath = File.separator + "snapshots" + File.separator
 -                    + dcId + File.separator + accountId + File.separator
 -                    + volumeId;
 -
 -            snapshotDestPath = ssPmountPath + File.separator + "snapshots"
 -                    + File.separator + dcId + File.separator + accountId
 -                    + File.separator + volumeId;
 -            KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
 -                    .getPrimaryStoragePoolNameLabel());
 -            KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd
 -                    .getVolumePath());
 -            Script command = new Script(_manageSnapshotPath, _cmdsTimeout,
 -                    s_logger);
 -            command.add("-b", snapshotDisk.getPath());
 -            command.add("-n", snapshotName);
 -            command.add("-p", snapshotDestPath);
 -            command.add("-t", snapshotName);
 -            String result = command.execute();
 -            if (result != null) {
 -                s_logger.debug("Failed to backup snaptshot: " + result);
 -                return new BackupSnapshotAnswer(cmd, false, result, null, true);
 -            }
 -            /* Delete the snapshot on primary */
 -
 -            DomainInfo.DomainState state = null;
 -            Domain vm = null;
 -            if (vmName != null) {
 -                try {
 -                    vm = getDomain(conn, cmd.getVmName());
 -                    state = vm.getInfo().state;
 -                } catch (LibvirtException e) {
 -
 -                }
 -            }
 -
 -            KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd
 -                    .getPool().getUuid());
 -            if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
 -                    && !primaryStorage.isExternalSnapshot()) {
 -                String vmUuid = vm.getUUIDString();
 -                Object[] args = new Object[] { snapshotName, vmUuid };
 -                String snapshot = SnapshotXML.format(args);
 -                s_logger.debug(snapshot);
 -                DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
 -                snap.delete(0);
 -
 -                /*
 -                 * libvirt on RHEL6 doesn't handle resume event emitted from
 -                 * qemu
 -                 */
 -                vm = getDomain(conn, cmd.getVmName());
 -                state = vm.getInfo().state;
 -                if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
 -                    vm.resume();
 -                }
 -            } else {
 -                command = new Script(_manageSnapshotPath, _cmdsTimeout,
 -                        s_logger);
 -                command.add("-d", snapshotDisk.getPath());
 -                command.add("-n", snapshotName);
 -                result = command.execute();
 -                if (result != null) {
 -                    s_logger.debug("Failed to backup snapshot: " + result);
 -                    return new BackupSnapshotAnswer(cmd, false,
 -                            "Failed to backup snapshot: " + result, null, true);
 -                }
 -            }
 -        } catch (LibvirtException e) {
 -            return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
 -                    true);
 -        } catch (CloudRuntimeException e) {
 -            return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
 -                    true);
 -        } finally {
 -            if (secondaryStoragePool != null) {
 -                secondaryStoragePool.delete();
 -            }
 -        }
 -        return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath
 -                + File.separator + snapshotName, true);
 -    }
 -
 -    protected DeleteSnapshotBackupAnswer execute(
 -            final DeleteSnapshotBackupCommand cmd) {
 -        Long dcId = cmd.getDataCenterId();
 -        Long accountId = cmd.getAccountId();
 -        Long volumeId = cmd.getVolumeId();
 -        KVMStoragePool secondaryStoragePool = null;
 -        try {
 -            secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
 -                    .getSecondaryStorageUrl());
 -
 -            String ssPmountPath = secondaryStoragePool.getLocalPath();
 -            String snapshotDestPath = ssPmountPath + File.separator
 -                    + "snapshots" + File.separator + dcId + File.separator
 -                    + accountId + File.separator + volumeId;
 -
 -            final Script command = new Script(_manageSnapshotPath,
 -                    _cmdsTimeout, s_logger);
 -            command.add("-d", snapshotDestPath);
 -            command.add("-n", cmd.getSnapshotName());
 -
 -            command.execute();
 -        } catch (CloudRuntimeException e) {
 -            return new DeleteSnapshotBackupAnswer(cmd, false, e.toString());
 -        } finally {
 -            if (secondaryStoragePool != null) {
 -                secondaryStoragePool.delete();
 -            }
 -        }
 -        return new DeleteSnapshotBackupAnswer(cmd, true, null);
 -    }
 -
 -    protected Answer execute(DeleteSnapshotsDirCommand cmd) {
 -        Long dcId = cmd.getDcId();
 -        Long accountId = cmd.getAccountId();
 -        Long volumeId = cmd.getVolumeId();
 -        KVMStoragePool secondaryStoragePool = null;
 -        try {
 -            secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
 -                    .getSecondaryStorageUrl());
 -
 -            String ssPmountPath = secondaryStoragePool.getLocalPath();
 -            String snapshotDestPath = ssPmountPath + File.separator
 -                    + "snapshots" + File.separator + dcId + File.separator
 -                    + accountId + File.separator + volumeId;
 -
 -            final Script command = new Script(_manageSnapshotPath,
 -                    _cmdsTimeout, s_logger);
 -            command.add("-d", snapshotDestPath);
 -            command.add("-f");
 -            command.execute();
 -        } catch (CloudRuntimeException e) {
 -            return new Answer(cmd, false, e.toString());
 -        } finally {
 -            if (secondaryStoragePool != null) {
 -                secondaryStoragePool.delete();
 -            }
 -
 -        }
 -        return new Answer(cmd, true, null);
 -    }
 -
 -    protected CreateVolumeFromSnapshotAnswer execute(
 -            final CreateVolumeFromSnapshotCommand cmd) {
 -        try {
 -
 -            String snapshotPath = cmd.getSnapshotUuid();
 -            int index = snapshotPath.lastIndexOf("/");
 -            snapshotPath = snapshotPath.substring(0, index);
 -            KVMStoragePool secondaryPool = _storagePoolMgr
 -                    .getStoragePoolByURI(cmd.getSecondaryStorageUrl()
 -                            + snapshotPath);
 -            KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd
 -                    .getSnapshotName());
 -
 -            String primaryUuid = cmd.getPrimaryStoragePoolNameLabel();
 -            KVMStoragePool primaryPool = _storagePoolMgr
 -                    .getStoragePool(primaryUuid);
 -            String volUuid = UUID.randomUUID().toString();
 -            KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot,
 -                    volUuid, primaryPool);
 -            return new CreateVolumeFromSnapshotAnswer(cmd, true, "",
 -                    disk.getName());
 -        } catch (CloudRuntimeException e) {
 -            return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(),
 -                    null);
 -        }
 -    }
 -
 -    protected Answer execute(final UpgradeSnapshotCommand cmd) {
 -
 -        return new Answer(cmd, true, "success");
 -    }
 -
 -    protected CreatePrivateTemplateAnswer execute(
 -            final CreatePrivateTemplateFromSnapshotCommand cmd) {
 -        String templateFolder = cmd.getAccountId() + File.separator
 -                + cmd.getNewTemplateId();
 -        String templateInstallFolder = "template/tmpl/" + templateFolder;
 -        String tmplName = UUID.randomUUID().toString();
 -        String tmplFileName = tmplName + ".qcow2";
 -        KVMStoragePool secondaryPool = null;
 -        KVMStoragePool snapshotPool = null;
 -        try {
 -            String snapshotPath = cmd.getSnapshotUuid();
 -            int index = snapshotPath.lastIndexOf("/");
 -            snapshotPath = snapshotPath.substring(0, index);
 -            snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd
 -                    .getSecondaryStorageUrl() + snapshotPath);
 -            KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd
 -                    .getSnapshotName());
 -
 -            secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd
 -                    .getSecondaryStorageUrl());
 -
 -            String templatePath = secondaryPool.getLocalPath() + File.separator
 -                    + templateInstallFolder;
 -
 -            _storage.mkdirs(templatePath);
 -
 -            String tmplPath = templateInstallFolder + File.separator
 -                    + tmplFileName;
 -            Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
 -            command.add("-t", templatePath);
 -            command.add("-n", tmplFileName);
 -            command.add("-f", snapshot.getPath());
 -            command.execute();
 -
 -            Map<String, Object> params = new HashMap<String, Object>();
 -            params.put(StorageLayer.InstanceConfigKey, _storage);
 -            Processor qcow2Processor = new QCOW2Processor();
 -            qcow2Processor.configure("QCOW2 Processor", params);
 -            FormatInfo info = qcow2Processor.process(templatePath, null,
 -                    tmplName);
 -
 -            TemplateLocation loc = new TemplateLocation(_storage, templatePath);
 -            loc.create(1, true, tmplName);
 -            loc.addFormat(info);
 -            loc.save();
 -
 -            return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath,
 -                    info.virtualSize, info.size, tmplName, info.format);
 -        } catch (ConfigurationException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
 -        } catch (InternalErrorException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
 -        } catch (IOException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
 -        } catch (CloudRuntimeException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
 -        } finally {
 -            if (secondaryPool != null) {
 -                secondaryPool.delete();
 -            }
 -            if (snapshotPool != null) {
 -                snapshotPool.delete();
 -            }
 -        }
 -    }
 -
 -    protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
 -        try {
 -            KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd
 -                    .getStorageId());
 -            return new GetStorageStatsAnswer(cmd, sp.getCapacity(),
 -                    sp.getUsed());
 -        } catch (CloudRuntimeException e) {
 -            return new GetStorageStatsAnswer(cmd, e.toString());
 -        }
 -    }
 -
 -    protected CreatePrivateTemplateAnswer execute(
 -            CreatePrivateTemplateFromVolumeCommand cmd) {
 -        String secondaryStorageURL = cmd.getSecondaryStorageUrl();
 -
 -        KVMStoragePool secondaryStorage = null;
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            String templateFolder = cmd.getAccountId() + File.separator
 -                    + cmd.getTemplateId() + File.separator;
 -            String templateInstallFolder = "/template/tmpl/" + templateFolder;
 -
 -            secondaryStorage = _storagePoolMgr
 -                    .getStoragePoolByURI(secondaryStorageURL);
 -
 -            KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
 -                    .getPrimaryStoragePoolNameLabel());
 -            KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
 -            String tmpltPath = secondaryStorage.getLocalPath() + File.separator
 -                    + templateInstallFolder;
 -            _storage.mkdirs(tmpltPath);
 -
 -            Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
 -            command.add("-f", disk.getPath());
 -            command.add("-t", tmpltPath);
 -            command.add("-n", cmd.getUniqueName() + ".qcow2");
 -
 -            String result = command.execute();
 -
 -            if (result != null) {
 -                s_logger.debug("failed to create template: " + result);
 -                return new CreatePrivateTemplateAnswer(cmd, false, result);
 -            }
 -
 -            Map<String, Object> params = new HashMap<String, Object>();
 -            params.put(StorageLayer.InstanceConfigKey, _storage);
 -            Processor qcow2Processor = new QCOW2Processor();
 -
 -            qcow2Processor.configure("QCOW2 Processor", params);
 -
 -            FormatInfo info = qcow2Processor.process(tmpltPath, null,
 -                    cmd.getUniqueName());
 -
 -            TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
 -            loc.create(1, true, cmd.getUniqueName());
 -            loc.addFormat(info);
 -            loc.save();
 -
 -            return new CreatePrivateTemplateAnswer(cmd, true, null,
 -                    templateInstallFolder + cmd.getUniqueName() + ".qcow2",
 -                    info.virtualSize, info.size, cmd.getUniqueName(),
 -                    ImageFormat.QCOW2);
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Failed to get secondary storage pool: "
 -                    + e.toString());
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
 -        } catch (InternalErrorException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
 -        } catch (IOException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
 -        } catch (ConfigurationException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
 -        } catch (CloudRuntimeException e) {
 -            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
 -        } finally {
 -            if (secondaryStorage != null) {
 -                secondaryStorage.delete();
 -            }
 -        }
 -    }
 -
 -    protected PrimaryStorageDownloadAnswer execute(
 -            final PrimaryStorageDownloadCommand cmd) {
 -        String tmplturl = cmd.getUrl();
 -        int index = tmplturl.lastIndexOf("/");
 -        String mountpoint = tmplturl.substring(0, index);
 -        String tmpltname = null;
 -        if (index < tmplturl.length() - 1) {
 -            tmpltname = tmplturl.substring(index + 1);
 -        }
 -
 -        KVMPhysicalDisk tmplVol = null;
 -        KVMStoragePool secondaryPool = null;
 -        try {
 -            secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint);
 -
 -            /* Get template vol */
 -            if (tmpltname == null) {
 -                secondaryPool.refresh();
 -                List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
 -                if (disks == null || disks.isEmpty()) {
 -                    return new PrimaryStorageDownloadAnswer(
 -                            "Failed to get volumes from pool: "
 -                                    + secondaryPool.getUuid());
 -                }
 -                for (KVMPhysicalDisk disk : disks) {
 -                    if (disk.getName().endsWith("qcow2")) {
 -                        tmplVol = disk;
 -                        break;
 -                    }
 -                }
 -                if (tmplVol == null) {
 -                    return new PrimaryStorageDownloadAnswer(
 -                            "Failed to get template from pool: "
 -                                    + secondaryPool.getUuid());
 -                }
 -            } else {
 -                tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
 -            }
 -
 -            /* Copy volume to primary storage */
 -            KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
 -                    .getPoolUuid());
 -
 -            KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(
 -                    tmplVol, UUID.randomUUID().toString(), primaryPool);
 -
 -            return new PrimaryStorageDownloadAnswer(primaryVol.getName(),
 -                    primaryVol.getSize());
 -        } catch (CloudRuntimeException e) {
 -            return new PrimaryStorageDownloadAnswer(e.toString());
 -        } finally {
 -            if (secondaryPool != null) {
 -                secondaryPool.delete();
 -            }
 -        }
 -    }
 -
 -    protected Answer execute(CreateStoragePoolCommand cmd) {
 -        return new Answer(cmd, true, "success");
 -    }
 -
 -    protected Answer execute(ModifyStoragePoolCommand cmd) {
 -        KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd
 -                .getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool()
 -                .getPath(), cmd.getPool().getType());
 -        if (storagepool == null) {
 -            return new Answer(cmd, false, " Failed to create storage pool");
 -        }
 -
 -        Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
 -        ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,
 -                storagepool.getCapacity(), storagepool.getUsed(), tInfo);
 -
 -        return answer;
 -    }
 -
 -    private Answer execute(SecurityGroupRulesCmd cmd) {
 -        String vif = null;
 -        String brname = null;
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
 -            vif = nics.get(0).getDevName();
 -            brname = nics.get(0).getBrName();
 -        } catch (LibvirtException e) {
 -            return new SecurityGroupRuleAnswer(cmd, false, e.toString());
 -        }
 -
 -        boolean result = add_network_rules(cmd.getVmName(),
 -                Long.toString(cmd.getVmId()), cmd.getGuestIp(),
 -                cmd.getSignature(), Long.toString(cmd.getSeqNum()),
 -                cmd.getGuestMac(), cmd.stringifyRules(), vif, brname);
 -
 -        if (!result) {
 -            s_logger.warn("Failed to program network rules for vm "
 -                    + cmd.getVmName());
 -            return new SecurityGroupRuleAnswer(cmd, false,
 -                    "programming network rules failed");
 -        } else {
 -            s_logger.debug("Programmed network rules for vm " + cmd.getVmName()
 -                    + " guestIp=" + cmd.getGuestIp() + ",ingress numrules="
 -                    + cmd.getIngressRuleSet().length + ",egress numrules="
 -                    + cmd.getEgressRuleSet().length);
 -            return new SecurityGroupRuleAnswer(cmd);
 -        }
 -    }
 -
 -    private Answer execute(CleanupNetworkRulesCmd cmd) {
 -        boolean result = cleanup_rules();
 -        return new Answer(cmd, result, "");
 -    }
 -
 -    protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            Integer vncPort = getVncPort(conn, cmd.getName());
 -            return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
 -        } catch (Exception e) {
 -            return new GetVncPortAnswer(cmd, e.toString());
 -        }
 -    }
 -
 -    protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
 -        return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
 -                cmd.getProxyVmName(), cmd.getProxyManagementIp(),
 -                cmd.getProxyCmdPort());
 -    }
 -
 -    protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
 -        return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
 -                cmd.getProxyVmName(), cmd.getProxyManagementIp(),
 -                cmd.getProxyCmdPort());
 -    }
 -
 -    protected MaintainAnswer execute(MaintainCommand cmd) {
 -        return new MaintainAnswer(cmd);
 -    }
 -
 -    private Answer executeProxyLoadScan(final Command cmd,
 -            final long proxyVmId, final String proxyVmName,
 -            final String proxyManagementIp, final int cmdPort) {
 -        String result = null;
 -
 -        final StringBuffer sb = new StringBuffer();
 -        sb.append("http://").append(proxyManagementIp).append(":" + cmdPort)
 -                .append("/cmd/getstatus");
 -
 -        boolean success = true;
 -        try {
 -            final URL url = new URL(sb.toString());
 -            final URLConnection conn = url.openConnection();
 -
 -            final InputStream is = conn.getInputStream();
 -            final BufferedReader reader = new BufferedReader(
 -                    new InputStreamReader(is));
 -            final StringBuilder sb2 = new StringBuilder();
 -            String line = null;
 -            try {
 -                while ((line = reader.readLine()) != null) {
 -                    sb2.append(line + "\n");
 -                }
 -                result = sb2.toString();
 -            } catch (final IOException e) {
 -                success = false;
 -            } finally {
 -                try {
 -                    is.close();
 -                } catch (final IOException e) {
 -                    s_logger.warn("Exception when closing , console proxy address : "
 -                            + proxyManagementIp);
 -                    success = false;
 -                }
 -            }
 -        } catch (final IOException e) {
 -            s_logger.warn("Unable to open console proxy command port url, console proxy address : "
 -                    + proxyManagementIp);
 -            success = false;
 -        }
 -
 -        return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success,
 -                result);
 -    }
 -
 -    private Answer execute(AttachIsoCommand cmd) {
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(),
 -                    cmd.isAttach());
 -        } catch (LibvirtException e) {
 -            return new Answer(cmd, false, e.toString());
 -        } catch (URISyntaxException e) {
 -            return new Answer(cmd, false, e.toString());
 -        } catch (InternalErrorException e) {
 -            return new Answer(cmd, false, e.toString());
 -        }
 -
 -        return new Answer(cmd);
 -    }
 -
 -    private AttachVolumeAnswer execute(AttachVolumeCommand cmd) {
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
 -                    .getPoolUuid());
 -            KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
 -            attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk,
 -                    cmd.getDeviceId().intValue());
 -        } catch (LibvirtException e) {
 -            return new AttachVolumeAnswer(cmd, e.toString());
 -        } catch (InternalErrorException e) {
 -            return new AttachVolumeAnswer(cmd, e.toString());
 -        }
 -
 -        return new AttachVolumeAnswer(cmd, cmd.getDeviceId());
 -    }
 -
 -    private Answer execute(ReadyCommand cmd) {
 -        return new ReadyAnswer(cmd);
 -    }
 -
 -    protected State convertToState(DomainInfo.DomainState ps) {
 -        final State state = s_statesTable.get(ps);
 -        return state == null ? State.Unknown : state;
 -    }
 -
 -    protected State getVmState(Connect conn, final String vmName) {
 -        int retry = 3;
 -        Domain vms = null;
 -        while (retry-- > 0) {
 -            try {
 -                vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                        .getBytes()));
 -                State s = convertToState(vms.getInfo().state);
 -                return s;
 -            } catch (final LibvirtException e) {
 -                s_logger.warn("Can't get vm state " + vmName + e.getMessage()
 -                        + "retry:" + retry);
 -            } catch (Exception e) {
 -                s_logger.warn("Can't get vm state " + vmName + e.getMessage()
 -                        + "retry:" + retry);
 -            } finally {
 -                try {
 -                    if (vms != null) {
 -                        vms.free();
 -                    }
 -                } catch (final LibvirtException e) {
 -
 -                }
 -            }
 -        }
 -        return State.Stopped;
 -    }
 -
 -    private Answer execute(CheckVirtualMachineCommand cmd) {
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            final State state = getVmState(conn, cmd.getVmName());
 -            Integer vncPort = null;
 -            if (state == State.Running) {
 -                vncPort = getVncPort(conn, cmd.getVmName());
 -
 -                synchronized (_vms) {
 -                    _vms.put(cmd.getVmName(), State.Running);
 -                }
 -            }
 -
 -            return new CheckVirtualMachineAnswer(cmd, state, vncPort);
 -        } catch (LibvirtException e) {
 -            return new CheckVirtualMachineAnswer(cmd, e.getMessage());
 -        }
 -    }
 -
 -    private Answer execute(PingTestCommand cmd) {
 -        String result = null;
 -        final String computingHostIp = cmd.getComputingHostIp(); // TODO, split
 -                                                                    // the
 -                                                                    // command
 -                                                                    // into 2
 -                                                                    // types
 -
 -        if (computingHostIp != null) {
 -            result = doPingTest(computingHostIp);
 -        } else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) {
 -            result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
 -        } else {
 -            return new Answer(cmd, false, "routerip and private ip is null");
 -        }
 -
 -        if (result != null) {
 -            return new Answer(cmd, false, result);
 -        }
 -        return new Answer(cmd);
 -    }
 -
 -    private String doPingTest(final String computingHostIp) {
 -        final Script command = new Script(_pingTestPath, 10000, s_logger);
 -        command.add("-h", computingHostIp);
 -        return command.execute();
 -    }
 -
 -    private String doPingTest(final String domRIp, final String vmIp) {
 -        final Script command = new Script(_pingTestPath, 10000, s_logger);
 -        command.add("-i", domRIp);
 -        command.add("-p", vmIp);
 -        return command.execute();
 -    }
 -
 -    private synchronized Answer execute(MigrateCommand cmd) {
 -        String vmName = cmd.getVmName();
 -
 -        State state = null;
 -        String result = null;
 -        synchronized (_vms) {
 -            state = _vms.get(vmName);
 -            _vms.put(vmName, State.Stopping);
 -        }
 -
 -        Domain dm = null;
 -        Connect dconn = null;
 -        Domain destDomain = null;
 -        Connect conn = null;
 -        try {
 -            conn = LibvirtConnection.getConnection();
 -            dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
 -                    .getBytes()));
 -            dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp()
 -                    + "/system");
 -            /*
 -             * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
 -             * VIR_MIGRATE_PERSIST_DEST(1<<3)
 -             */
 -            destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:"
 -                    + cmd.getDestinationIp(), _migrateSpeed);
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Can't migrate domain: " + e.getMessage());
 -            result = e.getMessage();
 -        } catch (Exception e) {
 -            s_logger.debug("Can't migrate domain: " + e.getMessage());
 -            result = e.getMessage();
 -        } finally {
 -            try {
 -                if (dm != null) {
 -                    dm.free();
 -                }
 -                if (dconn != null) {
 -                    dconn.close();
 -                }
 -                if (destDomain != null) {
 -                    destDomain.free();
 -                }
 -            } catch (final LibvirtException e) {
 -
 -            }
 -        }
 -
 -        if (result != null) {
 -            synchronized (_vms) {
 -                _vms.put(vmName, state);
 -            }
 -        } else {
 -            destroy_network_rules_for_vm(conn, vmName);
 -            cleanupVM(conn, vmName,
 -                    getVnetId(VirtualMachineName.getVnet(vmName)));
 -        }
 -
 -        return new MigrateAnswer(cmd, result == null, result, null);
 -    }
 -
 -    private synchronized Answer execute(PrepareForMigrationCommand cmd) {
 -
 -        VirtualMachineTO vm = cmd.getVirtualMachine();
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Preparing host for migrating " + vm);
 -        }
 -
 -        NicTO[] nics = vm.getNics();
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            for (NicTO nic : nics) {
 -                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")) {
 -                        createVlanBr(vlanId, _pifs.first());
 -                    }
 -                } else if (nic.getType() == TrafficType.Control) {
 -                    /* Make sure the network is still there */
 -                    createControlNetwork(conn);
 -                } else if (nic.getType() == TrafficType.Public) {
 -                    if (nic.getBroadcastType() == BroadcastDomainType.Vlan
 -                            && !vlanId.equalsIgnoreCase("untagged")) {
 -                        createVlanBr(vlanId, _pifs.second());
 -                    }
 -                }
 -            }
 -
 -            /* setup disks, e.g for iso */
 -            VolumeTO[] volumes = vm.getDisks();
 -            for (VolumeTO volume : volumes) {
 -                if (volume.getType() == Volume.Type.ISO) {
 -                    getVolumePath(conn, volume);
 -                }
 -            }
 -
 -            synchronized (_vms) {
 -                _vms.put(vm.getName(), State.Migrating);
 -            }
 -
 -            return new PrepareForMigrationAnswer(cmd);
 -        } catch (LibvirtException e) {
 -            return new PrepareForMigrationAnswer(cmd, e.toString());
 -        } catch (InternalErrorException e) {
 -            return new PrepareForMigrationAnswer(cmd, e.toString());
 -        } catch (URISyntaxException e) {
 -            return new PrepareForMigrationAnswer(cmd, e.toString());
 -        }
 -    }
 -
 -    public void createVnet(String vnetId, String pif)
 -            throws InternalErrorException {
 -        final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
 -        command.add("-v", vnetId);
 -        command.add("-p", pif);
 -        command.add("-o", "add");
 -
 -        final String result = command.execute();
 -        if (result != null) {
 -            throw new InternalErrorException("Failed to create vnet " + vnetId
 -                    + ": " + result);
 -        }
 -    }
 -
 -    private Answer execute(CheckHealthCommand cmd) {
 -        return new CheckHealthAnswer(cmd, true);
 -    }
 -
 -    private Answer execute(GetHostStatsCommand cmd) {
 -        final Script cpuScript = new Script("/bin/bash", s_logger);
 -        cpuScript.add("-c");
 -        cpuScript
 -                .add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle");
 -
 -        final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
 -        String result = cpuScript.execute(parser);
 -        if (result != null) {
 -            s_logger.debug("Unable to get the host CPU state: " + result);
 -            return new Answer(cmd, false, result);
 -        }
 -        double cpuUtil = (100.0D - Double.parseDouble(parser.getLine()));
 -
 -        long freeMem = 0;
 -        final Script memScript = new Script("/bin/bash", s_logger);
 -        memScript.add("-c");
 -        memScript
 -                .add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
 -        final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
 -        result = memScript.execute(Memparser);
 -        if (result != null) {
 -            s_logger.debug("Unable to get the host Mem state: " + result);
 -            return new Answer(cmd, false, result);
 -        }
 -        freeMem = Long.parseLong(Memparser.getLine());
 -
 -        Script totalMem = new Script("/bin/bash", s_logger);
 -        totalMem.add("-c");
 -        totalMem.add("free|grep Mem:|awk '{print $2}'");
 -        final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();
 -        result = totalMem.execute(totMemparser);
 -        if (result != null) {
 -            s_logger.debug("Unable to get the host Mem state: " + result);
 -            return new Answer(cmd, false, result);
 -        }
 -        long totMem = Long.parseLong(totMemparser.getLine());
 -
 -        Pair<Double, Double> nicStats = getNicStats(_publicBridgeName);
 -
 -        HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil,
 -                nicStats.first() / 1000, nicStats.second() / 1000, "host",
 -                totMem, freeMem, 0, 0);
 -        return new GetHostStatsAnswer(cmd, hostStats);
 -    }
 -
 -    protected String networkUsage(final String privateIpAddress,
 -            final String option, final String vif) {
 -        Script getUsage = new Script(_networkUsagePath, s_logger);
 -        if (option.equals("get")) {
 -            getUsage.add("-g");
 -        } else if (option.equals("create")) {
 -            getUsage.add("-c");
 -        } else if (option.equals("reset")) {
 -            getUsage.add("-r");
 -        } else if (option.equals("addVif")) {
 -            getUsage.add("-a", vif);
 -        } else if (option.equals("deleteVif")) {
 -            getUsage.add("-d", vif);
 -        }
 -
 -        getUsage.add("-i", privateIpAddress);
 -        final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser();
 -        String result = getUsage.execute(usageParser);
 -        if (result != null) {
 -            s_logger.debug("Failed to execute networkUsage:" + result);
 -            return null;
 -        }
 -        return usageParser.getLine();
 -    }
 -
 -    protected long[] getNetworkStats(String privateIP) {
 -        String result = networkUsage(privateIP, "get", null);
 -        long[] stats = new long[2];
 -        if (result != null) {
 -            String[] splitResult = result.split(":");
 -            int i = 0;
 -            while (i < splitResult.length - 1) {
 -                stats[0] += (new Long(splitResult[i++])).longValue();
 -                stats[1] += (new Long(splitResult[i++])).longValue();
 -            }
 -        }
 -        return stats;
 -    }
 -
 -    private Answer execute(NetworkUsageCommand cmd) {
 -        if (cmd.getOption() != null && cmd.getOption().equals("create")) {
 -            String result = networkUsage(cmd.getPrivateIP(), "create", null);
 -            NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L,
 -                    0L);
 -            return answer;
 -        }
 -        long[] stats = getNetworkStats(cmd.getPrivateIP());
 -        NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0],
 -                stats[1]);
 -        return answer;
 -    }
 -
 -    private Answer execute(RebootCommand cmd) {
 -        Long bytesReceived = null;
 -        Long bytesSent = null;
 -
 -        synchronized (_vms) {
 -            _vms.put(cmd.getVmName(), State.Starting);
 -        }
 -
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -            final String result = rebootVM(conn, cmd.getVmName());
 -            if (result == null) {
 -                Integer vncPort = null;
 -                try {
 -                    vncPort = getVncPort(conn, cmd.getVmName());
 -                } catch (Exception e) {
 -
 -                }
 -                get_rule_logs_for_vms();
 -                return new RebootAnswer(cmd, null, bytesSent, bytesReceived,
 -                        vncPort);
 -            } else {
 -                return new RebootAnswer(cmd, result);
 -            }
 -        } catch (LibvirtException e) {
 -            return new RebootAnswer(cmd, e.getMessage());
 -        } finally {
 -            synchronized (_vms) {
 -                _vms.put(cmd.getVmName(), State.Running);
 -            }
 -        }
 -    }
 -
 -    protected Answer execute(RebootRouterCommand cmd) {
 -        Long bytesSent = 0L;
 -        Long bytesRcvd = 0L;
 -        if (VirtualMachineName.isValidRouterName(cmd.getVmName())) {
 -            long[] stats = getNetworkStats(cmd.getPrivateIpAddress());
 -            bytesSent = stats[0];
 -            bytesRcvd = stats[1];
 -        }
 -        RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
 -        answer.setBytesSent(bytesSent);
 -        answer.setBytesReceived(bytesRcvd);
 -        String result = _virtRouterResource.connect(cmd.getPrivateIpAddress());
 -        if (result == null) {
 -            networkUsage(cmd.getPrivateIpAddress(), "create", null);
 -            return answer;
 -        } else {
 -            return new Answer(cmd, false, result);
 -        }
 -    }
 -
 -    protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
 -        List<String> vmNames = cmd.getVmNames();
 -        try {
 -            HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
 -            Connect conn = LibvirtConnection.getConnection();
 -            for (String vmName : vmNames) {
 -                VmStatsEntry statEntry = getVmStat(conn, vmName);
 -                if (statEntry == null) {
 -                    continue;
 -                }
 -
 -                vmStatsNameMap.put(vmName, statEntry);
 -            }
 -            return new GetVmStatsAnswer(cmd, vmStatsNameMap);
 -        } catch (LibvirtException e) {
 -            s_logger.debug("Can't get vm stats: " + e.toString());
 -            return new GetVmStatsAnswer(cmd, null);
 -        }
 -    }
 -
 -    protected Answer execute(StopCommand cmd) {
 -        final String vmName = cmd.getVmName();
 -
 -        Long bytesReceived = new Long(0);
 -        Long bytesSent = new Long(0);
 -
 -        State state = null;
 -        synchronized (_vms) {
 -            state = _vms.get(vmName);
 -            _vms.put(vmName, State.Stopping);
 -        }
 -        try {
 -            Connect conn = LibvirtConnection.getConnection();
 -
 -            List<DiskDef> disks = getDisks(conn, vmName);
 -            destroy_network_rules_for_vm(conn, vmName);
 -            String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
 -            if (result == null) {
 -                for (DiskDef disk : disks) {
 -                    if (disk.getDeviceType() == DiskDef.deviceType.CDROM
 -                            && disk.getDiskPath() != null)
 -                        cleanupDisk(conn, disk);
 -                }
 -            }
 -
 -            final String result2 = cleanupVnet(conn, cmd.getVnet());
 -
 -            if (result != null && result2 != null) {
 -                result = result2 + result;
 -            }
 -            state = State.Stopped;
 -            return new StopAnswer(cmd, result, 0, bytesSent, bytesReceived);
 -        } catch (LibvirtException e) {
 -            return new StopAnswer(cmd, e.getMessage());
 -        } finally {
 -            synchronized (_vms) {
 -                if (state != null) {
 -                    _vms.put(vmName, state);
 -                } else {
 -                    _vms.remove(vmName);
 -                }
 -            }
 -        }
 -  

<TRUNCATED>