You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ya...@apache.org on 2014/01/25 03:28:59 UTC

[1/4] git commit: updated refs/heads/master to 069bc36

Updated Branches:
  refs/heads/master 417b8e089 -> 069bc3686


CLOUDSTACK-5779: Generalize calling to execute or create file for Xen


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/2d100f12
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/2d100f12
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/2d100f12

Branch: refs/heads/master
Commit: 2d100f1269e44de927be32faed32e31c62afa57b
Parents: 417b8e0
Author: Sheng Yang <sh...@citrix.com>
Authored: Fri Jan 24 14:54:11 2014 -0800
Committer: Sheng Yang <sh...@citrix.com>
Committed: Fri Jan 24 18:27:55 2014 -0800

----------------------------------------------------------------------
 .../virtualnetwork/VirtualRoutingResource.java  |  58 +++---
 .../vmware/resource/VmwareResource.java         |  38 ++--
 .../xen/resource/CitrixResourceBase.java        | 206 ++++++++++---------
 .../xen/resource/XenServer56Resource.java       |  44 ++--
 scripts/vm/hypervisor/xenserver/vmops           |  15 +-
 utils/src/com/cloud/utils/ExecutionResult.java  |  44 ++++
 6 files changed, 221 insertions(+), 184 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index 732d7b4..b27ed55 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -177,7 +177,7 @@ public class VirtualRoutingResource implements Manager {
                 args += "-u ";
                 args += userpwd.getUsernamePassword();
             }
-            String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+            String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
             if (result != null) {
                 return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername());
             }
@@ -204,7 +204,7 @@ public class VirtualRoutingResource implements Manager {
         }
         args += " -C " + cmd.getLocalCidr();
         args += " -i " + cmd.getPublicInterface();
-        String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
         if (result != null) {
             return new Answer(cmd, false, "Configure VPN failed");
         }
@@ -252,9 +252,9 @@ public class VirtualRoutingResource implements Manager {
         String result = null;
 
         if (trafficType == FirewallRule.TrafficType.Egress) {
-            result = routerProxy("firewall_egress.sh", routerIp, args);
+            result = executeInVR(routerIp, "firewall_egress.sh", args);
         } else {
-            result = routerProxy("firewall_ingress.sh", routerIp, args);
+            result = executeInVR(routerIp, "firewall_ingress.sh", args);
         }
 
         if (result != null) {
@@ -278,7 +278,7 @@ public class VirtualRoutingResource implements Manager {
             args.append(" -r ").append(rule.getDstIp());
             args.append(" -d ").append(rule.getStringDstPortRange());
 
-            String result = routerProxy("firewall_nat.sh", routerIp, args.toString());
+            String result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
 
             if (result == null || result.isEmpty()) {
                 results[i++] = "Failed";
@@ -302,7 +302,7 @@ public class VirtualRoutingResource implements Manager {
             args += " -l " + rule.getSrcIp();
             args += " -r " + rule.getDstIp();
 
-            String result = routerProxy("vpc_staticnat.sh", routerIp, args);
+            String result = executeInVR(routerIp, "vpc_staticnat.sh", args);
 
             if (result == null) {
                 results[i++] = null;
@@ -337,7 +337,7 @@ public class VirtualRoutingResource implements Manager {
             args.append(" -d ").append(rule.getStringSrcPortRange());
             args.append(" -G ");
 
-            String result = routerProxy("firewall_nat.sh", routerIp, args.toString());
+            String result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
 
             if (result == null || result.isEmpty()) {
                 results[i++] = "Failed";
@@ -420,10 +420,10 @@ public class VirtualRoutingResource implements Manager {
 
             if (cmd.getVpcId() == null) {
                 args = " -i " + routerIp + args;
-                result = routerProxy("loadbalancer.sh", routerIp, args);
+                result = executeInVR(routerIp, "loadbalancer.sh", args);
             } else {
                 args = " -i " + cmd.getNic().getIp() + args;
-                result = routerProxy("vpc_loadbalancer.sh", routerIp, args);
+                result = executeInVR(routerIp, "vpc_loadbalancer.sh", args);
             }
 
             if (result != null) {
@@ -449,7 +449,7 @@ public class VirtualRoutingResource implements Manager {
 
         String args = "-d " + json;
 
-        final String result = routerProxy("vmdata.py", routerIp, args);
+        final String result = executeInVR(routerIp, "vmdata.py", args);
         if (result != null) {
             return new Answer(cmd, false, "VmDataCommand failed, check agent logs");
         }
@@ -485,7 +485,7 @@ public class VirtualRoutingResource implements Manager {
         String args = "-v " + vmIpAddress;
         args += " -p " + password;
 
-        String result = routerProxy("savepassword.sh", routerPrivateIPAddress, args);
+        String result = executeInVR(routerPrivateIPAddress, "savepassword.sh", args);
         if (result != null) {
             return new Answer(cmd, false, "Unable to save password to DomR.");
         }
@@ -520,7 +520,7 @@ public class VirtualRoutingResource implements Manager {
             args += " -N";
         }
 
-        final String result = routerProxy("edithosts.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+        final String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args);
         return new Answer(cmd, result == null, result);
     }
 
@@ -531,7 +531,7 @@ public class VirtualRoutingResource implements Manager {
         for (IpAliasTO ipaliasto : ipAliasTOs) {
             args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
         }
-        final String result = routerProxy("createipAlias.sh", routerIp, args);
+        final String result = executeInVR(routerIp, "createipAlias.sh", args);
         return new Answer(cmd, result == null, result);
     }
 
@@ -547,7 +547,7 @@ public class VirtualRoutingResource implements Manager {
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
         }
-        final String result = routerProxy("deleteipAlias.sh", routerIp, args);
+        final String result = executeInVR(routerIp, "deleteipAlias.sh", args);
         return new Answer(cmd, result == null, result);
     }
 
@@ -558,7 +558,7 @@ public class VirtualRoutingResource implements Manager {
         for (DhcpTO dhcpTo : dhcpTos) {
             args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
         }
-        final String result = routerProxy("dnsmasq.sh", routerIp, args);
+        final String result = executeInVR(routerIp, "dnsmasq.sh", args);
         return new Answer(cmd, result == null, result);
     }
 
@@ -589,14 +589,14 @@ public class VirtualRoutingResource implements Manager {
             args += " " + ip;
         }
 
-        final String result = routerProxy("checkbatchs2svpn.sh", routerIP, args);
+        final String result = executeInVR(routerIP, "checkbatchs2svpn.sh", args);
         if (result == null || result.isEmpty()) {
             return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
         }
         return new CheckS2SVpnConnectionsAnswer(cmd, true, result);
     }
 
-    public String routerProxy(String script, String routerIP, String args) {
+    public String executeInVR(String routerIP, String script, String args) {
         final Script command = new Script(_routerProxyPath, _timeout, s_logger);
         command.add(script);
         command.add(routerIP);
@@ -617,7 +617,7 @@ public class VirtualRoutingResource implements Manager {
     }
 
     protected Answer execute(BumpUpPriorityCommand cmd) {
-        String result = routerProxy("bumpup_priority.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), null);
+        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "bumpup_priority.sh", null);
         if (result != null) {
             return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result);
         }
@@ -692,7 +692,7 @@ public class VirtualRoutingResource implements Manager {
             args += " -N ";
             args += cmd.getPeerGuestCidrList();
         }
-        String result = routerProxy("ipsectunnel.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args);
         if (result != null) {
             return new Answer(cmd, false, "Configure site to site VPN failed due to " + result);
         }
@@ -740,7 +740,7 @@ public class VirtualRoutingResource implements Manager {
     public String configureMonitor(final String routerIP, final String config) {
 
         String args = " -c " + config;
-        return routerProxy("monitor_service.sh", routerIP, args);
+        return executeInVR(routerIP, "monitor_service.sh", args);
     }
 
     public String assignGuestNetwork(final String dev, final String routerIP, final String routerGIP, final String gateway, final String cidr, final String netmask,
@@ -758,19 +758,19 @@ public class VirtualRoutingResource implements Manager {
         if (domainName != null && !domainName.isEmpty()) {
             args += " -e " + domainName;
         }
-        return routerProxy("vpc_guestnw.sh", routerIP, args);
+        return executeInVR(routerIP, "vpc_guestnw.sh", args);
     }
 
     public String assignNetworkACL(final String routerIP, final String dev, final String routerGIP, final String netmask, final String rule, String privateGw) {
         String args = " -d " + dev;
         if (privateGw != null) {
             args += " -a " + rule;
-            return routerProxy("vpc_privategw_acl.sh", routerIP, args);
+            return executeInVR(routerIP, "vpc_privategw_acl.sh", args);
         } else {
             args += " -i " + routerGIP;
             args += " -m " + netmask;
             args += " -a " + rule;
-            return routerProxy("vpc_acl.sh", routerIP, args);
+            return executeInVR(routerIP, "vpc_acl.sh", args);
         }
     }
 
@@ -780,7 +780,7 @@ public class VirtualRoutingResource implements Manager {
         args += pubIP;
         args += " -c ";
         args += dev;
-        return routerProxy("vpc_snat.sh", routerIP, args);
+        return executeInVR(routerIP, "vpc_snat.sh", args);
     }
 
     private SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) {
@@ -797,7 +797,7 @@ public class VirtualRoutingResource implements Manager {
             args += " -r " + rule.getDstIp();
             args += " -d " + rule.getStringDstPortRange().replace(":", "-");
 
-            String result = routerProxy("vpc_portforwarding.sh", routerIp, args);
+            String result = executeInVR(routerIp, "vpc_portforwarding.sh", args);
 
             if (result != null) {
                 results[i++] = "Failed";
@@ -833,7 +833,7 @@ public class VirtualRoutingResource implements Manager {
         args += " -n ";
         args += subnet;
 
-        String result = routerProxy("vpc_ipassoc.sh", routerIP, args);
+        String result = executeInVR(routerIP, "vpc_ipassoc.sh", args);
         if (result != null) {
             throw new InternalErrorException("KVM plugin \"vpc_ipassoc\" failed:" + result);
         }
@@ -841,7 +841,7 @@ public class VirtualRoutingResource implements Manager {
             snatArgs += " -l " + pubIP;
             snatArgs += " -c " + nicname;
 
-            result = routerProxy("vpc_privateGateway.sh", routerIP, snatArgs);
+            result = executeInVR(routerIP, "vpc_privateGateway.sh", snatArgs);
             if (result != null) {
                 throw new InternalErrorException("KVM plugin \"vpc_privateGateway\" failed:" + result);
             }
@@ -862,7 +862,7 @@ public class VirtualRoutingResource implements Manager {
             }
 
             String args = " -a " + sb.toString();
-            String result = routerProxy("vpc_staticroute.sh", routerIP, args);
+            String result = executeInVR(routerIP, "vpc_staticroute.sh", args);
 
             if (result != null) {
                 for (int i = 0; i < results.length; i++) {
@@ -923,7 +923,7 @@ public class VirtualRoutingResource implements Manager {
             args += " -n";
         }
 
-        return routerProxy("ipassoc.sh", privateIpAddress, args);
+        return executeInVR(privateIpAddress, "ipassoc.sh", args);
     }
 
     private void deleteBridge(String brName) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index a6baa02..982031b 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@ -1954,6 +1954,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         return new IpAssocAnswer(cmd, results);
     }
 
+    protected Pair<Boolean, String> executeInVR(String script, String routerIP, String args) {
+        Pair<Boolean, String> result;
+        try {
+            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
+            result = SshHelper.sshExecute(routerIP, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/" + script + " " + args);
+        } catch (Exception e) {
+            String msg = "Command failed due to " + VmwareHelper.getExceptionMessage(e);
+            s_logger.error(msg);
+            result = new Pair<Boolean, String>(false, msg);
+        }
+        return result;
+    }
+
     protected Answer execute(SavePasswordCommand cmd) {
         if (s_logger.isInfoEnabled()) {
 
@@ -1975,27 +1988,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
 
         args += " -p " + password;
 
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + args);
-
-            if (!result.first()) {
-                s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second());
-
-                return new Answer(cmd, false, "SavePassword failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("savepassword command on domain router " + controlIp + " completed");
-            }
-
-        } catch (Throwable e) {
-            String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        Pair<Boolean, String> result = executeInVR("savepassword.sh", controlIp, args);
+        if (!result.first()) {
+            s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second());
+            return new Answer(cmd, false, "SavePassword failed due to " + result.second());
         }
-        return new Answer(cmd);
+    return new Answer(cmd);
     }
 
     protected Answer execute(DhcpEntryCommand cmd) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 811d056..05311b8 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -264,6 +264,7 @@ import com.cloud.storage.resource.StorageSubsystemCommandHandler;
 import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase;
 import com.cloud.storage.template.TemplateProp;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
+import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.StringUtils;
@@ -614,12 +615,21 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
     }
 
-    public String routerProxy(String script, String routerIP, String args) {
+    public ExecutionResult executeInVR(String routerIP, String script, String args) {
         Connection conn = getConnection();
-        String proxyArgs = script + " " + routerIP + " " + args;
-        return callHostPlugin(conn, "vmops", "routerProxy", "args", proxyArgs);
+        String rc = callHostPlugin(conn, "vmops", "routerProxy", "args", script + " " + routerIP + " " + args);
+        // Fail case would be start with "fail#"
+        return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5));
     }
 
+    protected ExecutionResult createFileInVR(String routerIp, String path, String content) {
+        Connection conn = getConnection();
+        String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", path, "filecontents", content);
+        // Fail case would be start with "fail#"
+        return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5));
+    }
+
+
     private Answer execute(PerformanceMonitorCommand cmd) {
         Connection conn = getConnection();
         String perfMon = getPerfMon(conn, cmd.getParams(), cmd.getWait());
@@ -1968,31 +1978,31 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         for (String ip : cmd.getVpnIps()) {
             args += ip + " ";
         }
-        String result = routerProxy("checkbatchs2svpn.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-        if (result == null || result.isEmpty()) {
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "checkbatchs2svpn.sh", args);
+        if (!result.isSuccess()) {
             return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
         }
-        return new CheckS2SVpnConnectionsAnswer(cmd, true, result);
+        return new CheckS2SVpnConnectionsAnswer(cmd, true, result.getDetails());
     }
 
     private CheckRouterAnswer execute(CheckRouterCommand cmd) {
-        String result = routerProxy("checkrouter.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), null);
-        if (result == null || result.isEmpty()) {
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "checkrouter.sh", null);
+        if (!result.isSuccess()) {
             return new CheckRouterAnswer(cmd, "CheckRouterCommand failed");
         }
-        return new CheckRouterAnswer(cmd, result, true);
+        return new CheckRouterAnswer(cmd, result.getDetails(), true);
     }
 
     private GetDomRVersionAnswer execute(GetDomRVersionCmd cmd) {
-        String result = routerProxy("get_template_version.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), null);
-        if (result == null || result.isEmpty()) {
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "get_template_version.sh", null);
+        if (!result.isSuccess()) {
             return new GetDomRVersionAnswer(cmd, "getDomRVersionCmd failed");
         }
-        String[] lines = result.split("&");
+        String[] lines = result.getDetails().split("&");
         if (lines.length != 2) {
-            return new GetDomRVersionAnswer(cmd, result);
+            return new GetDomRVersionAnswer(cmd, result.getDetails());
         }
-        return new GetDomRVersionAnswer(cmd, result, lines[0], lines[1]);
+        return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]);
     }
 
     private Answer execute(BumpUpPriorityCommand cmd) {
@@ -2032,7 +2042,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
     protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesCommand cmd) {
         getConnection();
-
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String[] results = new String[cmd.getRules().length];
         int i = 0;
@@ -2047,10 +2056,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args.append(" -r ").append(rule.getDstIp());
             args.append(" -d ").append(rule.getStringDstPortRange());
 
-            String result = routerProxy("firewall_nat.sh", routerIp, args.toString());
+            ExecutionResult result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
 
-            if (result == null || result.isEmpty()) {
-                results[i++] = "Failed";
+            if (!result.isSuccess()) {
+                results[i++] = "Failed: " + result.getDetails();
                 endResult = false;
             } else {
                 results[i++] = null;
@@ -2069,10 +2078,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             String args = rule.revoked() ? "-D" : "-A";
             args += " -l " + rule.getSrcIp();
             args += " -r " + rule.getDstIp();
-            String result = routerProxy("vpc_staticnat.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_staticnat.sh", args);
 
-            if (result == null || result.isEmpty()) {
-                results[i++] = "Failed";
+            if (!result.isSuccess()) {
+                results[i++] = "Failed: " + result.getDetails();
                 endResult = false;
             } else {
                 results[i++] = null;
@@ -2105,10 +2114,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args.append(" -d ").append(rule.getStringSrcPortRange());
             args.append(" -G ");
 
-            String result = routerProxy("firewall_nat.sh", routerIp, args.toString());
+            ExecutionResult result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
 
-            if (result == null || result.isEmpty()) {
-                results[i++] = "Failed";
+            if (!result.isSuccess()) {
+                results[i++] = "Failed:" + result.getDetails();
                 endResult = false;
             } else {
                 results[i++] = null;
@@ -2125,9 +2134,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         for (IpAliasTO ipaliasto : ipAliasTOs) {
             args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
         }
-        String result = routerProxy("createipAlias.sh", routerIp, args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "CreateIPAliasCommand failed\n");
+        ExecutionResult result = executeInVR(routerIp, "createipAlias.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "CreateIPAliasCommand failed due to " + result.getDetails());
         }
 
         return new Answer(cmd);
@@ -2146,9 +2155,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
         }
-        String result = routerProxy("deleteipAlias", routerIp, args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "DeleteipAliasCommand failed\n");
+        ExecutionResult result = executeInVR(routerIp, "deleteipAlias", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "DeleteipAliasCommand failed due to " + result.getDetails());
         }
 
         return new Answer(cmd);
@@ -2162,19 +2171,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
         }
 
-        String result = routerProxy("dnsmasq.sh", routerIp, args);
+        ExecutionResult result = executeInVR(routerIp, "dnsmasq.sh", args);
 
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "DnsMasqconfigCommand failed");
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "DnsMasqconfigCommand failed due to " + result.getDetails());
         }
 
         return new Answer(cmd);
-
-    }
-
-    protected String createFileInVR(String routerIp, String path, String content) {
-        Connection conn = getConnection();
-        return callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", path, "filecontents", content);
     }
 
     protected Answer execute(final LoadBalancerConfigCommand cmd) {
@@ -2192,10 +2195,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             tmpCfgFileContents += "\n";
         }
         String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new";
-        String result = createFileInVR(routerIp, tmpCfgFilePath, tmpCfgFileContents);
+        ExecutionResult result = createFileInVR(routerIp, tmpCfgFilePath, tmpCfgFileContents);
 
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "LoadBalancerConfigCommand failed to create HA proxy cfg file.");
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "LoadBalancerConfigCommand failed to create HA proxy cfg file: " + result.getDetails());
         }
 
         String[][] rules = cfgtr.generateFwRules(cmd);
@@ -2235,14 +2238,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
         if (cmd.getVpcId() == null) {
             args = " -i " + routerIp + args;
-            result = routerProxy("loadbalancer.sh", routerIp, args);
+            result = executeInVR(routerIp, "loadbalancer.sh", args);
         } else {
             args = " -i " + cmd.getNic().getIp() + args;
-            result = routerProxy("vpc_loadbalancer.sh", routerIp, args);
+            result = executeInVR(routerIp, "vpc_loadbalancer.sh", args);
         }
 
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "LoadBalancerConfigCommand failed");
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "LoadBalancerConfigCommand failed: " + result.getDetails());
         }
         return new Answer(cmd);
     }
@@ -2275,9 +2278,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args += " -N";
         }
 
-        String result = routerProxy("edithosts.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "DhcpEntry failed");
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "DhcpEntry failed: " + result.getDetails());
         }
         return new Answer(cmd);
     }
@@ -2296,9 +2299,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
         args += " -C " + cmd.getLocalCidr();
         args += " -i " + cmd.getPublicInterface();
-        String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "Configure VPN failed");
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "Configure VPN failed" + result.getDetails());
         }
         return new Answer(cmd);
     }
@@ -2311,9 +2314,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             } else {
                 args += " -u " + userpwd.getUsernamePassword();
             }
-            String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-            if (result == null || result.isEmpty()) {
-                return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername());
+            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
+            if (!result.isSuccess()) {
+                return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername() + ":" + result.getDetails());
             }
         }
 
@@ -2328,10 +2331,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
         String args = "-d " + json;
 
-        String result = routerProxy("vmdata.py", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vmdata.py", args);
 
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "vm_data failed");
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "vm_data failed:" + result.getDetails());
         } else {
             return new Answer(cmd);
         }
@@ -2344,10 +2347,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
         String args = " -v " + vmIpAddress;
         args += " -p " + password;
-        String result = routerProxy("savepassword.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "savepassword.sh", args);
 
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "savePassword failed");
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "savePassword failed:" + result.getDetails());
         }
         return new Answer(cmd);
     }
@@ -2439,10 +2442,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 args += " -n";
             }
 
-            String result = routerProxy("ipassoc.sh", privateIpAddress, args);
+            ExecutionResult result = executeInVR(privateIpAddress, "ipassoc.sh", args);
 
-            if (result == null || result.isEmpty()) {
-                throw new InternalErrorException("Xen plugin \"ipassoc\" failed.");
+            if (!result.isSuccess()) {
+                throw new InternalErrorException("Xen plugin \"ipassoc\" failed." + result.getDetails());
             }
 
             if (removeVif) {
@@ -2511,18 +2514,18 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args += " -n ";
             args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
 
-            String result = routerProxy("vpc_ipassoc.sh", routerIp, args);
-            if (result == null || result.isEmpty()) {
-                throw new InternalErrorException("Xen plugin \"vpc_ipassoc\" failed.");
+            ExecutionResult result = executeInVR(routerIp, "vpc_ipassoc.sh", args);
+            if (!result.isSuccess()) {
+                throw new InternalErrorException("Xen plugin \"vpc_ipassoc\" failed." + result.getDetails());
             }
 
             if (ip.isSourceNat()) {
                 snatArgs += " -l " + ip.getPublicIp();
                 snatArgs += " -c " + "eth" + correctVif.getDevice(conn);
 
-                result = routerProxy("vpc_privateGateway.sh", routerIp, snatArgs);
-                if (result == null || result.isEmpty()) {
-                    throw new InternalErrorException("Xen plugin \"vpc_privateGateway\" failed.");
+                result = executeInVR(routerIp, "vpc_privateGateway.sh", snatArgs);
+                if (!result.isSuccess()) {
+                    throw new InternalErrorException("Xen plugin \"vpc_privateGateway\" failed." + result.getDetails());
                 }
             }
 
@@ -7493,9 +7496,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
         String args = " -c " + config;
 
-        String result = routerProxy("monitor_service.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "SetMonitorServiceCommand failed to create cfg file.");
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "monitor_service.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "SetMonitorServiceCommand failed to create cfg file." + result.getDetails());
         }
 
         return new Answer(cmd, success, "");
@@ -7504,8 +7507,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
     protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) {
         String[] results = new String[cmd.getRules().length];
-        String callResult;
-        getConnection();
+        ExecutionResult callResult;
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
         FirewallRuleTO[] allrules = cmd.getRules();
@@ -7536,15 +7538,15 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
 
         if (trafficType == FirewallRule.TrafficType.Egress) {
-            callResult = routerProxy("firewall_egress.sh", routerIp, args);
+            callResult = executeInVR(routerIp, "firewall_egress.sh", args);
         } else {
-            callResult = routerProxy("firewall_ingress.sh", routerIp, args);
+            callResult = executeInVR(routerIp, "firewall_ingress.sh", args);
         }
 
-        if (callResult == null || callResult.isEmpty()) {
+        if (!callResult.isSuccess()) {
             //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
             for (int i = 0; i < results.length; i++) {
-                results[i] = "Failed";
+                results[i] = "Failed: " + callResult.getDetails();
             }
             return new SetFirewallRulesAnswer(cmd, false, results);
         }
@@ -7844,9 +7846,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             if (domainName != null && !domainName.isEmpty()) {
                 args += " -e " + domainName;
             }
-            String result = routerProxy("vpc_guestnw.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-            if (result == null || result.isEmpty()) {
-                return new SetupGuestNetworkAnswer(cmd, false, "creating guest network failed due to " + ((result == null) ? "null" : result));
+            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_guestnw.sh", args);
+            if (!result.isSuccess()) {
+                return new SetupGuestNetworkAnswer(cmd, false, "creating guest network failed due to " + result.getDetails());
             }
             return new SetupGuestNetworkAnswer(cmd, true, "success");
         } catch (Exception e) {
@@ -7919,9 +7921,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args += " -N ";
             args += cmd.getPeerGuestCidrList();
         }
-        String result = routerProxy("ipsectunnel.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "Configure site to site VPN failed! ");
+        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "Configure site to site VPN failed! " + result.getDetails());
         }
         return new Answer(cmd);
     }
@@ -7944,9 +7946,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args += " -c ";
             args += "eth" + correctVif.getDevice(conn);
 
-            String result = routerProxy("vpc_snat.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-            if (result == null || result.isEmpty()) {
-                throw new InternalErrorException("Xen plugin \"vpc_snat\" failed.");
+            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_snat.sh", args);
+            if (!result.isSuccess()) {
+                throw new InternalErrorException("Xen plugin \"vpc_snat\" failed." + result.getDetails());
             }
             return new SetSourceNatAnswer(cmd, true, "success");
         } catch (Exception e) {
@@ -7958,7 +7960,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
     private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) {
         String[] results = new String[cmd.getRules().length];
-        String callResult;
+        ExecutionResult callResult;
         Connection conn = getConnection();
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
@@ -7985,11 +7987,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 args += " -d " + "eth" + vif.getDevice(conn);
                 args += " -a " + sb.toString();
 
-                callResult = routerProxy("vpc_privategw_acl.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-                if (callResult == null || callResult.isEmpty()) {
+                callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_privategw_acl.sh", args);
+                if (!callResult.isSuccess()) {
                     //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
                     for (int i = 0; i < results.length; i++) {
-                        results[i] = "Failed";
+                        results[i] = "Failed:" + callResult.getDetails();
                     }
                     return new SetNetworkACLAnswer(cmd, false, results);
                 }
@@ -8000,11 +8002,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
                 args += " -a " + sb.toString();
 
-                callResult = routerProxy("vpc_acl.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-                if (callResult == null || callResult.isEmpty()) {
+                callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_acl.sh", args);
+                if (!callResult.isSuccess()) {
                     //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
                     for (int i = 0; i < results.length; i++) {
-                        results[i] = "Failed";
+                        results[i] = "Failed:" + callResult.getDetails();
                     }
                     return new SetNetworkACLAnswer(cmd, false, results);
                 }
@@ -8031,10 +8033,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             args += " -r " + rule.getDstIp();
             args += " -d " + rule.getStringDstPortRange().replace(":", "-");
 
-            String result = routerProxy("vpc_portforwarding.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
+            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_portforwarding.sh", args);
 
-            if (result == null || result.isEmpty()) {
-                results[i++] = "Failed";
+            if (!result.isSuccess()) {
+                results[i++] = "Failed:" + result.getDetails();
                 endResult = false;
             } else {
                 results[i++] = null;
@@ -8044,7 +8046,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
     }
 
     private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) {
-        String callResult;
+        ExecutionResult callResult;
         try {
             String[] results = new String[cmd.getStaticRoutes().length];
             String[][] rules = cmd.generateSRouteRules();
@@ -8054,11 +8056,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 sb.append(srRules[i]).append(',');
             }
             String args = "-a " + sb.toString();
-            callResult = routerProxy("vpc_staticroute.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
-            if (callResult == null || callResult.isEmpty()) {
+            callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_staticroute.sh", args);
+            if (!callResult.isSuccess()) {
                 //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
                 for (int i = 0; i < results.length; i++) {
-                    results[i] = "Failed";
+                    results[i] = "Failed:" + callResult.getDetails();
                 }
                 return new SetStaticRouteAnswer(cmd, false, results);
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java
index df43430..7e26a5c 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java
@@ -16,25 +16,6 @@
 // under the License.
 package com.cloud.hypervisor.xen.resource;
 
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import javax.ejb.Local;
-
-import org.apache.log4j.Logger;
-import org.apache.xmlrpc.XmlRpcException;
-
-import com.xensource.xenapi.Connection;
-import com.xensource.xenapi.Host;
-import com.xensource.xenapi.Network;
-import com.xensource.xenapi.PIF;
-import com.xensource.xenapi.Types.IpConfigurationMode;
-import com.xensource.xenapi.Types.XenAPIException;
-import com.xensource.xenapi.VLAN;
-import com.xensource.xenapi.VM;
-
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.CheckOnHostAnswer;
 import com.cloud.agent.api.CheckOnHostCommand;
@@ -47,6 +28,22 @@ import com.cloud.agent.api.StartupCommand;
 import com.cloud.resource.ServerResource;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.script.Script;
+import com.xensource.xenapi.Connection;
+import com.xensource.xenapi.Host;
+import com.xensource.xenapi.Network;
+import com.xensource.xenapi.PIF;
+import com.xensource.xenapi.Types.IpConfigurationMode;
+import com.xensource.xenapi.Types.XenAPIException;
+import com.xensource.xenapi.VLAN;
+import com.xensource.xenapi.VM;
+import org.apache.log4j.Logger;
+import org.apache.xmlrpc.XmlRpcException;
+
+import javax.ejb.Local;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
 
 @Local(value = ServerResource.class)
 public class XenServer56Resource extends CitrixResourceBase {
@@ -127,7 +124,7 @@ public class XenServer56Resource extends CitrixResourceBase {
 
     @Override
     protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) {
-        String args = "netusage.sh " + privateIpAddress + " ";
+        String args = "";
         if (option.equals("get")) {
             args += "-g";
         } else if (option.equals("create")) {
@@ -142,7 +139,7 @@ public class XenServer56Resource extends CitrixResourceBase {
             args += vif;
         }
 
-        return callHostPlugin(conn, "vmops", "routerProxy", "args", args);
+        return executeInVR(privateIpAddress, "netusage.sh", args).getDetails();
     }
 
     protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) {
@@ -151,8 +148,7 @@ public class XenServer56Resource extends CitrixResourceBase {
             String option = cmd.getOption();
             String publicIp = cmd.getGatewayIP();
 
-            String args = "vpc_netusage.sh " + cmd.getPrivateIP();
-            args += " -l " + publicIp + " ";
+            String args = " -l " + publicIp + " ";
             if (option.equals("get")) {
                 args += "-g";
             } else if (option.equals("create")) {
@@ -169,7 +165,7 @@ public class XenServer56Resource extends CitrixResourceBase {
                 return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
             }
 
-            String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
+            String result = executeInVR(cmd.getPrivateIP(), "vpc_netusage.sh", args).getDetails();
             if (option.equals("get") || option.equals("vpn")) {
                 long[] stats = new long[2];
                 if (result != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/scripts/vm/hypervisor/xenserver/vmops
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/vmops b/scripts/vm/hypervisor/xenserver/vmops
index 96b7866..2f0f347 100755
--- a/scripts/vm/hypervisor/xenserver/vmops
+++ b/scripts/vm/hypervisor/xenserver/vmops
@@ -230,12 +230,10 @@ def routerProxy(session, args):
     cmd.insert(0, "/bin/bash")
     try:
         txt = util.pread2(cmd)
-        if txt is None or len(txt) == 0 :
-            txt = 'success'
+        txt = 'succ#' + txt
     except:
         logging.debug("routerProxy command " + sargs + " failed "  )
-        txt = '' 
-
+        txt = 'fail#' + txt
     return txt
 
 @echo
@@ -265,13 +263,12 @@ def createFileInDomr(session, args):
         f.write(file_contents)
         f.close()
         target = "root@" + domrip + ":" + file_path
-        util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',tmpfile, target])
+        txt = util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',tmpfile, target])
         util.pread2(['rm',tmpfile])
-        txt = 'success'
+        txt = 'succ#' + txt
     except:
-        logging.debug(" failed to create HA proxy cfg file ")
-        txt = ''
-
+        logging.debug("failed to create file " + file_path + " in VR, contain: " + file_contents)
+        txt = 'fail#' + txt
     return txt
 
 @echo

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d100f12/utils/src/com/cloud/utils/ExecutionResult.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/ExecutionResult.java b/utils/src/com/cloud/utils/ExecutionResult.java
new file mode 100644
index 0000000..8edb55b
--- /dev/null
+++ b/utils/src/com/cloud/utils/ExecutionResult.java
@@ -0,0 +1,44 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package com.cloud.utils;
+
+public class ExecutionResult {
+    private Boolean success;
+    private String details;
+
+    public ExecutionResult(Boolean success, String details) {
+        this.success = success;
+        this.details = details;
+    }
+
+    public Boolean isSuccess() {
+        return success;
+    }
+
+    public void setSuccess(Boolean success) {
+        this.success = success;
+    }
+
+    public String getDetails() {
+        return details;
+    }
+
+    public void setDetails(String details) {
+        this.details = details;
+    }
+}


[2/4] git commit: updated refs/heads/master to 069bc36

Posted by ya...@apache.org.
CLOUDSTACK-5779: Generalize calling to execute or create file for Vmware


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/2d302259
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/2d302259
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/2d302259

Branch: refs/heads/master
Commit: 2d3022594c94b0359ddced70907c8a95014eec96
Parents: 2d100f1
Author: Sheng Yang <sh...@citrix.com>
Authored: Mon Jan 20 12:03:06 2014 -0800
Committer: Sheng Yang <sh...@citrix.com>
Committed: Fri Jan 24 18:28:00 2014 -0800

----------------------------------------------------------------------
 .../vmware/resource/VmwareResource.java         | 748 +++++--------------
 1 file changed, 201 insertions(+), 547 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2d302259/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 982031b..e5158cb 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@ -312,6 +312,7 @@ import com.cloud.storage.resource.VmwareStorageProcessor;
 import com.cloud.storage.resource.VmwareStorageSubsystemCommandHandler;
 import com.cloud.storage.template.TemplateProp;
 import com.cloud.utils.DateUtil;
+import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.StringUtils;
@@ -705,10 +706,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         String controlIp = getRouterSshControlIp(cmd);
         String args = "";
         String[] results = new String[cmd.getStaticRoutes().length];
+        String[][] rules = cmd.generateSRouteRules();
         int i = 0;
 
-        // Extract and build the arguments for the command to be sent to the VR.
-        String[][] rules = cmd.generateSRouteRules();
         StringBuilder sb = new StringBuilder();
         String[] srRules = rules[0];
         for (int j = 0; j < srRules.length; j++) {
@@ -716,25 +716,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         }
         args += " -a " + sb.toString();
 
-        // Send over the command for execution, via ssh, to the VR.
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticroute.sh " + args);
-
-            if (s_logger.isDebugEnabled())
-                s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args);
+        ExecutionResult result = executeInVR(controlIp, "vpc_staticroute.sh", args);
 
-            if (!result.first()) {
-                s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args);
+        if (!result.isSuccess()) {
+            s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args);
+            while (i < results.length) {
                 results[i++] = "Failed";
-                endResult = false;
-            } else {
-                results[i++] = null;
             }
-        } catch (Throwable e) {
-            s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e);
-            results[i++] = "Failed";
             endResult = false;
         }
         return new SetStaticRouteAnswer(cmd, endResult, results);
@@ -762,41 +750,28 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         } else {
             return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
         }
-        try {
-            if (s_logger.isTraceEnabled()) {
-                s_logger.trace("Executing /opt/cloud/bin/vpc_netusage.sh " + args + " on DomR " + privateIp);
-            }
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
 
-            Pair<Boolean, String> resultPair =
-                    SshHelper.sshExecute(privateIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_netusage.sh " + args);
+        ExecutionResult callResult = executeInVR(privateIp, "vpc_netusage.sh", args);
 
-            if (!resultPair.first()) {
-                throw new Exception(" vpc network usage plugin call failed ");
+        if (!callResult.isSuccess()) {
+            s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + callResult.getDetails());
+        }
 
+        if (option.equals("get") || option.equals("vpn")) {
+            String result = callResult.getDetails();
+            if (result == null || result.isEmpty()) {
+                s_logger.error(" vpc network usage get returns empty ");
             }
-
-            if (option.equals("get") || option.equals("vpn")) {
-                String result = resultPair.second();
-                if (result == null || result.isEmpty()) {
-                    throw new Exception(" vpc network usage get returns empty ");
-                }
-                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 new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]);
+            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 new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]);
             }
-            return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
-        } catch (Throwable e) {
-
-            s_logger.error(
-                    "Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e);
         }
         return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
     }
@@ -813,23 +788,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
 
         args += " -c " + config;
 
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/monitor_service.sh " + args);
-
-            if (!result.first()) {
-                String msg = "monitor_service.sh failed on domain router " + controlIp + " failed " + result.second();
-                s_logger.error(msg);
-                return new Answer(cmd, false, msg);
-            }
-
-            return new Answer(cmd);
-
-        } catch (Throwable e) {
-            s_logger.error("Unexpected exception: " + e.toString(), e);
-            return new Answer(cmd, false, "SetMonitorServiceCommand failed due to " + VmwareHelper.getExceptionMessage(e));
+        ExecutionResult result = executeInVR(controlIp, "monitor_service.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
+        return new Answer(cmd);
     }
 
     protected Answer execute(SetPortForwardingRulesCommand cmd) {
@@ -851,24 +814,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -r " + rule.getDstIp();
             args += " -d " + rule.getStringDstPortRange();
 
-            try {
-                VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-                Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/firewall_nat.sh " + args);
-
-                if (s_logger.isDebugEnabled())
-                    s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/firewall_nat.sh " + args);
-
-                if (!result.first()) {
-                    s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args);
-                    results[i++] = "Failed";
-                    endResult = false;
-                } else {
-                    results[i++] = null;
-                }
-            } catch (Throwable e) {
-                s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e);
+            ExecutionResult result = executeInVR(controlIp, "firewall_nat.sh", args);
+            if (!result.isSuccess()) {
+                s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args);
                 results[i++] = "Failed";
                 endResult = false;
+            } else {
+                results[i++] = null;
             }
         }
 
@@ -905,40 +857,21 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -a " + sb.toString();
         }
 
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-
-            Pair<Boolean, String> result = null;
-
-            if (trafficType == FirewallRule.TrafficType.Egress) {
-                result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/firewall_egress.sh " + args);
-            } else {
-                result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/firewall_ingress.sh " + args);
-            }
-
-            if (s_logger.isDebugEnabled()) {
-                if (trafficType == FirewallRule.TrafficType.Egress) {
-                    s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/firewall_egress.sh " + args);
-                } else {
-                    s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/firewall_ingress.sh " + args);
-                }
-            }
+        ExecutionResult result = null;
 
-            if (!result.first()) {
-                s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args);
-                //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
-                for (int i = 0; i < results.length; i++) {
-                    results[i] = "Failed";
-                }
+        if (trafficType == FirewallRule.TrafficType.Egress) {
+            result = executeInVR(controlIp, "firewall_egress.sh", args);
+        } else {
+            result = executeInVR(controlIp, "firewall_ingress.sh", args);
+        }
 
-                return new SetFirewallRulesAnswer(cmd, false, results);
-            }
-        } catch (Throwable e) {
-            s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e);
+        if (!result.isSuccess()) {
+            s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args);
             //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
             for (int i = 0; i < results.length; i++) {
                 results[i] = "Failed";
             }
+
             return new SetFirewallRulesAnswer(cmd, false, results);
         }
 
@@ -951,37 +884,24 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         }
 
         String[] results = new String[cmd.getRules().length];
-        VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
         String controlIp = getRouterSshControlIp(cmd);
 
         int i = 0;
         boolean endResult = true;
         for (StaticNatRuleTO rule : cmd.getRules()) {
-            // Prepare command to be send to VPC VR
             String args = "";
             args += rule.revoked() ? " -D" : " -A";
             args += " -l " + rule.getSrcIp();
             args += " -r " + rule.getDstIp();
 
-            // Invoke command on VPC VR.
-            try {
-                Pair<Boolean, String> result =
-                        SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticnat.sh " + args);
-
-                if (s_logger.isDebugEnabled())
-                    s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticnat.sh " + args);
+            ExecutionResult result = executeInVR(controlIp, "vpc_staticnat.sh", args);
 
-                if (!result.first()) {
-                    s_logger.error("SetVPCStaticNatRulesCommand failure on setting one rule. args: " + args);
-                    results[i++] = "Failed";
-                    endResult = false;
-                } else {
-                    results[i++] = null;
-                }
-            } catch (Throwable e) {
-                s_logger.error("SetVPCStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e);
+            if (!result.isSuccess()) {
+                s_logger.error("SetVPCStaticNatRulesCommand failure on setting one rule. args: " + args);
                 results[i++] = "Failed";
                 endResult = false;
+            } else {
+                results[i++] = null;
             }
         }
         return new SetStaticNatRulesAnswer(cmd, results, endResult);
@@ -1015,25 +935,15 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -d " + rule.getStringSrcPortRange();
             args += " -G ";
 
-            try {
-                VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-                String controlIp = getRouterSshControlIp(cmd);
-                Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/firewall_nat.sh " + args);
-
-                if (s_logger.isDebugEnabled())
-                    s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/firewall_nat.sh " + args);
+            String controlIp = getRouterSshControlIp(cmd);
+            ExecutionResult result = executeInVR(controlIp, "firewall_nat.sh", args);
 
-                if (!result.first()) {
-                    s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args);
-                    results[i++] = "Failed";
-                    endResult = false;
-                } else {
-                    results[i++] = null;
-                }
-            } catch (Throwable e) {
-                s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e);
+            if (!result.isSuccess()) {
+                s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args);
                 results[i++] = "Failed";
                 endResult = false;
+            } else {
+                results[i++] = null;
             }
         }
         return new SetStaticNatRulesAnswer(cmd, results, endResult);
@@ -1076,67 +986,61 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             return new Answer(cmd, false, "Fail to create LB config file in VR");
         }
 
-        try {
-
-            String[][] rules = cfgtr.generateFwRules(cmd);
+        String[][] rules = cfgtr.generateFwRules(cmd);
 
-            String[] addRules = rules[LoadBalancerConfigurator.ADD];
-            String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
-            String[] statRules = rules[LoadBalancerConfigurator.STATS];
+        String[] addRules = rules[LoadBalancerConfigurator.ADD];
+        String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
+        String[] statRules = rules[LoadBalancerConfigurator.STATS];
 
-            String args = "";
-            StringBuilder sb = new StringBuilder();
-            if (addRules.length > 0) {
-                for (int i = 0; i < addRules.length; i++) {
-                    sb.append(addRules[i]).append(',');
-                }
-
-                args += " -a " + sb.toString();
+        String args = "";
+        StringBuilder sb = new StringBuilder();
+        if (addRules.length > 0) {
+            for (int i = 0; i < addRules.length; i++) {
+                sb.append(addRules[i]).append(',');
             }
 
-            sb = new StringBuilder();
-            if (removeRules.length > 0) {
-                for (int i = 0; i < removeRules.length; i++) {
-                    sb.append(removeRules[i]).append(',');
-                }
+            args += " -a " + sb.toString();
+        }
 
-                args += " -d " + sb.toString();
+        sb = new StringBuilder();
+        if (removeRules.length > 0) {
+            for (int i = 0; i < removeRules.length; i++) {
+                sb.append(removeRules[i]).append(',');
             }
 
-            sb = new StringBuilder();
-            if (statRules.length > 0) {
-                for (int i = 0; i < statRules.length; i++) {
-                    sb.append(statRules[i]).append(',');
-                }
+            args += " -d " + sb.toString();
+        }
 
-                args += " -s " + sb.toString();
+        sb = new StringBuilder();
+        if (statRules.length > 0) {
+            for (int i = 0; i < statRules.length; i++) {
+                sb.append(statRules[i]).append(',');
             }
 
-            Pair<Boolean, String> result;
-            if (cmd.getVpcId() == null) {
-                args = " -i " + routerIp + args;
-                result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/loadbalancer.sh " + args);
-            } else {
-                args = " -i " + cmd.getNic().getIp() + args;
-                result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_loadbalancer.sh " + args);
-            }
-            // Invoke the command
+            args += " -s " + sb.toString();
+        }
 
-            if (!result.first()) {
-                String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second();
-                s_logger.error(msg);
+        ExecutionResult result;
+        if (cmd.getVpcId() == null) {
+            args = " -i " + routerIp + args;
+            result = executeInVR(controlIp, "loadbalancer.sh", args);
+        } else {
+            args = " -i " + cmd.getNic().getIp() + args;
+            result = executeInVR(controlIp, "vpc_loadbalancer.sh", args);
+        }
+        // Invoke the command
 
-                return new Answer(cmd, false, msg);
-            }
+        if (!result.isSuccess()) {
+            String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.getDetails();
+            s_logger.error(msg);
 
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed");
-            }
-            return new Answer(cmd);
-        } catch (Throwable e) {
-            s_logger.error("Unexpected exception: " + e.toString(), e);
-            return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e));
+            return new Answer(cmd, false, msg);
         }
+
+        if (s_logger.isInfoEnabled()) {
+            s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed");
+        }
+        return new Answer(cmd);
     }
 
     //
@@ -1246,13 +1150,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
                 args += " -e " + domainName;
             }
 
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_guestnw.sh " + args);
+            ExecutionResult result = executeInVR(routerIp, "vpc_guestnw.sh", args);
 
-            if (!result.first()) {
-                String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second();
+            if (!result.isSuccess()) {
+                String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.getDetails();
                 s_logger.error(msg);
-
                 return new SetupGuestNetworkAnswer(cmd, false, msg);
             }
 
@@ -1303,6 +1205,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         String routerIp = getRouterSshControlIp(cmd);
         IpAddressTO pubIp = cmd.getIpAddress();
+
         try {
             int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress());
             String args = "";
@@ -1313,11 +1216,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -c ";
             args += "eth" + ethDeviceNum;
 
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_snat.sh " + args);
+            ExecutionResult result = executeInVR(routerIp, "vpc_snat.sh", args);
 
-            if (!result.first()) {
-                String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second();
+            if (!result.isSuccess()) {
+                String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.getDetails();
                 s_logger.error(msg);
 
                 return new SetSourceNatAnswer(cmd, false, msg);
@@ -1357,16 +1259,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             NicTO nic = cmd.getNic();
             int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, nic.getMac());
             String args = "";
-            Pair<Boolean, String> result;
+            ExecutionResult result;
 
             if (privateGw != null) {
                 s_logger.debug("Private gateway configuration is set");
                 args += " -d " + "eth" + ethDeviceNum;
                 args += " -a " + sb.toString();
-                result = SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privategw_acl.sh " + args);
+                result = executeInVR(routerIp, "vpc_privategw_acl.sh", args);
 
-                if (!result.first()) {
-                    String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second();
+                if (!result.isSuccess()) {
+                    String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.getDetails();
                     s_logger.error(msg);
                     return new SetNetworkACLAnswer(cmd, false, results);
                 }
@@ -1377,10 +1279,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
                 args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
                 args += " -a " + sb.toString();
 
-                result = SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_acl.sh " + args);
+                result = executeInVR(routerIp, "vpc_acl.sh", args);
 
-                if (!result.first()) {
-                    String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second();
+                if (!result.isSuccess()) {
+                    String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.getDetails();
                     s_logger.error(msg);
 
                     return new SetNetworkACLAnswer(cmd, false, results);
@@ -1417,19 +1319,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -r " + rule.getDstIp();
             args += " -d " + rule.getStringDstPortRange().replace(":", "-");
 
-            try {
-                Pair<Boolean, String> sshResult =
-                        SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_portforwarding.sh " + args);
+            ExecutionResult sshResult = executeInVR(routerIp, "vpc_portforwarding.sh", args);
 
-                if (!sshResult.first()) {
-                    results[i++] = "Failed";
-                    endResult = false;
-                } else {
-                    results[i++] = null;
-                }
-            } catch (Exception e) {
+            if (!sshResult.isSuccess()) {
                 results[i++] = "Failed";
                 endResult = false;
+            } else {
+                results[i++] = null;
             }
         }
         return new SetPortForwardingRulesAnswer(cmd, results, endResult);
@@ -1486,25 +1382,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += cmd.getPeerGuestCidrList();
         }
 
-        Pair<Boolean, String> result;
-        try {
-            result = SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipsectunnel.sh " + args);
+        ExecutionResult result = executeInVR(routerIp, "ipsectunnel.sh", args);
 
-            if (!result.first()) {
-                s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second());
+        if (!result.isSuccess()) {
+            s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.getDetails());
 
-                return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.second());
-            }
+            return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.getDetails());
+        }
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "Setup site2site VPN falied due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, "Setup site2site VPN failed due to " + VmwareHelper.getExceptionMessage(e));
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
         }
-        return new Answer(cmd, true, result.second());
+
+        return new Answer(cmd, true, result.getDetails());
     }
 
     private PlugNicAnswer execute(PlugNicCommand cmd) {
@@ -1687,10 +1577,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         args += " -n ";
         args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
 
-        Pair<Boolean, String> result =
-                SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_ipassoc.sh " + args);
+        ExecutionResult result = executeInVR(routerIp, "vpc_ipassoc.sh", args);
 
-        if (!result.first()) {
+        if (!result.isSuccess()) {
             throw new InternalErrorException("Unable to assign public IP address");
         }
 
@@ -1700,10 +1589,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             snatArgs += " -c ";
             snatArgs += "eth" + ethDeviceNum;
 
-            Pair<Boolean, String> result_gateway =
-                    SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privateGateway.sh " + snatArgs);
+            ExecutionResult result_gateway = executeInVR(routerIp, "vpc_privateGateway.sh", snatArgs);
 
-            if (!result_gateway.first()) {
+            if (!result_gateway.isSuccess()) {
                 throw new InternalErrorException("Unable to configure source NAT for public IP address.");
             }
         }
@@ -1787,21 +1675,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -n ";
         }
 
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args);
-        }
-
-        VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-        Pair<Boolean, String> result =
-                SshHelper.sshExecute(privateIpAddress, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args);
+        ExecutionResult result = executeInVR(privateIpAddress, "ipassoc.sh", args);
 
-        if (!result.first()) {
-            s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second());
-            throw new Exception("ipassoc failed due to " + result.second());
+        if (!result.isSuccess()) {
+            s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.getDetails());
+            throw new Exception("ipassoc failed due to " + result.getDetails());
         }
 
         if (removeVif) {
-
             String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK);
             int nicMasks = Integer.parseInt(nicMasksStr);
             nicMasks &= ~(1 << publicNicInfo.first().intValue());
@@ -1954,8 +1835,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         return new IpAssocAnswer(cmd, results);
     }
 
-    protected Pair<Boolean, String> executeInVR(String script, String routerIP, String args) {
+    protected ExecutionResult executeInVR(String routerIP, String script, String args) {
         Pair<Boolean, String> result;
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Run command on VR: " + routerIP + ", script: " + script + " with args: " + args);
+        }
+
         try {
             VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
             result = SshHelper.sshExecute(routerIP, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/" + script + " " + args);
@@ -1964,12 +1850,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             s_logger.error(msg);
             result = new Pair<Boolean, String>(false, msg);
         }
-        return result;
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug(script + " execution result: " + result.first().toString());
+        }
+        return new ExecutionResult(result.first(), result.second());
     }
 
     protected Answer execute(SavePasswordCommand cmd) {
         if (s_logger.isInfoEnabled()) {
-
             s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " +
                     StringUtils.getMaskedPasswordForDisplay(cmd.getPassword()));
         }
@@ -1978,7 +1866,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         final String password = cmd.getPassword();
         final String vmIpAddress = cmd.getVmIpAddress();
 
-        // Run save_password_to_domr.sh
         String args = " -v " + vmIpAddress;
 
         if (s_logger.isDebugEnabled()) {
@@ -1988,19 +1875,17 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
 
         args += " -p " + password;
 
-        Pair<Boolean, String> result = executeInVR("savepassword.sh", controlIp, args);
-        if (!result.first()) {
-            s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second());
-            return new Answer(cmd, false, "SavePassword failed due to " + result.second());
+        //TODO: Password should be masked, cannot output to log directly
+        ExecutionResult result = executeInVR(controlIp, "savepassword.sh", args);
+        if (!result.isSuccess()) {
+            s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.getDetails());
+            return new Answer(cmd, false, result.getDetails());
         }
-    return new Answer(cmd);
+
+        return new Answer(cmd);
     }
 
     protected Answer execute(DhcpEntryCommand cmd) {
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd));
-        }
-
         // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null
 
         String args = " -m " + cmd.getVmMac();
@@ -2030,68 +1915,29 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += " -N";
         }
 
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/edithosts.sh " + args);
-        }
-
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/edithosts.sh " + args);
-
-            if (!result.first()) {
-                s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second());
-
-                return new Answer(cmd, false, "DhcpEntry failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("dhcp_entry command on domain router " + controlIp + " completed");
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "edithosts.sh", args);
 
-        } catch (Throwable e) {
-            String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
 
         return new Answer(cmd);
     }
 
     protected Answer execute(final CreateIpAliasCommand cmd) {
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("Executing createIpAlias command: " + _gson.toJson(cmd));
-        }
         cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
         String args = "";
         for (IpAliasTO ipaliasto : ipAliasTOs) {
             args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
         }
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/createIpAlias " + args);
-        }
-
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/createIpAlias.sh " + args);
-
-            if (!result.first()) {
-                s_logger.error("CreateIpAlias command on domr " + controlIp + " failed, message: " + result.second());
 
-                return new Answer(cmd, false, "createipAlias failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("createIpAlias command on domain router " + controlIp + " completed");
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "createIpAlias.sh", args);
 
-        } catch (Throwable e) {
-            String msg = "createIpAlias failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
 
         return new Answer(cmd);
@@ -2101,9 +1947,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
         List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("Executing deleteIpAlias command: " + _gson.toJson(cmd));
-        }
         String args = "";
         for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
@@ -2112,39 +1955,18 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
         }
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/deleteIpAlias " + args);
-        }
-
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/deleteIpAlias.sh " + args);
 
-            if (!result.first()) {
-                s_logger.error("deleteIpAlias command on domr " + controlIp + " failed, message: " + result.second());
-
-                return new Answer(cmd, false, "deleteIpAlias failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("deleteIpAlias command on domain router " + controlIp + " completed");
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "deleteIpAlias.sh", args);
 
-        } catch (Throwable e) {
-            String msg = "deleteIpAlias failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
 
         return new Answer(cmd);
     }
 
     protected Answer execute(final DnsMasqConfigCommand cmd) {
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("Executing dnsmasqConfig command: " + _gson.toJson(cmd));
-        }
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String controlIp = getRouterSshControlIp(cmd);
 
@@ -2155,166 +1977,68 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         for (DhcpTO dhcpTo : dhcpTos) {
             args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
         }
-        VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-        mgr.getSystemVMKeyFile();
-
-        try {
-            Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/dnsmasq.sh " + args);
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Run command on domain router " + routerIp + ",  /opt/cloud/bin/dnsmasq.sh");
-            }
 
-            if (!result.first()) {
-                s_logger.error("Unable update dnsmasq config file");
-                return new Answer(cmd, false, "dnsmasq config update failed due to: " + result.second());
-            }
+        ExecutionResult result = executeInVR(controlIp, "dnsmasq.sh", args);
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("dnsmasq config command on domain router " + routerIp + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "Dnsmasqconfig command failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
 
         return new Answer(cmd);
     }
 
     protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd));
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh ");
+        String controlIp = getRouterSshControlIp(cmd);
+        String args = "";
+        for (String ip : cmd.getVpnIps()) {
+            args += ip + " ";
         }
 
-        Pair<Boolean, String> result;
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh ";
-            for (String ip : cmd.getVpnIps()) {
-                cmdline += " " + ip;
-            }
-
-            result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, cmdline);
-
-            if (!result.first()) {
-                s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " +
-                        result.second());
+        ExecutionResult result = executeInVR(controlIp, "checkbatchs2svpn.sh", args);
 
-                return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second());
-            }
-
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
+        if (!result.isSuccess()) {
+            return new CheckS2SVpnConnectionsAnswer(cmd, false, result.getDetails());
         }
-        return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second());
+
+        return new CheckS2SVpnConnectionsAnswer(cmd, true, result.getDetails());
     }
 
     protected Answer execute(CheckRouterCommand cmd) {
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd));
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh ");
-        }
-
-        Pair<Boolean, String> result;
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/checkrouter.sh ");
-
-            if (!result.first()) {
-                s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second());
-
-                return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second());
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "checkrouter.sh", null);
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "CheckRouterCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new CheckRouterAnswer(cmd, msg);
+        if (!result.isSuccess()) {
+            return new CheckRouterAnswer(cmd, result.getDetails());
         }
-        return new CheckRouterAnswer(cmd, result.second(), true);
+        return new CheckRouterAnswer(cmd, result.getDetails(), true);
     }
 
     protected Answer execute(GetDomRVersionCmd cmd) {
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd));
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh ");
-        }
-
-        Pair<Boolean, String> result;
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/get_template_version.sh ");
-
-            if (!result.first()) {
-                s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second());
-
-                return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed due to " + result.second());
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "get_template_version.sh", null);
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("GetDomRVersionCmd on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "GetDomRVersionCmd failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new GetDomRVersionAnswer(cmd, msg);
+        if (!result.isSuccess()) {
+            return new GetDomRVersionAnswer(cmd, result.getDetails());
         }
-        String[] lines = result.second().split("&");
+        String[] lines = result.getDetails().split("&");
         if (lines.length != 2) {
-            return new GetDomRVersionAnswer(cmd, result.second());
+            return new GetDomRVersionAnswer(cmd, result.getDetails());
         }
-        return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]);
+        return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]);
     }
 
     protected Answer execute(BumpUpPriorityCommand cmd) {
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd));
-            s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/bumpup_priority.sh ");
-        }
-
-        Pair<Boolean, String> result;
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-            String controlIp = getRouterSshControlIp(cmd);
-            result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/bumpup_priority.sh ");
-
-            if (!result.first()) {
-                s_logger.error("BumpUpPriority command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second());
-
-                return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result.second());
-            }
+        String controlIp = getRouterSshControlIp(cmd);
+        ExecutionResult result = executeInVR(controlIp, "bumpup_priority.sh", null);
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("BumpUpPriorityCommand on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "BumpUpPriorityCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
-        if (result.second() == null || result.second().isEmpty()) {
-            return new Answer(cmd, true, result.second());
-        }
-        return new Answer(cmd, false, result.second());
+
+        return new Answer(cmd);
     }
 
     protected Answer execute(VmDataCommand cmd) {
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd));
-        }
-
         String controlIp = getRouterSshControlIp(cmd);
         Map<String, List<String[]>> data = new HashMap<String, List<String[]>>();
         data.put(cmd.getVmIpAddress(), cmd.getVmData());
@@ -2326,23 +2050,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
 
         String args = "-d " + json;
 
-        VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
+        ExecutionResult result = executeInVR(controlIp, "vmdata.py", args);
 
-        try {
-            Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vmdata.py " + args);
-            if (!result.first()) {
-                s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second());
-                return new Answer(cmd, false, "VmDataCommand failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("vm_data command on domain router " + controlIp + " completed");
-            }
-        } catch (Throwable e) {
-            String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
+
         return new Answer(cmd);
     }
 
@@ -3588,44 +3301,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         argsBuf.append(" -C ").append(cmd.getLocalCidr());
         argsBuf.append(" -i ").append(cmd.getPublicInterface());
 
-        try {
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh ");
-            }
 
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString());
+        ExecutionResult result = executeInVR(controlIp, "vpn_l2tp.sh", argsBuf.toString());
 
-            if (!result.first()) {
-                s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second());
-
-                return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second());
-            }
-
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed");
-            }
-
-        } catch (Throwable e) {
-            if (e instanceof RemoteException) {
-                s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
-                invalidateServiceContext();
-            }
-
-            String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e);
-            s_logger.error(msg, e);
-            return new Answer(cmd, false, msg);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
 
         return new Answer(cmd);
     }
 
     protected Answer execute(final VpnUsersCfgCommand cmd) {
-        VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-
         String controlIp = getRouterSshControlIp(cmd);
+
         for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) {
             StringBuffer argsBuf = new StringBuffer();
             if (!userpwd.isAdd()) {
@@ -3634,29 +3322,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
                 argsBuf.append(" -u ").append(userpwd.getUsernamePassword());
             }
 
-            try {
-
-                if (s_logger.isDebugEnabled()) {
-                    s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh ");
-                }
-
-                Pair<Boolean, String> result =
-                        SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString());
-
-                if (!result.first()) {
-                    s_logger.error("VpnUserCfg command on domR failed, message: " + result.second());
-
-                    return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second());
-                }
-            } catch (Throwable e) {
-                if (e instanceof RemoteException) {
-                    s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
-                    invalidateServiceContext();
-                }
+            ExecutionResult result = executeInVR(controlIp, "vpn_l2tp.sh", argsBuf.toString());
 
-                String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e);
-                s_logger.error(msg, e);
-                return new Answer(cmd, false, msg);
+            if (!result.isSuccess()) {
+                return new Answer(cmd, false, result.getDetails());
             }
         }
 
@@ -6519,28 +6188,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             args += ethName;
         }
 
-        try {
-            if (s_logger.isTraceEnabled()) {
-                s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress);
-            }
+        ExecutionResult result = executeInVR(privateIpAddress, "netusage.sh", args);
 
-            VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
-
-            Pair<Boolean, String> result =
-                    SshHelper.sshExecute(privateIpAddress, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args);
-
-            if (!result.first()) {
-                return null;
-            }
-
-            return result.second();
-        } catch (Throwable e) {
-            s_logger.error(
-                    "Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " +
-                            VmwareHelper.getExceptionMessage(e), e);
+        if (!result.isSuccess()) {
+            return null;
         }
 
-        return null;
+        return result.getDetails();
     }
 
     private long[] getNetworkStats(String privateIP) {


[4/4] git commit: updated refs/heads/master to 069bc36

Posted by ya...@apache.org.
CLOUDSTACK-5779: Make CitrixResource to use VirtualRoutingResource


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/069bc368
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/069bc368
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/069bc368

Branch: refs/heads/master
Commit: 069bc3686e29c6a683a41fe2beca687ce22d4186
Parents: 285f23f
Author: Sheng Yang <sh...@citrix.com>
Authored: Mon Jan 20 12:03:07 2014 -0800
Committer: Sheng Yang <sh...@citrix.com>
Committed: Fri Jan 24 18:28:31 2014 -0800

----------------------------------------------------------------------
 .../virtualnetwork/VirtualRoutingResource.java  |   30 +-
 .../xen/resource/CitrixResourceBase.java        | 1082 +++---------------
 2 files changed, 195 insertions(+), 917 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/069bc368/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index f63824e..1ed3864 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -215,9 +215,6 @@ public class VirtualRoutingResource {
 
     private Answer execute(SetFirewallRulesCommand cmd) {
         String[] results = new String[cmd.getRules().length];
-        for (int i = 0; i < cmd.getRules().length; i++) {
-            results[i] = "Failed";
-        }
         String routerAccessIp = cmd.getRouterAccessIp();
         String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
 
@@ -260,9 +257,13 @@ public class VirtualRoutingResource {
         }
 
         if (!result.isSuccess()) {
+            //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
+            for (int i = 0; i < results.length; i++) {
+                results[i] = "Failed: " + result.getDetails();
+            }
             return new SetFirewallRulesAnswer(cmd, false, results);
         }
-        return new SetFirewallRulesAnswer(cmd, true, null);
+        return new SetFirewallRulesAnswer(cmd, true, results);
 
     }
 
@@ -292,7 +293,7 @@ public class VirtualRoutingResource {
         return new SetPortForwardingRulesAnswer(cmd, results, endResult);
     }
 
-    protected Answer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) {
+    protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) {
         String[] results = new String[cmd.getRules().length];
         int i = 0;
         boolean endResult = true;
@@ -315,7 +316,7 @@ public class VirtualRoutingResource {
 
     }
 
-    private Answer execute(SetStaticNatRulesCommand cmd) {
+    private SetStaticNatRulesAnswer execute(SetStaticNatRulesCommand cmd) {
         if (cmd.getVpcId() != null) {
             return SetVPCStaticNatRules(cmd);
         }
@@ -364,7 +365,11 @@ public class VirtualRoutingResource {
             tmpCfgFileContents += "\n";
         }
 
-        if (!_vrDeployer.createFileInVR(cmd.getRouterAccessIp(), "/etc/haproxy/", "haproxy.cfg.new", tmpCfgFileContents).isSuccess()) {
+        String tmpCfgFilePath = "/etc/haproxy/";
+        String tmpCfgFileName = "haproxy.cfg.new";
+        ExecutionResult result = _vrDeployer.createFileInVR(cmd.getRouterAccessIp(), tmpCfgFilePath, tmpCfgFileName, tmpCfgFileContents);
+
+        if (!result.isSuccess()) {
             return new Answer(cmd, false, "Fail to copy LB config file to VR");
         }
 
@@ -401,8 +406,6 @@ public class VirtualRoutingResource {
             args += " -s " + sb.toString();
         }
 
-        ExecutionResult result;
-
         if (cmd.getVpcId() == null) {
             args = " -i " + routerIp + args;
             result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "loadbalancer.sh", args);
@@ -490,6 +493,7 @@ public class VirtualRoutingResource {
         for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
         }
+        //this is to ensure that thre is some argument passed to the deleteipAlias script  when there are no revoked rules.
         args = args + "- ";
         List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
@@ -514,7 +518,7 @@ public class VirtualRoutingResource {
 
         String args = "";
         for (String ip : cmd.getVpnIps()) {
-            args += " " + ip;
+            args += ip + " ";
         }
 
         ExecutionResult result = _vrDeployer.executeInVR(routerIP, "checkbatchs2svpn.sh", args);
@@ -551,9 +555,9 @@ public class VirtualRoutingResource {
     }
 
     protected Answer execute(Site2SiteVpnCfgCommand cmd) {
-        String args;
+        String args = "";
         if (cmd.isCreate()) {
-            args = "-A";
+            args += "-A";
             args += " -l ";
             args += cmd.getLocalPublicIp();
             args += " -n ";
@@ -584,7 +588,7 @@ public class VirtualRoutingResource {
                 args += " -p ";
             }
         } else {
-            args = "-D";
+            args += "-D";
             args += " -r ";
             args += cmd.getPeerGatewayIp();
             args += " -n ";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/069bc368/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 05311b8..a817e26 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -45,7 +45,6 @@ import javax.ejb.Local;
 import javax.naming.ConfigurationException;
 import javax.xml.parsers.DocumentBuilderFactory;
 
-import org.apache.commons.codec.binary.Base64;
 import org.apache.log4j.Logger;
 import org.apache.xmlrpc.XmlRpcException;
 import org.w3c.dom.Document;
@@ -53,7 +52,6 @@ import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 
-import com.google.gson.Gson;
 import com.trilead.ssh2.SCPClient;
 import com.xensource.xenapi.Bond;
 import com.xensource.xenapi.Connection;
@@ -90,17 +88,12 @@ import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeAnswer;
 import com.cloud.agent.api.AttachVolumeCommand;
-import com.cloud.agent.api.BumpUpPriorityCommand;
 import com.cloud.agent.api.CheckHealthAnswer;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkAnswer;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostAnswer;
 import com.cloud.agent.api.CheckOnHostCommand;
-import com.cloud.agent.api.CheckRouterAnswer;
-import com.cloud.agent.api.CheckRouterCommand;
-import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer;
-import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
 import com.cloud.agent.api.CheckVirtualMachineAnswer;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
@@ -113,8 +106,6 @@ import com.cloud.agent.api.CreateVMSnapshotCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.DeleteVMSnapshotAnswer;
 import com.cloud.agent.api.DeleteVMSnapshotCommand;
-import com.cloud.agent.api.GetDomRVersionAnswer;
-import com.cloud.agent.api.GetDomRVersionCmd;
 import com.cloud.agent.api.GetHostStatsAnswer;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetStorageStatsAnswer;
@@ -174,7 +165,6 @@ import com.cloud.agent.api.SecurityGroupRuleAnswer;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.SetupAnswer;
 import com.cloud.agent.api.SetupCommand;
-import com.cloud.agent.api.SetupGuestNetworkAnswer;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.StartAnswer;
 import com.cloud.agent.api.StartCommand;
@@ -194,35 +184,11 @@ import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
-import com.cloud.agent.api.routing.CreateIpAliasCommand;
-import com.cloud.agent.api.routing.DeleteIpAliasCommand;
-import com.cloud.agent.api.routing.DhcpEntryCommand;
-import com.cloud.agent.api.routing.DnsMasqConfigCommand;
-import com.cloud.agent.api.routing.IpAliasTO;
-import com.cloud.agent.api.routing.IpAssocAnswer;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
-import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
-import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
-import com.cloud.agent.api.routing.SavePasswordCommand;
-import com.cloud.agent.api.routing.SetFirewallRulesAnswer;
-import com.cloud.agent.api.routing.SetFirewallRulesCommand;
-import com.cloud.agent.api.routing.SetMonitorServiceCommand;
-import com.cloud.agent.api.routing.SetNetworkACLAnswer;
 import com.cloud.agent.api.routing.SetNetworkACLCommand;
-import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer;
-import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
-import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
-import com.cloud.agent.api.routing.SetSourceNatAnswer;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
-import com.cloud.agent.api.routing.SetStaticNatRulesAnswer;
-import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
-import com.cloud.agent.api.routing.SetStaticRouteAnswer;
-import com.cloud.agent.api.routing.SetStaticRouteCommand;
-import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand;
-import com.cloud.agent.api.routing.VmDataCommand;
-import com.cloud.agent.api.routing.VpnUsersCfgCommand;
 import com.cloud.agent.api.storage.CreateAnswer;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
@@ -232,28 +198,23 @@ import com.cloud.agent.api.storage.ResizeVolumeAnswer;
 import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
 import com.cloud.agent.api.to.DataTO;
-import com.cloud.agent.api.to.DhcpTO;
 import com.cloud.agent.api.to.DiskTO;
-import com.cloud.agent.api.to.FirewallRuleTO;
 import com.cloud.agent.api.to.IpAddressTO;
 import com.cloud.agent.api.to.NfsTO;
 import com.cloud.agent.api.to.NicTO;
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-import com.cloud.agent.api.to.StaticNatRuleTO;
 import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.api.to.VolumeTO;
+import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
+import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.exception.InternalErrorException;
 import com.cloud.host.Host.Type;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
-import com.cloud.network.HAProxyConfigurator;
-import com.cloud.network.LoadBalancerConfigurator;
 import com.cloud.network.Networks;
 import com.cloud.network.Networks.BroadcastDomainType;
 import com.cloud.network.Networks.IsolationType;
 import com.cloud.network.Networks.TrafficType;
 import com.cloud.network.PhysicalNetworkSetupInfo;
-import com.cloud.network.rules.FirewallRule;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.hypervisor.HypervisorResource;
 import com.cloud.storage.Storage;
@@ -292,7 +253,7 @@ import com.cloud.vm.snapshot.VMSnapshot;
  *
  */
 @Local(value = ServerResource.class)
-public abstract class CitrixResourceBase implements ServerResource, HypervisorResource {
+public abstract class CitrixResourceBase implements ServerResource, HypervisorResource, VirtualRouterDeployer {
     private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class);
     protected static final XenServerConnectionPool ConnPool = XenServerConnectionPool.getInstance();
     protected String _name;
@@ -339,6 +300,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
     protected StorageSubsystemCommandHandler storageHandler;
     protected int _maxNics = 7;
 
+    protected VirtualRoutingResource _vrResource;
+
     public enum SRType {
         NFS, LVM, ISCSI, ISO, LVMOISCSI, LVMOHBA, EXT, FILE;
 
@@ -448,30 +411,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         Class<? extends Command> clazz = cmd.getClass();
         if (clazz == CreateCommand.class) {
             return execute((CreateCommand)cmd);
-        } else if (clazz == SetPortForwardingRulesCommand.class) {
-            return execute((SetPortForwardingRulesCommand)cmd);
-        } else if (clazz == SetStaticNatRulesCommand.class) {
-            return execute((SetStaticNatRulesCommand)cmd);
-        } else if (clazz == LoadBalancerConfigCommand.class) {
-            return execute((LoadBalancerConfigCommand)cmd);
-        } else if (clazz == IpAssocCommand.class) {
-            return execute((IpAssocCommand)cmd);
+        } else if (cmd instanceof NetworkElementCommand) {
+            return _vrResource.executeRequest(cmd);
         } else if (clazz == CheckConsoleProxyLoadCommand.class) {
             return execute((CheckConsoleProxyLoadCommand)cmd);
         } else if (clazz == WatchConsoleProxyLoadCommand.class) {
             return execute((WatchConsoleProxyLoadCommand)cmd);
-        } else if (clazz == SavePasswordCommand.class) {
-            return execute((SavePasswordCommand)cmd);
-        } else if (clazz == DhcpEntryCommand.class) {
-            return execute((DhcpEntryCommand)cmd);
-        } else if (clazz == CreateIpAliasCommand.class) {
-            return execute((CreateIpAliasCommand)cmd);
-        } else if (clazz == DnsMasqConfigCommand.class) {
-            return execute((DnsMasqConfigCommand)cmd);
-        } else if (clazz == DeleteIpAliasCommand.class) {
-            return execute((DeleteIpAliasCommand)cmd);
-        } else if (clazz == VmDataCommand.class) {
-            return execute((VmDataCommand)cmd);
         } else if (clazz == ReadyCommand.class) {
             return execute((ReadyCommand)cmd);
         } else if (clazz == GetHostStatsCommand.class) {
@@ -530,10 +475,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             return execute((PoolEjectCommand)cmd);
         } else if (clazz == StartCommand.class) {
             return execute((StartCommand)cmd);
-        } else if (clazz == RemoteAccessVpnCfgCommand.class) {
-            return execute((RemoteAccessVpnCfgCommand)cmd);
-        } else if (clazz == VpnUsersCfgCommand.class) {
-            return execute((VpnUsersCfgCommand)cmd);
         } else if (clazz == CheckSshCommand.class) {
             return execute((CheckSshCommand)cmd);
         } else if (clazz == SecurityGroupRulesCmd.class) {
@@ -560,54 +501,28 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             return execute((OvsDestroyTunnelCommand)cmd);
         } else if (clazz == UpdateHostPasswordCommand.class) {
             return execute((UpdateHostPasswordCommand)cmd);
-        } else if (cmd instanceof CheckRouterCommand) {
-            return execute((CheckRouterCommand)cmd);
-        } else if (cmd instanceof SetFirewallRulesCommand) {
-            return execute((SetFirewallRulesCommand)cmd);
-        } else if (cmd instanceof BumpUpPriorityCommand) {
-            return execute((BumpUpPriorityCommand)cmd);
         } else if (cmd instanceof ClusterSyncCommand) {
             return execute((ClusterSyncCommand)cmd);
-        } else if (cmd instanceof GetDomRVersionCmd) {
-            return execute((GetDomRVersionCmd)cmd);
         } else if (clazz == CheckNetworkCommand.class) {
             return execute((CheckNetworkCommand)cmd);
-        } else if (clazz == SetupGuestNetworkCommand.class) {
-            return execute((SetupGuestNetworkCommand)cmd);
         } else if (clazz == PlugNicCommand.class) {
             return execute((PlugNicCommand)cmd);
         } else if (clazz == UnPlugNicCommand.class) {
             return execute((UnPlugNicCommand)cmd);
-        } else if (clazz == IpAssocVpcCommand.class) {
-            return execute((IpAssocVpcCommand)cmd);
-        } else if (clazz == SetSourceNatCommand.class) {
-            return execute((SetSourceNatCommand)cmd);
-        } else if (clazz == SetNetworkACLCommand.class) {
-            return execute((SetNetworkACLCommand)cmd);
-        } else if (clazz == SetPortForwardingRulesVpcCommand.class) {
-            return execute((SetPortForwardingRulesVpcCommand)cmd);
-        } else if (clazz == SetStaticRouteCommand.class) {
-            return execute((SetStaticRouteCommand)cmd);
-        } else if (clazz == Site2SiteVpnCfgCommand.class) {
-            return execute((Site2SiteVpnCfgCommand)cmd);
-        } else if (clazz == CheckS2SVpnConnectionsCommand.class) {
-            return execute((CheckS2SVpnConnectionsCommand)cmd);
         } else if (cmd instanceof StorageSubSystemCommand) {
-            return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
+            return storageHandler.handleStorageCommands((StorageSubSystemCommand) cmd);
         } else if (clazz == CreateVMSnapshotCommand.class) {
-            return execute((CreateVMSnapshotCommand)cmd);
+            return execute((CreateVMSnapshotCommand) cmd);
         } else if (clazz == DeleteVMSnapshotCommand.class) {
-            return execute((DeleteVMSnapshotCommand)cmd);
+            return execute((DeleteVMSnapshotCommand) cmd);
         } else if (clazz == RevertToVMSnapshotCommand.class) {
-            return execute((RevertToVMSnapshotCommand)cmd);
+            return execute((RevertToVMSnapshotCommand) cmd);
         } else if (clazz == NetworkRulesVmSecondaryIpCommand.class) {
-            return execute((NetworkRulesVmSecondaryIpCommand)cmd);
+            return execute((NetworkRulesVmSecondaryIpCommand) cmd);
         } else if (clazz == ScaleVmCommand.class) {
             return execute((ScaleVmCommand)cmd);
         } else if (clazz == PvlanSetupCommand.class) {
             return execute((PvlanSetupCommand)cmd);
-        } else if (clazz == SetMonitorServiceCommand.class) {
-            return execute((SetMonitorServiceCommand)cmd);
         } else if (clazz == PerformanceMonitorCommand.class) {
             return execute((PerformanceMonitorCommand)cmd);
         } else {
@@ -615,6 +530,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
     }
 
+    @Override
     public ExecutionResult executeInVR(String routerIP, String script, String args) {
         Connection conn = getConnection();
         String rc = callHostPlugin(conn, "vmops", "routerProxy", "args", script + " " + routerIP + " " + args);
@@ -622,13 +538,40 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5));
     }
 
-    protected ExecutionResult createFileInVR(String routerIp, String path, String content) {
+    @Override
+    public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) {
         Connection conn = getConnection();
-        String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", path, "filecontents", content);
+        String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", path + filename, "filecontents", content);
         // Fail case would be start with "fail#"
         return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5));
     }
 
+    @Override
+    public ExecutionResult prepareCommand(NetworkElementCommand cmd) {
+        //Update IP used to access router
+        cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
+
+        if (cmd instanceof IpAssocVpcCommand) {
+            return prepareNetworkElementCommand((IpAssocVpcCommand)cmd);
+        } else if (cmd instanceof IpAssocCommand) {
+            return prepareNetworkElementCommand((IpAssocCommand)cmd);
+        } else if (cmd instanceof SetupGuestNetworkCommand) {
+            return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd);
+        } else if (cmd instanceof SetSourceNatCommand) {
+            return prepareNetworkElementCommand((SetSourceNatCommand)cmd);
+        } else if (cmd instanceof SetNetworkACLCommand) {
+            return prepareNetworkElementCommand((SetNetworkACLCommand)cmd);
+        }
+        return new ExecutionResult(true, null);
+    }
+
+    @Override
+    public ExecutionResult cleanupCommand(NetworkElementCommand cmd) {
+        if (cmd instanceof IpAssocCommand && !(cmd instanceof IpAssocVpcCommand)) {
+            cleanupNetworkElementCommand((IpAssocCommand)cmd);
+        }
+        return new ExecutionResult(true, null);
+    }
 
     private Answer execute(PerformanceMonitorCommand cmd) {
         Connection conn = getConnection();
@@ -1973,48 +1916,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return new Answer(cmd);
     }
 
-    private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
-        String args = "";
-        for (String ip : cmd.getVpnIps()) {
-            args += ip + " ";
-        }
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "checkbatchs2svpn.sh", args);
-        if (!result.isSuccess()) {
-            return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
-        }
-        return new CheckS2SVpnConnectionsAnswer(cmd, true, result.getDetails());
-    }
-
-    private CheckRouterAnswer execute(CheckRouterCommand cmd) {
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "checkrouter.sh", null);
-        if (!result.isSuccess()) {
-            return new CheckRouterAnswer(cmd, "CheckRouterCommand failed");
-        }
-        return new CheckRouterAnswer(cmd, result.getDetails(), true);
-    }
-
-    private GetDomRVersionAnswer execute(GetDomRVersionCmd cmd) {
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "get_template_version.sh", null);
-        if (!result.isSuccess()) {
-            return new GetDomRVersionAnswer(cmd, "getDomRVersionCmd failed");
-        }
-        String[] lines = result.getDetails().split("&");
-        if (lines.length != 2) {
-            return new GetDomRVersionAnswer(cmd, result.getDetails());
-        }
-        return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]);
-    }
-
-    private Answer execute(BumpUpPriorityCommand cmd) {
-        Connection conn = getConnection();
-        String args = "bumpup_priority.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
-        if (result == null || result.isEmpty()) {
-            return new Answer(cmd, false, "BumpUpPriorityCommand failed");
-        }
-        return new Answer(cmd, true, result);
-    }
-
     protected MaintainAnswer execute(MaintainCommand cmd) {
         Connection conn = getConnection();
         try {
@@ -2040,530 +1941,147 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
     }
 
-    protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesCommand cmd) {
-        getConnection();
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String[] results = new String[cmd.getRules().length];
-        int i = 0;
-
-        boolean endResult = true;
-        for (PortForwardingRuleTO rule : cmd.getRules()) {
-            StringBuilder args = new StringBuilder();
-            args.append(rule.revoked() ? " -D " : " -A ");
-            args.append(" -P ").append(rule.getProtocol().toLowerCase());
-            args.append(" -l ").append(rule.getSrcIp());
-            args.append(" -p ").append(rule.getStringSrcPortRange());
-            args.append(" -r ").append(rule.getDstIp());
-            args.append(" -d ").append(rule.getStringDstPortRange());
-
-            ExecutionResult result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
-
-            if (!result.isSuccess()) {
-                results[i++] = "Failed: " + result.getDetails();
-                endResult = false;
-            } else {
-                results[i++] = null;
-            }
-        }
-
-        return new SetPortForwardingRulesAnswer(cmd, results, endResult);
-    }
-
-    protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) {
-        //String args = routerIp;
-        String[] results = new String[cmd.getRules().length];
-        int i = 0;
-        boolean endResult = true;
-        for (StaticNatRuleTO rule : cmd.getRules()) {
-            String args = rule.revoked() ? "-D" : "-A";
-            args += " -l " + rule.getSrcIp();
-            args += " -r " + rule.getDstIp();
-            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_staticnat.sh", args);
-
-            if (!result.isSuccess()) {
-                results[i++] = "Failed: " + result.getDetails();
-                endResult = false;
-            } else {
-                results[i++] = null;
-            }
+    protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) {
+        if (option.equals("get")) {
+            return "0:0";
         }
-        return new SetStaticNatRulesAnswer(cmd, results, endResult);
+        return null;
     }
 
-    protected SetStaticNatRulesAnswer execute(SetStaticNatRulesCommand cmd) {
-        if (cmd.getVpcId() != null) {
-            return SetVPCStaticNatRules(cmd);
-        }
-        getConnection();
-
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String[] results = new String[cmd.getRules().length];
+    protected ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
+        Connection conn = getConnection();
         int i = 0;
-        boolean endResult = true;
-        for (StaticNatRuleTO rule : cmd.getRules()) {
-            //1:1 NAT needs instanceip;publicip;domrip;op
-            StringBuilder args = new StringBuilder();
-            args.append(rule.revoked() ? " -D " : " -A ");
-            args.append(" -l ").append(rule.getSrcIp());
-            args.append(" -r ").append(rule.getDstIp());
-
-            if (rule.getProtocol() != null) {
-                args.append(" -P ").append(rule.getProtocol().toLowerCase());
-            }
-
-            args.append(" -d ").append(rule.getStringSrcPortRange());
-            args.append(" -G ");
-
-            ExecutionResult result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
-
-            if (!result.isSuccess()) {
-                results[i++] = "Failed:" + result.getDetails();
-                endResult = false;
-            } else {
-                results[i++] = null;
-            }
-        }
-
-        return new SetStaticNatRulesAnswer(cmd, results, endResult);
-    }
-
-    protected Answer execute(final CreateIpAliasCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
-        String args = "";
-        for (IpAliasTO ipaliasto : ipAliasTOs) {
-            args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
-        }
-        ExecutionResult result = executeInVR(routerIp, "createipAlias.sh", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "CreateIPAliasCommand failed due to " + result.getDetails());
-        }
-
-        return new Answer(cmd);
-    }
-
-    protected Answer execute(final DeleteIpAliasCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
-        String args = "";
-        for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
-            args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
-        }
-        //this is to ensure that thre is some argument passed to the deleteipAlias script  when there are no revoked rules.
-        args = args + "- ";
-        List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
-        for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
-            args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
-        }
-        ExecutionResult result = executeInVR(routerIp, "deleteipAlias", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "DeleteipAliasCommand failed due to " + result.getDetails());
-        }
-
-        return new Answer(cmd);
-    }
-
-    protected Answer execute(final DnsMasqConfigCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        List<DhcpTO> dhcpTos = cmd.getIps();
-        String args = "";
-        for (DhcpTO dhcpTo : dhcpTos) {
-            args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
-        }
-
-        ExecutionResult result = executeInVR(routerIp, "dnsmasq.sh", args);
-
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "DnsMasqconfigCommand failed due to " + result.getDetails());
-        }
-
-        return new Answer(cmd);
-    }
-
-    protected Answer execute(final LoadBalancerConfigCommand cmd) {
+        String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 
-        if (routerIp == null) {
-            return new Answer(cmd);
-        }
-
-        LoadBalancerConfigurator cfgtr = new HAProxyConfigurator();
-        String[] config = cfgtr.generateConfiguration(cmd);
-        String tmpCfgFileContents = "";
-        for (int i = 0; i < config.length; i++) {
-            tmpCfgFileContents += config[i];
-            tmpCfgFileContents += "\n";
-        }
-        String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new";
-        ExecutionResult result = createFileInVR(routerIp, tmpCfgFilePath, tmpCfgFileContents);
-
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "LoadBalancerConfigCommand failed to create HA proxy cfg file: " + result.getDetails());
-        }
-
-        String[][] rules = cfgtr.generateFwRules(cmd);
-
-        String[] addRules = rules[LoadBalancerConfigurator.ADD];
-        String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
-        String[] statRules = rules[LoadBalancerConfigurator.STATS];
-
-        String ip = cmd.getNic().getIp();
-        String args = " -i " + ip;
-        StringBuilder sb = new StringBuilder();
-        if (addRules.length > 0) {
-            for (int i = 0; i < addRules.length; i++) {
-                sb.append(addRules[i]).append(',');
-            }
-
-            args += " -a " + sb.toString();
-        }
-
-        sb = new StringBuilder();
-        if (removeRules.length > 0) {
-            for (int i = 0; i < removeRules.length; i++) {
-                sb.append(removeRules[i]).append(',');
-            }
-
-            args += " -d " + sb.toString();
-        }
-
-        sb = new StringBuilder();
-        if (statRules.length > 0) {
-            for (int i = 0; i < statRules.length; i++) {
-                sb.append(statRules[i]).append(',');
-            }
-
-            args += " -s " + sb.toString();
-        }
-
-        if (cmd.getVpcId() == null) {
-            args = " -i " + routerIp + args;
-            result = executeInVR(routerIp, "loadbalancer.sh", args);
-        } else {
-            args = " -i " + cmd.getNic().getIp() + args;
-            result = executeInVR(routerIp, "vpc_loadbalancer.sh", args);
-        }
-
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "LoadBalancerConfigCommand failed: " + result.getDetails());
-        }
-        return new Answer(cmd);
-    }
-
-    protected synchronized Answer execute(final DhcpEntryCommand cmd) {
-        String args = " -m " + cmd.getVmMac();
-        if (cmd.getVmIpAddress() != null) {
-            args += " -4 " + cmd.getVmIpAddress();
-        }
-        args += " -h " + cmd.getVmName();
-
-        if (cmd.getDefaultRouter() != null) {
-            args += " -d " + cmd.getDefaultRouter();
-        }
-
-        if (cmd.getDefaultDns() != null) {
-            args += " -n " + cmd.getDefaultDns();
-        }
-
-        if (cmd.getStaticRoutes() != null) {
-            args += " -s " + cmd.getStaticRoutes();
-        }
-
-        if (cmd.getVmIp6Address() != null) {
-            args += " -6 " + cmd.getVmIp6Address();
-            args += " -u " + cmd.getDuid();
-        }
-
-        if (!cmd.isDefault()) {
-            args += " -N";
-        }
-
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "DhcpEntry failed: " + result.getDetails());
-        }
-        return new Answer(cmd);
-    }
-
-    protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) {
-        String args = "";
-        if (cmd.isCreate()) {
-            args += " -r " + cmd.getIpRange();
-            args += " -p " + cmd.getPresharedKey();
-            args += " -s " + cmd.getVpnServerIp();
-            args += " -l " + cmd.getLocalIp();
-            args += " -c ";
-        } else {
-            args += " -d ";
-            args += " -s " + cmd.getVpnServerIp();
-        }
-        args += " -C " + cmd.getLocalCidr();
-        args += " -i " + cmd.getPublicInterface();
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "Configure VPN failed" + result.getDetails());
-        }
-        return new Answer(cmd);
-    }
-
-    protected synchronized Answer execute(final VpnUsersCfgCommand cmd) {
-        for (VpnUsersCfgCommand.UsernamePassword userpwd: cmd.getUserpwds()) {
-            String args = "";
-            if (!userpwd.isAdd()) {
-                args += " -U " + userpwd.getUsername();
-            } else {
-                args += " -u " + userpwd.getUsernamePassword();
-            }
-            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
-            if (!result.isSuccess()) {
-                return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername() + ":" + result.getDetails());
-            }
-        }
-
-        return new Answer(cmd);
-    }
-
-    protected Answer execute(final VmDataCommand cmd) {
-        Map<String, List<String[]>> data = new HashMap<String, List<String[]>>();
-        data.put(cmd.getVmIpAddress(), cmd.getVmData());
-        String json = new Gson().toJson(data);
-        json = Base64.encodeBase64String(json.getBytes());
-
-        String args = "-d " + json;
-
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vmdata.py", args);
-
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "vm_data failed:" + result.getDetails());
-        } else {
-            return new Answer(cmd);
-        }
-
-    }
-
-    protected Answer execute(final SavePasswordCommand cmd) {
-        final String password = cmd.getPassword();
-        final String vmIpAddress = cmd.getVmIpAddress();
-
-        String args = " -v " + vmIpAddress;
-        args += " -p " + password;
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "savepassword.sh", args);
-
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "savePassword failed:" + result.getDetails());
-        }
-        return new Answer(cmd);
-    }
-
-    protected void assignPublicIpAddress(Connection conn, String vmName, String privateIpAddress, String publicIpAddress, boolean add, boolean firstIP,
-            boolean sourceNat, String vlanId, String vlanGateway, String vlanNetmask, String vifMacAddress, Integer networkRate, TrafficType trafficType, String name)
-                    throws InternalErrorException {
-
         try {
-            VM router = getVM(conn, vmName);
-
-            NicTO nic = new NicTO();
-            nic.setMac(vifMacAddress);
-            nic.setType(trafficType);
-            if (vlanId == null) {
-                nic.setBroadcastType(BroadcastDomainType.Native);
-            } else {
-                URI uri = BroadcastDomainType.fromString(vlanId);
-                nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
-                nic.setBroadcastUri(uri);
-            }
-            nic.setDeviceId(0);
-            nic.setNetworkRateMbps(networkRate);
-            nic.setName(name);
-
-            Network network = getNetwork(conn, nic);
-
-            // Determine the correct VIF on DomR to associate/disassociate the
-            // IP address with
-            VIF correctVif = getCorrectVif(conn, router, network);
-
-            // If we are associating an IP address and DomR doesn't have a VIF
-            // for the specified vlan ID, we need to add a VIF
-            // If we are disassociating the last IP address in the VLAN, we need
-            // to remove a VIF
-            boolean addVif = false;
-            boolean removeVif = false;
-            if (add && correctVif == null) {
-                addVif = true;
-            }
+            IpAddressTO[] ips = cmd.getIpAddresses();
+            for (IpAddressTO ip : ips) {
 
-            if (addVif) {
-                // Add a new VIF to DomR
-                String vifDeviceNum = getLowestAvailableVIFDeviceNum(conn, router);
+                VM router = getVM(conn, routerName);
 
-                if (vifDeviceNum == null) {
-                    throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn));
+                NicTO nic = new NicTO();
+                nic.setMac(ip.getVifMacAddress());
+                nic.setType(ip.getTrafficType());
+                if (ip.getBroadcastUri()== null) {
+                    nic.setBroadcastType(BroadcastDomainType.Native);
+                } else {
+                    URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri());
+                    nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
+                    nic.setBroadcastUri(uri);
                 }
+                nic.setDeviceId(0);
+                nic.setNetworkRateMbps(ip.getNetworkRate());
+                nic.setName(ip.getNetworkName());
 
-                nic.setDeviceId(Integer.parseInt(vifDeviceNum));
-
-                correctVif = createVif(conn, vmName, router, null, nic);
-                correctVif.plug(conn);
-                // Add iptables rule for network usage
-                networkUsage(conn, privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn));
-            }
-
-            if (correctVif == null) {
-                throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with.");
-            }
-
-            String args = "";
-
-            if (add) {
-                args += " -A ";
-            } else {
-                args += " -D ";
-            }
-
-            if (sourceNat) {
-                args += " -s";
-            }
-            if (firstIP) {
-                args += " -f";
-            }
-
-            String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask));
-            args += " -l ";
-            args += publicIpAddress + "/" + cidrSize;
+                Network network = getNetwork(conn, nic);
 
-            args += " -c ";
-            args += "eth" + correctVif.getDevice(conn);
+                // Determine the correct VIF on DomR to associate/disassociate the
+                // IP address with
+                VIF correctVif = getCorrectVif(conn, router, network);
 
-            args += " -g ";
-            args += vlanGateway;
-
-            if (addVif) {
-                //To indicate this is new interface created
-                args += " -n";
-            }
+                // If we are associating an IP address and DomR doesn't have a VIF
+                // for the specified vlan ID, we need to add a VIF
+                // If we are disassociating the last IP address in the VLAN, we need
+                // to remove a VIF
+                boolean addVif = false;
+                if (ip.isAdd() && correctVif == null) {
+                    addVif = true;
+                }
 
-            ExecutionResult result = executeInVR(privateIpAddress, "ipassoc.sh", args);
+                if (addVif) {
+                    // Add a new VIF to DomR
+                    String vifDeviceNum = getLowestAvailableVIFDeviceNum(conn, router);
 
-            if (!result.isSuccess()) {
-                throw new InternalErrorException("Xen plugin \"ipassoc\" failed." + result.getDetails());
-            }
+                    if (vifDeviceNum == null) {
+                        throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn));
+                    }
 
-            if (removeVif) {
-                network = correctVif.getNetwork(conn);
+                    nic.setDeviceId(Integer.valueOf(vifDeviceNum));
 
-                // Mark this vif to be removed from network usage
-                networkUsage(conn, privateIpAddress, "deleteVif", "eth" + correctVif.getDevice(conn));
+                    correctVif = createVif(conn, routerName, router, null, nic);
+                    correctVif.plug(conn);
+                    // Add iptables rule for network usage
+                    networkUsage(conn, routerIp, "addVif", "eth" + correctVif.getDevice(conn));
+                }
 
-                // Remove the VIF from DomR
-                correctVif.unplug(conn);
-                correctVif.destroy(conn);
+                if (correctVif == null) {
+                    throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with.");
+                }
 
-                // Disable the VLAN network if necessary
-                disableVlanNetwork(conn, network);
+                ip.setNicDevId(Integer.valueOf(correctVif.getDevice(conn)));
+                ip.setNewNic(addVif);
             }
-
-        } catch (XenAPIException e) {
-            String msg = "Unable to assign public IP address due to " + e.toString();
-            s_logger.warn(msg, e);
-            throw new InternalErrorException(msg);
-        } catch (final XmlRpcException e) {
-            String msg = "Unable to assign public IP address due to " + e.getMessage();
-            s_logger.warn(msg, e);
-            throw new InternalErrorException(msg);
+        } catch (InternalErrorException e) {
+            s_logger.error("Ip Assoc failure on applying one ip due to exception:  ", e);
+            return new ExecutionResult(false, e.getMessage());
+        } catch (Exception e) {
+            return new ExecutionResult(false, e.getMessage());
         }
+        return new ExecutionResult(true, null);
     }
 
-    protected void assignVPCPublicIpAddress(Connection conn, String vmName, String routerIp, IpAddressTO ip) throws Exception {
-
+    protected ExecutionResult cleanupNetworkElementCommand(IpAssocCommand cmd) {
+        Connection conn = getConnection();
+        String[] results = new String[cmd.getIpAddresses().length];
+        int i = 0;
+        String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
+        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         try {
-            VM router = getVM(conn, vmName);
+            IpAddressTO[] ips = cmd.getIpAddresses();
+            for (IpAddressTO ip : ips) {
+
+                VM router = getVM(conn, routerName);
 
-            VIF correctVif = getVifByMac(conn, router, ip.getVifMacAddress());
-            if (correctVif == null) {
-                if (ip.isAdd()) {
-                    throw new InternalErrorException("Failed to find DomR VIF to associate IP with.");
+                NicTO nic = new NicTO();
+                nic.setMac(ip.getVifMacAddress());
+                nic.setType(ip.getTrafficType());
+                if (ip.getBroadcastUri()== null) {
+                    nic.setBroadcastType(BroadcastDomainType.Native);
                 } else {
-                    s_logger.debug("VIF to deassociate IP with does not exist, return success");
-                    return;
+                    URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri());
+                    nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
+                    nic.setBroadcastUri(uri);
                 }
-            }
-
-            String args = "";
-            String snatArgs = "";
+                nic.setDeviceId(0);
+                nic.setNetworkRateMbps(ip.getNetworkRate());
+                nic.setName(ip.getNetworkName());
 
-            if (ip.isAdd()) {
-                args += " -A ";
-                snatArgs += " -A ";
-            } else {
-                args += " -D ";
-                snatArgs += " -D ";
-            }
-
-            args += " -l ";
-            args += ip.getPublicIp();
-
-            args += " -c ";
-            args += "eth" + correctVif.getDevice(conn);
-
-            args += " -g ";
-            args += ip.getVlanGateway();
+                Network network = getNetwork(conn, nic);
 
-            args += " -m ";
-            args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
+                // Determine the correct VIF on DomR to associate/disassociate the
+                // IP address with
+                VIF correctVif = getCorrectVif(conn, router, network);
 
-            args += " -n ";
-            args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
+                // If we are disassociating the last IP address in the VLAN, we need
+                // to remove a VIF
+                boolean removeVif = false;
 
-            ExecutionResult result = executeInVR(routerIp, "vpc_ipassoc.sh", args);
-            if (!result.isSuccess()) {
-                throw new InternalErrorException("Xen plugin \"vpc_ipassoc\" failed." + result.getDetails());
-            }
-
-            if (ip.isSourceNat()) {
-                snatArgs += " -l " + ip.getPublicIp();
-                snatArgs += " -c " + "eth" + correctVif.getDevice(conn);
-
-                result = executeInVR(routerIp, "vpc_privateGateway.sh", snatArgs);
-                if (!result.isSuccess()) {
-                    throw new InternalErrorException("Xen plugin \"vpc_privateGateway\" failed." + result.getDetails());
+                if (correctVif == null) {
+                    throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with.");
                 }
-            }
 
-        } catch (Exception e) {
-            String msg = "Unable to assign public IP address due to " + e.toString();
-            s_logger.warn(msg, e);
-            throw new Exception(msg);
-        }
-    }
+                if (removeVif) {
+                    network = correctVif.getNetwork(conn);
 
-    protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) {
+                    // Mark this vif to be removed from network usage
+                    networkUsage(conn, routerIp, "deleteVif", "eth" + correctVif.getDevice(conn));
 
-        if (option.equals("get")) {
-            return "0:0";
-        }
-        return null;
-    }
+                    // Remove the VIF from DomR
+                    correctVif.unplug(conn);
+                    correctVif.destroy(conn);
 
-    protected Answer execute(IpAssocCommand cmd) {
-        Connection conn = getConnection();
-        String[] results = new String[cmd.getIpAddresses().length];
-        int i = 0;
-        String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        try {
-            IpAddressTO[] ips = cmd.getIpAddresses();
-            for (IpAddressTO ip : ips) {
-
-                assignPublicIpAddress(conn, routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(),
-                        ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), ip.getNetworkRate(), ip.getTrafficType(), ip.getNetworkName());
-                results[i++] = ip.getPublicIp() + " - success";
+                    // Disable the VLAN network if necessary
+                    disableVlanNetwork(conn, network);
+                }
             }
         } catch (InternalErrorException e) {
             s_logger.error("Ip Assoc failure on applying one ip due to exception:  ", e);
-            results[i++] = IpAssocAnswer.errorResult;
+            return new ExecutionResult(false, e.getMessage());
+        } catch (Exception e) {
+            return new ExecutionResult(false, e.getMessage());
         }
-
-        return new IpAssocAnswer(cmd, results);
+        return new ExecutionResult(true, null);
     }
 
     protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
@@ -6013,8 +5531,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         CheckXenHostInfo();
 
         storageHandler = getStorageHandler();
-        return true;
 
+        _vrResource = new VirtualRoutingResource(this);
+        if (!_vrResource.configure(name, params)) {
+            throw new ConfigurationException("Unable to configure VirtualRoutingResource");
+        }
+        return true;
     }
 
     protected StorageSubsystemCommandHandler getStorageHandler() {
@@ -7484,75 +7006,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return new Answer(cmd, success, "");
     }
 
-    private Answer execute(SetMonitorServiceCommand cmd) {
-        boolean success = true;
-
-        String config = cmd.getConfiguration();
-
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        if (routerIp == null) {
-            return new Answer(cmd);
-        }
-
-        String args = " -c " + config;
-
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "monitor_service.sh", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "SetMonitorServiceCommand failed to create cfg file." + result.getDetails());
-        }
-
-        return new Answer(cmd, success, "");
-
-    }
-
-    protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) {
-        String[] results = new String[cmd.getRules().length];
-        ExecutionResult callResult;
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
-        FirewallRuleTO[] allrules = cmd.getRules();
-        FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
-        if (routerIp == null) {
-            return new SetFirewallRulesAnswer(cmd, false, results);
-        }
-
-        String[][] rules = cmd.generateFwRules();
-        String args = " -F";
-        if (trafficType == FirewallRule.TrafficType.Egress) {
-            args += " -E";
-            if (egressDefault.equals("true")) {
-                args += " -P 1";
-            } else if (egressDefault.equals("System")) {
-                args += " -P 2";
-            } else {
-                args += " -P 0";
-            }
-        }
-        StringBuilder sb = new StringBuilder();
-        String[] fwRules = rules[0];
-        if (fwRules.length > 0) {
-            for (int i = 0; i < fwRules.length; i++) {
-                sb.append(fwRules[i]).append(',');
-            }
-            args += " -a " + sb.toString();
-        }
-
-        if (trafficType == FirewallRule.TrafficType.Egress) {
-            callResult = executeInVR(routerIp, "firewall_egress.sh", args);
-        } else {
-            callResult = executeInVR(routerIp, "firewall_ingress.sh", args);
-        }
-
-        if (!callResult.isSuccess()) {
-            //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
-            for (int i = 0; i < results.length; i++) {
-                results[i] = "Failed: " + callResult.getDetails();
-            }
-            return new SetFirewallRulesAnswer(cmd, false, results);
-        }
-        return new SetFirewallRulesAnswer(cmd, true, results);
-    }
-
     protected Answer execute(final ClusterSyncCommand cmd) {
         Connection conn = getConnection();
         //check if this is master
@@ -7796,28 +7249,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
      * @param cmd
      * @return
      */
-    private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) {
+    private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) {
         Connection conn = getConnection();
         NicTO nic = cmd.getNic();
-        cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String domrGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP);
         String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String gw = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY);
-        String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
-        String domainName = cmd.getNetworkDomain();
-        String dns = cmd.getDefaultDns1();
-        if (dns == null || dns.isEmpty()) {
-            dns = cmd.getDefaultDns2();
-        } else {
-            String dns2 = cmd.getDefaultDns2();
-            if (dns2 != null && !dns2.isEmpty()) {
-                dns += "," + dns2;
-            }
-        }
         try {
             Set<VM> vms = VM.getByNameLabel(conn, domrName);
             if (vms == null || vms.isEmpty()) {
-                return new SetupGuestNetworkAnswer(cmd, false, "Can not find VM " + domrName);
+                return new ExecutionResult(false, "Can not find VM " + domrName);
             }
             VM vm = vms.iterator().next();
             String mac = nic.getMac();
@@ -7830,105 +7269,46 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 }
             }
             if (domrVif == null) {
-                return new SetupGuestNetworkAnswer(cmd, false, "Can not find vif with mac " + mac + " for VM " + domrName);
+                return new ExecutionResult(false, "Can not find vif with mac " + mac + " for VM " + domrName);
             }
 
-            String args = (cmd.isAdd()?" -C":" -D");
-            String dev = "eth" + domrVif.getDevice(conn);
-            args += " -d " + dev;
-            args += " -i " + domrGIP;
-            args += " -g " + gw;
-            args += " -m " + cidr;
-            args += " -n " + NetUtils.getSubNet(domrGIP, nic.getNetmask());
-            if (dns != null && !dns.isEmpty()) {
-                args += " -s " + dns;
-            }
-            if (domainName != null && !domainName.isEmpty()) {
-                args += " -e " + domainName;
-            }
-            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_guestnw.sh", args);
-            if (!result.isSuccess()) {
-                return new SetupGuestNetworkAnswer(cmd, false, "creating guest network failed due to " + result.getDetails());
-            }
-            return new SetupGuestNetworkAnswer(cmd, true, "success");
+            nic.setDeviceId(Integer.valueOf(domrVif.getDevice(conn)));
         } catch (Exception e) {
             String msg = "Creating guest network failed due to " + e.toString();
             s_logger.warn(msg, e);
-            return new SetupGuestNetworkAnswer(cmd, false, msg);
+            return new ExecutionResult(false, msg);
         }
+        return new ExecutionResult(true, null);
     }
 
-    protected IpAssocAnswer execute(IpAssocVpcCommand cmd) {
+    protected ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) {
         Connection conn = getConnection();
-        String[] results = new String[cmd.getIpAddresses().length];
-        int i = 0;
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         try {
             IpAddressTO[] ips = cmd.getIpAddresses();
             for (IpAddressTO ip : ips) {
 
-                assignVPCPublicIpAddress(conn, routerName, routerIp, ip);
-                results[i++] = ip.getPublicIp() + " - success";
+                VM router = getVM(conn, routerName);
+
+                VIF correctVif = getVifByMac(conn, router, ip.getVifMacAddress());
+                if (correctVif == null) {
+                    if (ip.isAdd()) {
+                        throw new InternalErrorException("Failed to find DomR VIF to associate IP with.");
+                    } else {
+                        s_logger.debug("VIF to deassociate IP with does not exist, return success");
+                    }
+                }
+                ip.setNicDevId(Integer.valueOf(correctVif.getDevice(conn)));
             }
         } catch (Exception e) {
             s_logger.error("Ip Assoc failure on applying one ip due to exception:  ", e);
-            results[i++] = IpAssocAnswer.errorResult;
-        }
-
-        return new IpAssocAnswer(cmd, results);
-    }
-
-    protected Answer execute(Site2SiteVpnCfgCommand cmd) {
-        String args = "";
-        if (cmd.isCreate()) {
-            args += " -A";
-            args += " -l ";
-            args += cmd.getLocalPublicIp();
-            args += " -n ";
-            args += cmd.getLocalGuestCidr();
-            args += " -g ";
-            args += cmd.getLocalPublicGateway();
-            args += " -r ";
-            args += cmd.getPeerGatewayIp();
-            args += " -N ";
-            args += cmd.getPeerGuestCidrList();
-            args += " -e ";
-            args += "\"" + cmd.getEspPolicy() + "\"";
-            args += " -i ";
-            args += "\"" + cmd.getIkePolicy() + "\"";
-            args += " -t ";
-            args += Long.toString(cmd.getIkeLifetime());
-            args += " -T ";
-            args += Long.toString(cmd.getEspLifetime());
-            args += " -s ";
-            args += "\"" + cmd.getIpsecPsk() + "\"";
-            args += " -d ";
-            if (cmd.getDpd()) {
-                args += "1";
-            } else {
-                args += "0";
-            }
-            if (cmd.isPassive()) {
-                args += " -p ";
-            }
-        } else {
-            args += " -D";
-            args += " -r ";
-            args += cmd.getPeerGatewayIp();
-            args += " -n ";
-            args += cmd.getLocalGuestCidr();
-            args += " -N ";
-            args += cmd.getPeerGuestCidrList();
-        }
-        ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args);
-        if (!result.isSuccess()) {
-            return new Answer(cmd, false, "Configure site to site VPN failed! " + result.getDetails());
+            return new ExecutionResult(false, e.getMessage());
         }
-        return new Answer(cmd);
+
+        return new ExecutionResult(true, null);
     }
 
-    protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) {
+    protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) {
         Connection conn = getConnection();
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         IpAddressTO pubIp = cmd.getIpAddress();
@@ -7937,139 +7317,33 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
             VIF correctVif = getCorrectVif(conn, router, pubIp);
 
-            String args = "";
-
-            args += " -A ";
-            args += " -l ";
-            args += pubIp.getPublicIp();
+            pubIp.setNicDevId(Integer.valueOf(correctVif.getDevice(conn)));
 
-            args += " -c ";
-            args += "eth" + correctVif.getDevice(conn);
-
-            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_snat.sh", args);
-            if (!result.isSuccess()) {
-                throw new InternalErrorException("Xen plugin \"vpc_snat\" failed." + result.getDetails());
-            }
-            return new SetSourceNatAnswer(cmd, true, "success");
         } catch (Exception e) {
             String msg = "Ip SNAT failure due to " + e.toString();
             s_logger.error(msg, e);
-            return new SetSourceNatAnswer(cmd, false, msg);
+            return new ExecutionResult(false, msg);
         }
+        return new ExecutionResult(true, null);
     }
 
-    private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) {
-        String[] results = new String[cmd.getRules().length];
-        ExecutionResult callResult;
+    protected ExecutionResult prepareNetworkElementCommand(SetNetworkACLCommand cmd) {
         Connection conn = getConnection();
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
 
         try {
             VM router = getVM(conn, routerName);
-            String[][] rules = cmd.generateFwRules();
-            StringBuilder sb = new StringBuilder();
-            String[] aclRules = rules[0];
 
-            for (int i = 0; i < aclRules.length; i++) {
-                sb.append(aclRules[i]).append(',');
-            }
-
-            if (privateGw != null) {
-                s_logger.debug("Private gateway configuration is set");
-            }
             NicTO nic = cmd.getNic();
             VIF vif = getVifByMac(conn, router, nic.getMac());
 
-            if (privateGw != null) {
-                s_logger.debug("Private gateway configuration is set");
-                String args = "";
-                args += " -d " + "eth" + vif.getDevice(conn);
-                args += " -a " + sb.toString();
-
-                callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_privategw_acl.sh", args);
-                if (!callResult.isSuccess()) {
-                    //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
-                    for (int i = 0; i < results.length; i++) {
-                        results[i] = "Failed:" + callResult.getDetails();
-                    }
-                    return new SetNetworkACLAnswer(cmd, false, results);
-                }
-            } else {
-                String args = "";
-                args += " -d " + "eth" + vif.getDevice(conn);
-                args += " -i " + nic.getIp();
-                args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
-                args += " -a " + sb.toString();
-
-                callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_acl.sh", args);
-                if (!callResult.isSuccess()) {
-                    //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
-                    for (int i = 0; i < results.length; i++) {
-                        results[i] = "Failed:" + callResult.getDetails();
-                    }
-                    return new SetNetworkACLAnswer(cmd, false, results);
-                }
-            }
-            return new SetNetworkACLAnswer(cmd, true, results);
-        } catch (Exception e) {
-            String msg = "SetNetworkACL failed due to " + e.toString();
-            s_logger.error(msg, e);
-            return new SetNetworkACLAnswer(cmd, false, results);
-        }
-    }
-
-    protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) {
-        String[] results = new String[cmd.getRules().length];
-        int i = 0;
-
-        boolean endResult = true;
-        for (PortForwardingRuleTO rule : cmd.getRules()) {
-            String args = "";
-            args += rule.revoked() ? " -D" : " -A";
-            args += " -P " + rule.getProtocol().toLowerCase();
-            args += " -l " + rule.getSrcIp();
-            args += " -p " + rule.getStringSrcPortRange();
-            args += " -r " + rule.getDstIp();
-            args += " -d " + rule.getStringDstPortRange().replace(":", "-");
-
-            ExecutionResult result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_portforwarding.sh", args);
-
-            if (!result.isSuccess()) {
-                results[i++] = "Failed:" + result.getDetails();
-                endResult = false;
-            } else {
-                results[i++] = null;
-            }
-        }
-        return new SetPortForwardingRulesAnswer(cmd, results, endResult);
-    }
-
-    private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) {
-        ExecutionResult callResult;
-        try {
-            String[] results = new String[cmd.getStaticRoutes().length];
-            String[][] rules = cmd.generateSRouteRules();
-            StringBuilder sb = new StringBuilder();
-            String[] srRules = rules[0];
-            for (int i = 0; i < srRules.length; i++) {
-                sb.append(srRules[i]).append(',');
-            }
-            String args = "-a " + sb.toString();
-            callResult = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpc_staticroute.sh", args);
-            if (!callResult.isSuccess()) {
-                //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
-                for (int i = 0; i < results.length; i++) {
-                    results[i] = "Failed:" + callResult.getDetails();
-                }
-                return new SetStaticRouteAnswer(cmd, false, results);
-            }
-            return new SetStaticRouteAnswer(cmd, true, results);
+            nic.setDeviceId(Integer.valueOf(vif.getDevice(conn)));
         } catch (Exception e) {
-            String msg = "SetStaticRoute failed due to " + e.toString();
+            String msg = "Prepare SetNetworkACL failed due to " + e.toString();
             s_logger.error(msg, e);
-            return new SetStaticRouteAnswer(cmd, false, null);
+            return new ExecutionResult(false, msg);
         }
+        return new ExecutionResult(true, null);
     }
 
     @Override


[3/4] git commit: updated refs/heads/master to 069bc36

Posted by ya...@apache.org.
CLOUDSTACK-5779: Generalize calling to execute or create file for KVM


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/285f23f1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/285f23f1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/285f23f1

Branch: refs/heads/master
Commit: 285f23f11be9d7908e9e3b087d977dc0e223f4fe
Parents: 2d30225
Author: Sheng Yang <sh...@citrix.com>
Authored: Mon Jan 20 12:03:06 2014 -0800
Committer: Sheng Yang <sh...@citrix.com>
Committed: Fri Jan 24 18:28:25 2014 -0800

----------------------------------------------------------------------
 api/src/com/cloud/agent/api/to/IpAddressTO.java |  17 +
 .../api/routing/NetworkElementCommand.java      |  13 +-
 .../virtualnetwork/VirtualRouterDeployer.java   |  27 +
 .../virtualnetwork/VirtualRoutingResource.java  | 800 +++++++------------
 .../kvm/resource/LibvirtComputingResource.java  | 316 ++++----
 .../cloud/utils/script/OutputInterpreter.java   |   4 +-
 utils/src/com/cloud/utils/script/Script.java    |  15 +-
 7 files changed, 486 insertions(+), 706 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/api/src/com/cloud/agent/api/to/IpAddressTO.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/to/IpAddressTO.java b/api/src/com/cloud/agent/api/to/IpAddressTO.java
index 5f31313..1169820 100644
--- a/api/src/com/cloud/agent/api/to/IpAddressTO.java
+++ b/api/src/com/cloud/agent/api/to/IpAddressTO.java
@@ -33,6 +33,8 @@ public class IpAddressTO {
     private Integer networkRate;
     private TrafficType trafficType;
     private String networkName;
+    private Integer nicDevId;
+    private boolean newNic;
 
     public IpAddressTO(long accountId, String ipAddress, boolean add, boolean firstIP, boolean sourceNat, String broadcastUri, String vlanGateway, String vlanNetmask,
             String vifMacAddress, Integer networkRate, boolean isOneToOneNat) {
@@ -116,4 +118,19 @@ public class IpAddressTO {
         return networkRate;
     }
 
+    public Integer getNicDevId() {
+        return nicDevId;
+    }
+
+    public void setNicDevId(Integer nicDevId) {
+        this.nicDevId = nicDevId;
+    }
+
+    public boolean isNewNic() {
+        return newNic;
+    }
+
+    public void setNewNic(boolean newNic) {
+        this.newNic = newNic;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
index 9a2bea8..217e962 100644
--- a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
+++ b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
@@ -16,10 +16,10 @@
 // under the License.
 package com.cloud.agent.api.routing;
 
-import java.util.HashMap;
-
 import com.cloud.agent.api.Command;
 
+import java.util.HashMap;
+
 public abstract class NetworkElementCommand extends Command {
     HashMap<String, String> accessDetails = new HashMap<String, String>(0);
 
@@ -35,6 +35,8 @@ public abstract class NetworkElementCommand extends Command {
     public static final String VPC_PRIVATE_GATEWAY = "vpc.gateway.private";
     public static final String FIREWALL_EGRESS_DEFAULT = "firewall.egress.default";
 
+    private String routerAccessIp;
+
     protected NetworkElementCommand() {
         super();
     }
@@ -52,4 +54,11 @@ public abstract class NetworkElementCommand extends Command {
         return false;
     }
 
+    public String getRouterAccessIp() {
+        return routerAccessIp;
+    }
+
+    public void setRouterAccessIp(String routerAccessIp) {
+        this.routerAccessIp = routerAccessIp;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java
new file mode 100644
index 0000000..243098a
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java
@@ -0,0 +1,27 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.agent.resource.virtualnetwork;
+
+import com.cloud.agent.api.routing.NetworkElementCommand;
+import com.cloud.utils.ExecutionResult;
+
+public interface VirtualRouterDeployer {
+    ExecutionResult executeInVR(String routerIp, String script, String args);
+    ExecutionResult createFileInVR(String routerIp, String path, String filename, String content);
+    ExecutionResult prepareCommand(NetworkElementCommand cmd);
+    ExecutionResult cleanupCommand(NetworkElementCommand cmd);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index b27ed55..f63824e 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -25,9 +25,8 @@ import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.GetDomRVersionAnswer;
 import com.cloud.agent.api.GetDomRVersionCmd;
-import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
-import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
-import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.SetupGuestNetworkAnswer;
+import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.routing.CreateIpAliasCommand;
 import com.cloud.agent.api.routing.DeleteIpAliasCommand;
 import com.cloud.agent.api.routing.DhcpEntryCommand;
@@ -35,6 +34,7 @@ import com.cloud.agent.api.routing.DnsMasqConfigCommand;
 import com.cloud.agent.api.routing.IpAliasTO;
 import com.cloud.agent.api.routing.IpAssocAnswer;
 import com.cloud.agent.api.routing.IpAssocCommand;
+import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
@@ -42,9 +42,13 @@ import com.cloud.agent.api.routing.SavePasswordCommand;
 import com.cloud.agent.api.routing.SetFirewallRulesAnswer;
 import com.cloud.agent.api.routing.SetFirewallRulesCommand;
 import com.cloud.agent.api.routing.SetMonitorServiceCommand;
+import com.cloud.agent.api.routing.SetNetworkACLAnswer;
+import com.cloud.agent.api.routing.SetNetworkACLCommand;
 import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer;
 import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
 import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
+import com.cloud.agent.api.routing.SetSourceNatAnswer;
+import com.cloud.agent.api.routing.SetSourceNatCommand;
 import com.cloud.agent.api.routing.SetStaticNatRulesAnswer;
 import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
 import com.cloud.agent.api.routing.SetStaticRouteAnswer;
@@ -55,33 +59,22 @@ import com.cloud.agent.api.routing.VpnUsersCfgCommand;
 import com.cloud.agent.api.to.DhcpTO;
 import com.cloud.agent.api.to.FirewallRuleTO;
 import com.cloud.agent.api.to.IpAddressTO;
+import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.PortForwardingRuleTO;
 import com.cloud.agent.api.to.StaticNatRuleTO;
-import com.cloud.exception.InternalErrorException;
 import com.cloud.network.HAProxyConfigurator;
 import com.cloud.network.LoadBalancerConfigurator;
 import com.cloud.network.rules.FirewallRule;
+import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
-import com.cloud.utils.component.ComponentLifecycle;
-import com.cloud.utils.component.Manager;
 import com.cloud.utils.net.NetUtils;
-import com.cloud.utils.script.OutputInterpreter;
-import com.cloud.utils.script.Script;
-import com.cloud.utils.ssh.SshHelper;
 import com.google.gson.Gson;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.log4j.Logger;
 
-import javax.ejb.Local;
 import javax.naming.ConfigurationException;
-import java.io.BufferedReader;
-import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.net.InetSocketAddress;
-import java.net.URL;
-import java.net.URLConnection;
 import java.nio.channels.SocketChannel;
 import java.util.HashMap;
 import java.util.List;
@@ -95,24 +88,27 @@ import java.util.Map;
  *    || Param Name | Description | Values | Default ||
  *  }
  **/
-@Local(value = {VirtualRoutingResource.class})
-public class VirtualRoutingResource implements Manager {
+public class VirtualRoutingResource {
     private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class);
-    private String _publicIpAddress;
-    private String _publicEthIf;
-    private String _privateEthIf;
-    private String _routerProxyPath;
-
-    private int _timeout;
-    private int _startTimeout;
-    private String _scriptsDir;
+    private VirtualRouterDeployer _vrDeployer;
+
     private String _name;
     private int _sleep;
     private int _retry;
     private int _port;
 
+    public VirtualRoutingResource(VirtualRouterDeployer deployer) {
+        this._vrDeployer = deployer;
+    }
+
     public Answer executeRequest(final Command cmd) {
         try {
+            ExecutionResult rc = _vrDeployer.prepareCommand((NetworkElementCommand)cmd);
+            if (!rc.isSuccess()) {
+                s_logger.error("Failed to prepare VR command due to " + rc.getDetails());
+                return new Answer(cmd, false, rc.getDetails());
+            }
+
             if (cmd instanceof SetPortForwardingRulesVpcCommand) {
                 return execute((SetPortForwardingRulesVpcCommand)cmd);
             } else if (cmd instanceof SetPortForwardingRulesCommand) {
@@ -123,12 +119,6 @@ public class VirtualRoutingResource implements Manager {
                 return execute((SetStaticNatRulesCommand)cmd);
             } else if (cmd instanceof LoadBalancerConfigCommand) {
                 return execute((LoadBalancerConfigCommand)cmd);
-            } else if (cmd instanceof IpAssocCommand) {
-                return execute((IpAssocCommand)cmd);
-            } else if (cmd instanceof CheckConsoleProxyLoadCommand) {
-                return execute((CheckConsoleProxyLoadCommand)cmd);
-            } else if (cmd instanceof WatchConsoleProxyLoadCommand) {
-                return execute((WatchConsoleProxyLoadCommand)cmd);
             } else if (cmd instanceof SavePasswordCommand) {
                 return execute((SavePasswordCommand)cmd);
             } else if (cmd instanceof DhcpEntryCommand) {
@@ -158,12 +148,27 @@ public class VirtualRoutingResource implements Manager {
             } else if (cmd instanceof CheckS2SVpnConnectionsCommand) {
                 return execute((CheckS2SVpnConnectionsCommand)cmd);
             } else if (cmd instanceof SetMonitorServiceCommand) {
-                return execute((SetMonitorServiceCommand) cmd);
+                return execute((SetMonitorServiceCommand)cmd);
+            } else if (cmd instanceof SetupGuestNetworkCommand) {
+                return execute((SetupGuestNetworkCommand)cmd);
+            } else if (cmd instanceof SetNetworkACLCommand) {
+                return execute((SetNetworkACLCommand)cmd);
+            } else if (cmd instanceof SetSourceNatCommand) {
+                return execute((SetSourceNatCommand)cmd);
+            } else if (cmd instanceof IpAssocVpcCommand) {
+                return execute((IpAssocVpcCommand)cmd);
+            } else if (cmd instanceof IpAssocCommand) {
+                return execute((IpAssocCommand)cmd);
             } else {
                 return Answer.createUnsupportedCommandAnswer(cmd);
             }
         } catch (final IllegalArgumentException e) {
             return new Answer(cmd, false, e.getMessage());
+        } finally {
+            ExecutionResult rc = _vrDeployer.cleanupCommand((NetworkElementCommand)cmd);
+            if (!rc.isSuccess()) {
+                s_logger.error("Failed to cleanup VR command due to " + rc.getDetails());
+            }
         }
     }
 
@@ -177,9 +182,9 @@ public class VirtualRoutingResource implements Manager {
                 args += "-u ";
                 args += userpwd.getUsernamePassword();
             }
-            String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
-            if (result != null) {
-                return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername());
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpn_l2tp.sh", args);
+            if (!result.isSuccess()) {
+                return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername() + ":" + result.getDetails());
             }
         }
         return new Answer(cmd);
@@ -204,11 +209,8 @@ public class VirtualRoutingResource implements Manager {
         }
         args += " -C " + cmd.getLocalCidr();
         args += " -i " + cmd.getPublicInterface();
-        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "vpn_l2tp.sh", args);
-        if (result != null) {
-            return new Answer(cmd, false, "Configure VPN failed");
-        }
-        return new Answer(cmd);
+        ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpn_l2tp.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     private Answer execute(SetFirewallRulesCommand cmd) {
@@ -216,10 +218,10 @@ public class VirtualRoutingResource implements Manager {
         for (int i = 0; i < cmd.getRules().length; i++) {
             results[i] = "Failed";
         }
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        String routerAccessIp = cmd.getRouterAccessIp();
         String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
 
-        if (routerIp == null) {
+        if (routerAccessIp == null) {
             return new SetFirewallRulesAnswer(cmd, false, results);
         }
 
@@ -230,7 +232,7 @@ public class VirtualRoutingResource implements Manager {
         String args = " -F";
 
         if (trafficType == FirewallRule.TrafficType.Egress) {
-            args += "-E";
+            args += " -E";
             if (egressDefault.equals("true")) {
                 args += " -P 1";
             } else if (egressDefault.equals("System")) {
@@ -249,15 +251,15 @@ public class VirtualRoutingResource implements Manager {
             args += " -a " + sb.toString();
         }
 
-        String result = null;
+        ExecutionResult result;
 
         if (trafficType == FirewallRule.TrafficType.Egress) {
-            result = executeInVR(routerIp, "firewall_egress.sh", args);
+            result = _vrDeployer.executeInVR(routerAccessIp, "firewall_egress.sh", args);
         } else {
-            result = executeInVR(routerIp, "firewall_ingress.sh", args);
+            result = _vrDeployer.executeInVR(routerAccessIp, "firewall_ingress.sh", args);
         }
 
-        if (result != null) {
+        if (!result.isSuccess()) {
             return new SetFirewallRulesAnswer(cmd, false, results);
         }
         return new SetFirewallRulesAnswer(cmd, true, null);
@@ -265,7 +267,6 @@ public class VirtualRoutingResource implements Manager {
     }
 
     private Answer execute(SetPortForwardingRulesCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String[] results = new String[cmd.getRules().length];
         int i = 0;
         boolean endResult = true;
@@ -278,9 +279,9 @@ public class VirtualRoutingResource implements Manager {
             args.append(" -r ").append(rule.getDstIp());
             args.append(" -d ").append(rule.getStringDstPortRange());
 
-            String result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "firewall_nat.sh", args.toString());
 
-            if (result == null || result.isEmpty()) {
+            if (!result.isSuccess()) {
                 results[i++] = "Failed";
                 endResult = false;
             } else {
@@ -292,7 +293,6 @@ public class VirtualRoutingResource implements Manager {
     }
 
     protected Answer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String[] results = new String[cmd.getRules().length];
         int i = 0;
         boolean endResult = true;
@@ -302,9 +302,9 @@ public class VirtualRoutingResource implements Manager {
             args += " -l " + rule.getSrcIp();
             args += " -r " + rule.getDstIp();
 
-            String result = executeInVR(routerIp, "vpc_staticnat.sh", args);
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_staticnat.sh", args);
 
-            if (result == null) {
+            if (!result.isSuccess()) {
                 results[i++] = null;
             } else {
                 results[i++] = "Failed";
@@ -319,7 +319,6 @@ public class VirtualRoutingResource implements Manager {
         if (cmd.getVpcId() != null) {
             return SetVPCStaticNatRules(cmd);
         }
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String[] results = new String[cmd.getRules().length];
         int i = 0;
         boolean endResult = true;
@@ -337,9 +336,9 @@ public class VirtualRoutingResource implements Manager {
             args.append(" -d ").append(rule.getStringSrcPortRange());
             args.append(" -G ");
 
-            String result = executeInVR(routerIp, "firewall_nat.sh", args.toString());
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "firewall_nat.sh", args.toString());
 
-            if (result == null || result.isEmpty()) {
+            if (!result.isSuccess()) {
                 results[i++] = "Failed";
                 endResult = false;
             } else {
@@ -350,19 +349,6 @@ public class VirtualRoutingResource implements Manager {
         return new SetStaticNatRulesAnswer(cmd, results, endResult);
     }
 
-    protected boolean createFileInVR(String routerIp, String path, String filename, String content) {
-        File permKey = new File("/root/.ssh/id_rsa.cloud");
-        boolean result = true;
-
-        try {
-            SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null);
-        } catch (Exception e) {
-            s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e);
-            result = false;
-        }
-        return result;
-    }
-
     private Answer execute(LoadBalancerConfigCommand cmd) {
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 
@@ -378,67 +364,58 @@ public class VirtualRoutingResource implements Manager {
             tmpCfgFileContents += "\n";
         }
 
-        if (!createFileInVR(routerIp, "/etc/haproxy/", "haproxy.cfg.new", tmpCfgFileContents)) {
+        if (!_vrDeployer.createFileInVR(cmd.getRouterAccessIp(), "/etc/haproxy/", "haproxy.cfg.new", tmpCfgFileContents).isSuccess()) {
             return new Answer(cmd, false, "Fail to copy LB config file to VR");
         }
 
-        try {
-            String[][] rules = cfgtr.generateFwRules(cmd);
+        String[][] rules = cfgtr.generateFwRules(cmd);
 
-            String[] addRules = rules[LoadBalancerConfigurator.ADD];
-            String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
-            String[] statRules = rules[LoadBalancerConfigurator.STATS];
+        String[] addRules = rules[LoadBalancerConfigurator.ADD];
+        String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
+        String[] statRules = rules[LoadBalancerConfigurator.STATS];
 
-            String args = "";
-            StringBuilder sb = new StringBuilder();
-            if (addRules.length > 0) {
-                for (int i = 0; i < addRules.length; i++) {
-                    sb.append(addRules[i]).append(',');
-                }
-                args += " -a " + sb.toString();
+        String args = "";
+        StringBuilder sb = new StringBuilder();
+        if (addRules.length > 0) {
+            for (int i = 0; i < addRules.length; i++) {
+                sb.append(addRules[i]).append(',');
             }
+            args += " -a " + sb.toString();
+        }
 
-            sb = new StringBuilder();
-            if (removeRules.length > 0) {
-                for (int i = 0; i < removeRules.length; i++) {
-                    sb.append(removeRules[i]).append(',');
-                }
-
-                args += " -d " + sb.toString();
+        sb = new StringBuilder();
+        if (removeRules.length > 0) {
+            for (int i = 0; i < removeRules.length; i++) {
+                sb.append(removeRules[i]).append(',');
             }
 
-            sb = new StringBuilder();
-            if (statRules.length > 0) {
-                for (int i = 0; i < statRules.length; i++) {
-                    sb.append(statRules[i]).append(',');
-                }
+            args += " -d " + sb.toString();
+        }
 
-                args += " -s " + sb.toString();
+        sb = new StringBuilder();
+        if (statRules.length > 0) {
+            for (int i = 0; i < statRules.length; i++) {
+                sb.append(statRules[i]).append(',');
             }
 
-            String result;
+            args += " -s " + sb.toString();
+        }
 
-            if (cmd.getVpcId() == null) {
-                args = " -i " + routerIp + args;
-                result = executeInVR(routerIp, "loadbalancer.sh", args);
-            } else {
-                args = " -i " + cmd.getNic().getIp() + args;
-                result = executeInVR(routerIp, "vpc_loadbalancer.sh", args);
-            }
+        ExecutionResult result;
 
-            if (result != null) {
-                return new Answer(cmd, false, "LoadBalancerConfigCommand failed");
-            }
-            return new Answer(cmd);
-
-        } catch (Exception e) {
-            return new Answer(cmd, e);
+        if (cmd.getVpcId() == null) {
+            args = " -i " + routerIp + args;
+            result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "loadbalancer.sh", args);
+        } else {
+            args = " -i " + cmd.getNic().getIp() + args;
+            result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_loadbalancer.sh", args);
         }
+
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
 
     protected Answer execute(VmDataCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         Map<String, List<String[]>> data = new HashMap<String, List<String[]>>();
         data.put(cmd.getVmIpAddress(), cmd.getVmData());
 
@@ -449,32 +426,8 @@ public class VirtualRoutingResource implements Manager {
 
         String args = "-d " + json;
 
-        final String result = executeInVR(routerIp, "vmdata.py", args);
-        if (result != null) {
-            return new Answer(cmd, false, "VmDataCommand failed, check agent logs");
-        }
-        return new Answer(cmd);
-    }
-
-    protected Answer execute(final IpAssocCommand cmd) {
-        IpAddressTO[] ips = cmd.getIpAddresses();
-        String[] results = new String[cmd.getIpAddresses().length];
-        int i = 0;
-        String result = null;
-        String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        for (IpAddressTO ip : ips) {
-            result =
-                assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(),
-                    ip.getVlanNetmask(), ip.getVifMacAddress(), 2, false);
-            if (result != null) {
-                results[i++] = IpAssocAnswer.errorResult;
-            } else {
-                results[i++] = ip.getPublicIp() + " - success";
-                ;
-            }
-        }
-        return new IpAssocAnswer(cmd, results);
+        final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vmdata.py", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(final SavePasswordCommand cmd) {
@@ -485,11 +438,8 @@ public class VirtualRoutingResource implements Manager {
         String args = "-v " + vmIpAddress;
         args += " -p " + password;
 
-        String result = executeInVR(routerPrivateIPAddress, "savepassword.sh", args);
-        if (result != null) {
-            return new Answer(cmd, false, "Unable to save password to DomR.");
-        }
-        return new Answer(cmd);
+        ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "savepassword.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(final DhcpEntryCommand cmd) {
@@ -520,23 +470,21 @@ public class VirtualRoutingResource implements Manager {
             args += " -N";
         }
 
-        final String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args);
-        return new Answer(cmd, result == null, result);
+        final ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(final CreateIpAliasCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
         String args = "";
         for (IpAliasTO ipaliasto : ipAliasTOs) {
             args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
         }
-        final String result = executeInVR(routerIp, "createipAlias.sh", args);
-        return new Answer(cmd, result == null, result);
+        final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "createipAlias.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(final DeleteIpAliasCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String args = "";
         List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
         for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
@@ -547,38 +495,18 @@ public class VirtualRoutingResource implements Manager {
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
             args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
         }
-        final String result = executeInVR(routerIp, "deleteipAlias.sh", args);
-        return new Answer(cmd, result == null, result);
+        final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "deleteipAlias.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(final DnsMasqConfigCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         List<DhcpTO> dhcpTos = cmd.getIps();
         String args = "";
         for (DhcpTO dhcpTo : dhcpTos) {
             args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
         }
-        final String result = executeInVR(routerIp, "dnsmasq.sh", args);
-        return new Answer(cmd, result == null, result);
-    }
-
-    public String getRouterStatus(String routerIP) {
-        return routerProxyWithParser("checkrouter.sh", routerIP, null);
-    }
-
-    public String routerProxyWithParser(String script, String routerIP, String args) {
-        final Script command = new Script(_routerProxyPath, _timeout, s_logger);
-        final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
-        command.add(script);
-        command.add(routerIP);
-        if (args != null) {
-            command.add(args);
-        }
-        String result = command.execute(parser);
-        if (result == null) {
-            return parser.getLine();
-        }
-        return null;
+        final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "dnsmasq.sh", args);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
@@ -589,65 +517,37 @@ public class VirtualRoutingResource implements Manager {
             args += " " + ip;
         }
 
-        final String result = executeInVR(routerIP, "checkbatchs2svpn.sh", args);
-        if (result == null || result.isEmpty()) {
-            return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
-        }
-        return new CheckS2SVpnConnectionsAnswer(cmd, true, result);
-    }
-
-    public String executeInVR(String routerIP, String script, String args) {
-        final Script command = new Script(_routerProxyPath, _timeout, s_logger);
-        command.add(script);
-        command.add(routerIP);
-        if (args != null) {
-            command.add(args);
-        }
-        return command.execute();
+        ExecutionResult result = _vrDeployer.executeInVR(routerIP, "checkbatchs2svpn.sh", args);
+        return new CheckS2SVpnConnectionsAnswer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(CheckRouterCommand cmd) {
         final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 
-        final String result = getRouterStatus(routerPrivateIPAddress);
-        if (result == null || result.isEmpty()) {
-            return new CheckRouterAnswer(cmd, "CheckRouterCommand failed");
+        final ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "checkrouter.sh", null);
+        if (!result.isSuccess()) {
+            return new CheckRouterAnswer(cmd, result.getDetails());
         }
-        return new CheckRouterAnswer(cmd, result, true);
+        return new CheckRouterAnswer(cmd, result.getDetails(), true);
     }
 
     protected Answer execute(BumpUpPriorityCommand cmd) {
-        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "bumpup_priority.sh", null);
-        if (result != null) {
-            return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result);
-        }
-        return new Answer(cmd, true, null);
-    }
-
-    protected String getDomRVersion(String routerIP) {
-        return routerProxyWithParser("get_template_version.sh", routerIP, null);
+        ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "bumpup_priority.sh", null);
+        return new Answer(cmd, result.isSuccess(), result.getDetails());
     }
 
     protected Answer execute(GetDomRVersionCmd cmd) {
         final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 
-        final String result = getDomRVersion(routerPrivateIPAddress);
-        if (result == null || result.isEmpty()) {
+        final ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "get_template_version.sh", null);
+        if (!result.isSuccess()) {
             return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed");
         }
-        String[] lines = result.split("&");
+        String[] lines = result.getDetails().split("&");
         if (lines.length != 2) {
-            return new GetDomRVersionAnswer(cmd, result);
+            return new GetDomRVersionAnswer(cmd, result.getDetails());
         }
-        return new GetDomRVersionAnswer(cmd, result, lines[0], lines[1]);
-    }
-
-    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());
+        return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]);
     }
 
     protected Answer execute(Site2SiteVpnCfgCommand cmd) {
@@ -692,59 +592,45 @@ public class VirtualRoutingResource implements Manager {
             args += " -N ";
             args += cmd.getPeerGuestCidrList();
         }
-        String result = executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args);
-        if (result != null) {
-            return new Answer(cmd, false, "Configure site to site VPN failed due to " + result);
+        ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args);
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, "Configure site to site VPN failed due to " + result.getDetails());
         }
         return new Answer(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");
+    protected Answer execute(SetMonitorServiceCommand cmd) {
+        String config = cmd.getConfiguration();
 
-        boolean success = true;
-        try {
-            final URL url = new URL(sb.toString());
-            final URLConnection conn = url.openConnection();
+        String args = " -c " + config;
+        ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "monitor_service.sh", args);
 
-            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;
+        if (!result.isSuccess()) {
+            return new Answer(cmd, false, result.getDetails());
         }
-
-        return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result);
+        return new Answer(cmd);
     }
 
-    public String configureMonitor(final String routerIP, final String config) {
-
-        String args = " -c " + config;
-        return executeInVR(routerIP, "monitor_service.sh", args);
-    }
+    protected SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) {
+        NicTO nic = cmd.getNic();
+        String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        String routerGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP);
+        String gateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY);
+        String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
+        String domainName = cmd.getNetworkDomain();
+        String dns = cmd.getDefaultDns1();
+
+        if (dns == null || dns.isEmpty()) {
+            dns = cmd.getDefaultDns2();
+        } else {
+            String dns2 = cmd.getDefaultDns2();
+            if (dns2 != null && !dns2.isEmpty()) {
+                dns += "," + dns2;
+            }
+        }
 
-    public String assignGuestNetwork(final String dev, final String routerIP, final String routerGIP, final String gateway, final String cidr, final String netmask,
-        final String dns, final String domainName) {
+        String dev = "eth" + nic.getDeviceId();
+        String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask());
 
         String args = " -C";
         args += " -d " + dev;
@@ -758,33 +644,74 @@ public class VirtualRoutingResource implements Manager {
         if (domainName != null && !domainName.isEmpty()) {
             args += " -e " + domainName;
         }
-        return executeInVR(routerIP, "vpc_guestnw.sh", args);
+        ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_guestnw.sh", args);
+
+        if (!result.isSuccess()) {
+            return new SetupGuestNetworkAnswer(cmd, false, "Creating guest network failed due to " + result.getDetails());
+        }
+        return new SetupGuestNetworkAnswer(cmd, true, "success");
     }
 
-    public String assignNetworkACL(final String routerIP, final String dev, final String routerGIP, final String netmask, final String rule, String privateGw) {
-        String args = " -d " + dev;
-        if (privateGw != null) {
-            args += " -a " + rule;
-            return executeInVR(routerIP, "vpc_privategw_acl.sh", args);
-        } else {
-            args += " -i " + routerGIP;
-            args += " -m " + netmask;
-            args += " -a " + rule;
-            return executeInVR(routerIP, "vpc_acl.sh", args);
+    private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) {
+        String[] results = new String[cmd.getRules().length];
+
+        String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
+
+        try {
+            String[][] rules = cmd.generateFwRules();
+            String[] aclRules = rules[0];
+            NicTO nic = cmd.getNic();
+            String dev = "eth" + nic.getDeviceId();
+            String netmask = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
+            StringBuilder sb = new StringBuilder();
+
+            for (int i = 0; i < aclRules.length; i++) {
+                sb.append(aclRules[i]).append(',');
+            }
+
+            String rule = sb.toString();
+            ExecutionResult result;
+
+            String args = " -d " + dev;
+            if (privateGw != null) {
+                args += " -a " + rule;
+                result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_privategw_acl.sh", args);
+            } else {
+                args += " -i " + nic.getIp();
+                args += " -m " + netmask;
+                args += " -a " + rule;
+                result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_acl.sh", args);
+            }
+
+            if (!result.isSuccess()) {
+                for (int i = 0; i < results.length; i++) {
+                    results[i] = "Failed";
+                }
+                return new SetNetworkACLAnswer(cmd, false, results);
+            }
+
+            return new SetNetworkACLAnswer(cmd, true, results);
+        } catch (Exception e) {
+            String msg = "SetNetworkACL failed due to " + e.toString();
+            s_logger.error(msg, e);
+            return new SetNetworkACLAnswer(cmd, false, results);
         }
     }
 
-    public String assignSourceNat(final String routerIP, final String pubIP, final String dev) {
+    protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) {
+        String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        IpAddressTO pubIP = cmd.getIpAddress();
+        String dev = "eth" + pubIP.getNicDevId();
         String args = " -A ";
         args += " -l ";
-        args += pubIP;
+        args += pubIP.getPublicIp();
         args += " -c ";
         args += dev;
-        return executeInVR(routerIP, "vpc_snat.sh", args);
+        ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_snat.sh", args);
+        return new SetSourceNatAnswer(cmd, result.isSuccess(), result.getDetails());
     }
 
     private SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) {
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         String[] results = new String[cmd.getRules().length];
         int i = 0;
 
@@ -797,9 +724,9 @@ public class VirtualRoutingResource implements Manager {
             args += " -r " + rule.getDstIp();
             args += " -d " + rule.getStringDstPortRange().replace(":", "-");
 
-            String result = executeInVR(routerIp, "vpc_portforwarding.sh", args);
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_portforwarding.sh", args);
 
-            if (result != null) {
+            if (!result.isSuccess()) {
                 results[i++] = "Failed";
                 endResult = false;
             } else {
@@ -809,44 +736,56 @@ public class VirtualRoutingResource implements Manager {
         return new SetPortForwardingRulesAnswer(cmd, results, endResult);
     }
 
-    public void assignVpcIpToRouter(final String routerIP, final boolean add, final String pubIP, final String nicname, final String gateway, final String netmask,
-        final String subnet, boolean sourceNat) throws InternalErrorException {
+    public IpAssocAnswer execute(IpAssocVpcCommand cmd) {
+        String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        String[] results = new String[cmd.getIpAddresses().length];
         String args = "";
         String snatArgs = "";
-
-        if (add) {
-            args += " -A ";
-            snatArgs += " -A ";
-        } else {
-            args += " -D ";
-            snatArgs += " -D ";
+        for (int i = 0; i < cmd.getIpAddresses().length; i ++) {
+            results[i] = "Failed";
         }
 
-        args += " -l ";
-        args += pubIP;
-        args += " -c ";
-        args += nicname;
-        args += " -g ";
-        args += gateway;
-        args += " -m ";
-        args += netmask;
-        args += " -n ";
-        args += subnet;
-
-        String result = executeInVR(routerIP, "vpc_ipassoc.sh", args);
-        if (result != null) {
-            throw new InternalErrorException("KVM plugin \"vpc_ipassoc\" failed:" + result);
-        }
-        if (sourceNat) {
-            snatArgs += " -l " + pubIP;
-            snatArgs += " -c " + nicname;
+        int i = 0;
+        for (IpAddressTO ip : cmd.getIpAddresses()) {
+            if (ip.isAdd()) {
+                args += " -A ";
+                snatArgs += " -A ";
+            } else {
+                args += " -D ";
+                snatArgs += " -D ";
+            }
 
-            result = executeInVR(routerIP, "vpc_privateGateway.sh", snatArgs);
-            if (result != null) {
-                throw new InternalErrorException("KVM plugin \"vpc_privateGateway\" failed:" + result);
+            args += " -l ";
+            args += ip.getPublicIp();
+            String nicName = "eth" + ip.getNicDevId();
+            args += " -c ";
+            args += nicName;
+            args += " -g ";
+            args += ip.getVlanGateway();
+            args += " -m ";
+            args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
+            args += " -n ";
+            args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
+
+            ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_ipassoc.sh", args);
+            if (!result.isSuccess()) {
+                results[i++] = ip.getPublicIp() + " - vpc_ipassoc failed:" + result.getDetails();
+                break;
             }
 
+            if (ip.isSourceNat()) {
+                snatArgs += " -l " + ip.getPublicIp();
+                snatArgs += " -c " + nicName;
+
+                result = _vrDeployer.executeInVR(routerIP, "vpc_privateGateway.sh", snatArgs);
+                if (result != null) {
+                    results[i++] = ip.getPublicIp() + " - vpc_privateGateway failed:" + result.getDetails();
+                    break;
+                }
+            }
+            results[i++] = ip.getPublicIp() + " - success ";
         }
+        return new IpAssocAnswer(cmd, results);
     }
 
     private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) {
@@ -862,9 +801,9 @@ public class VirtualRoutingResource implements Manager {
             }
 
             String args = " -a " + sb.toString();
-            String result = executeInVR(routerIP, "vpc_staticroute.sh", args);
+            ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_staticroute.sh", args);
 
-            if (result != null) {
+            if (!result.isSuccess()) {
                 for (int i = 0; i < results.length; i++) {
                     results[i] = "Failed";
                 }
@@ -879,161 +818,56 @@ public class VirtualRoutingResource implements Manager {
         }
     }
 
-    private Answer execute(SetMonitorServiceCommand cmd) {
-
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String config = cmd.getConfiguration();
-
-        String result = configureMonitor(routerIp, config);
-
-        if (result != null) {
-            return new Answer(cmd, false, "SetMonitorServiceCommand failed");
-        }
-        return new Answer(cmd);
-
-    }
-
-    public String assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP,
-        final boolean sourceNat, final String broadcastUri, final String vlanGateway, final String vlanNetmask, final String vifMacAddress, int nicNum, boolean newNic) {
-
-        String args = "";
-        if (add) {
-            args += "-A";
-        } else {
-            args += "-D";
-        }
-        String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask));
-        if (sourceNat) {
-            args += " -s";
-        }
-        if (firstIP) {
-            args += " -f";
+    public Answer execute(IpAssocCommand cmd) {
+        String[] results = new String[cmd.getIpAddresses().length];
+        for (int i = 0; i < results.length; i++) {
+            results[i] = IpAssocAnswer.errorResult;
         }
-        args += " -l ";
-        args += publicIpAddress + "/" + cidrSize;
 
-        String publicNic = "eth" + nicNum;
-        args += " -c ";
-        args += publicNic;
-
-        args += " -g ";
-        args += vlanGateway;
+        int i = 0;
+        for (IpAddressTO ip: cmd.getIpAddresses()) {
+            String args = "";
+            if (ip.isAdd()) {
+                args += "-A";
+            } else {
+                args += "-D";
+            }
+            String cidrSize = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
+            if (ip.isSourceNat()) {
+                args += " -s";
+            }
+            if (ip.isFirstIP()) {
+                args += " -f";
+            }
+            args += " -l ";
+            args += ip.getPublicIp() + "/" + cidrSize;
 
-        if (newNic) {
-            args += " -n";
-        }
+            String publicNic = "eth" + ip.getNicDevId();
+            args += " -c ";
+            args += publicNic;
 
-        return executeInVR(privateIpAddress, "ipassoc.sh", args);
-    }
+            args += " -g ";
+            args += ip.getVlanGateway();
 
-    private void deleteBridge(String brName) {
-        Script cmd = new Script("/bin/sh", _timeout);
-        cmd.add("-c");
-        cmd.add("ifconfig " + brName + " down;brctl delbr " + brName);
-        cmd.execute();
-    }
+            if (ip.isNewNic()) {
+                args += " -n";
+            }
 
-    private boolean isDNSmasqRunning(String dnsmasqName) {
-        Script cmd = new Script("/bin/sh", _timeout);
-        cmd.add("-c");
-        cmd.add("ls -l /var/run/libvirt/network/" + dnsmasqName + ".pid");
-        String result = cmd.execute();
-        if (result != null) {
-            return false;
-        } else {
-            return true;
+            ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "ipassoc.sh", args);
+            if (result.isSuccess()) {
+                results[i++] = ip.getPublicIp() + " - success";
+            } else {
+                results[i++] = ip.getPublicIp() + " - failed:" + result.getDetails();
+                break;
+            }
         }
+        return new IpAssocAnswer(cmd, results);
     }
 
-    private void stopDnsmasq(String dnsmasqName) {
-        Script cmd = new Script("/bin/sh", _timeout);
-        cmd.add("-c");
-        cmd.add("kill -9 `cat /var/run/libvirt/network/" + dnsmasqName + ".pid`");
-        cmd.execute();
-    }
-
-    //    protected Answer execute(final SetFirewallRuleCommand cmd) {
-    //        String args;
-    //        if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
-    //            //1:1 NAT needs instanceip;publicip;domrip;op
-    //            if(cmd.isCreate()) {
-    //                args = "-A";
-    //            } else {
-    //                args = "-D";
-    //            }
-    //
-    //            args += " -l " + cmd.getPublicIpAddress();
-    //            args += " -i " + cmd.getRouterIpAddress();
-    //            args += " -r " + cmd.getPrivateIpAddress();
-    //            args += " -G " + cmd.getProtocol();
-    //        }else{
-    //            if (cmd.isEnable()) {
-    //                args = "-A";
-    //            } else {
-    //                args = "-D";
-    //            }
-    //
-    //            args += " -P " + cmd.getProtocol().toLowerCase();
-    //            args += " -l " + cmd.getPublicIpAddress();
-    //            args += " -p " + cmd.getPublicPort();
-    //            args += " -n " + cmd.getRouterName();
-    //            args += " -i " + cmd.getRouterIpAddress();
-    //            args += " -r " + cmd.getPrivateIpAddress();
-    //            args += " -d " + cmd.getPrivatePort();
-    //            args += " -N " + cmd.getVlanNetmask();
-    //
-    //            String oldPrivateIP = cmd.getOldPrivateIP();
-    //            String oldPrivatePort = cmd.getOldPrivatePort();
-    //
-    //            if (oldPrivateIP != null) {
-    //                args += " -w " + oldPrivateIP;
-    //            }
-    //
-    //            if (oldPrivatePort != null) {
-    //                args += " -x " + oldPrivatePort;
-    //            }
-    //        }
-    //
-    //        final Script command = new Script(_firewallPath, _timeout, s_logger);
-    //        String [] argsArray = args.split(" ");
-    //        for (String param : argsArray) {
-    //            command.add(param);
-    //        }
-    //        String result = command.execute();
-    //        return new Answer(cmd, result == null, result);
-    //    }
-
-    protected String getDefaultScriptsDir() {
-        return "scripts/network/domr/dom0";
-    }
-
-    protected String findScript(final String script) {
-        return Script.findScript(_scriptsDir, script);
-    }
-
-    @Override
     public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
         _name = name;
 
-        _scriptsDir = (String)params.get("domr.scripts.dir");
-        if (_scriptsDir == null) {
-            if (s_logger.isInfoEnabled()) {
-                s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default");
-            }
-            _scriptsDir = getDefaultScriptsDir();
-        }
-
-        if (s_logger.isInfoEnabled()) {
-            s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir);
-        }
-
-        String value = (String)params.get("scripts.timeout");
-        _timeout = NumbersUtil.parseInt(value, 120) * 1000;
-
-        value = (String)params.get("start.script.timeout");
-        _startTimeout = NumbersUtil.parseInt(value, 360) * 1000;
-
-        value = (String)params.get("ssh.sleep");
+        String value = (String)params.get("ssh.sleep");
         _sleep = NumbersUtil.parseInt(value, 10) * 1000;
 
         value = (String)params.get("ssh.retry");
@@ -1042,26 +876,8 @@ public class VirtualRoutingResource implements Manager {
         value = (String)params.get("ssh.port");
         _port = NumbersUtil.parseInt(value, 3922);
 
-        _publicIpAddress = (String)params.get("public.ip.address");
-        if (_publicIpAddress != null) {
-            s_logger.warn("Incoming public ip address is overriden.  Will always be using the same ip address: " + _publicIpAddress);
-        }
-
-        _publicEthIf = (String)params.get("public.network.device");
-        if (_publicEthIf == null) {
-            _publicEthIf = "xenbr1";
-        }
-        _publicEthIf = _publicEthIf.toLowerCase();
-
-        _privateEthIf = (String)params.get("private.network.device");
-        if (_privateEthIf == null) {
-            _privateEthIf = "xenbr0";
-        }
-        _privateEthIf = _privateEthIf.toLowerCase();
-
-        _routerProxyPath = findScript("router_proxy.sh");
-        if (_routerProxyPath == null) {
-            throw new ConfigurationException("Unable to find router_proxy.sh");
+        if (_vrDeployer == null) {
+            throw new ConfigurationException("Unable to find the resource for VirtualRouterDeployer!");
         }
         return true;
     }
@@ -1141,50 +957,4 @@ public class VirtualRoutingResource implements Manager {
 
         return false;
     }
-
-    @Override
-    public String getName() {
-        return _name;
-    }
-
-    @Override
-    public void setName(String name) {
-        _name = name;
-    }
-
-    @Override
-    public boolean start() {
-        return true;
-    }
-
-    @Override
-    public boolean stop() {
-        return true;
-    }
-
-    @Override
-    public int getRunLevel() {
-        return ComponentLifecycle.RUN_LEVEL_COMPONENT;
-    }
-
-    public void setRunLevel() {
-    }
-
-    @Override
-    public void setConfigParams(Map<String, Object> params) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public Map<String, Object> getConfigParams() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public void setRunLevel(int level) {
-        // TODO Auto-generated method stub
-
-    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index c40cd75..fa0d99f 100755
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -16,73 +16,12 @@
 // under the License.
 package com.cloud.hypervisor.kvm.resource;
 
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.InetAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.ejb.Local;
-import javax.naming.ConfigurationException;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.log4j.Logger;
-import org.libvirt.Connect;
-import org.libvirt.Domain;
-import org.libvirt.DomainBlockStats;
-import org.libvirt.DomainInfo;
-import org.libvirt.DomainInterfaceStats;
-import org.libvirt.DomainSnapshot;
-import org.libvirt.LibvirtException;
-import org.libvirt.NodeInfo;
-
 import com.ceph.rados.IoCTX;
 import com.ceph.rados.Rados;
 import com.ceph.rados.RadosException;
 import com.ceph.rbd.Rbd;
 import com.ceph.rbd.RbdException;
 import com.ceph.rbd.RbdImage;
-
-import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
-import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
-import org.apache.cloudstack.storage.to.VolumeObjectTO;
-import org.apache.cloudstack.utils.qemu.QemuImg;
-import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
-import org.apache.cloudstack.utils.qemu.QemuImgException;
-import org.apache.cloudstack.utils.qemu.QemuImgFile;
-
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeAnswer;
@@ -155,7 +94,6 @@ import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.SecurityGroupRuleAnswer;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
-import com.cloud.agent.api.SetupGuestNetworkAnswer;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.StartAnswer;
 import com.cloud.agent.api.StartCommand;
@@ -174,13 +112,9 @@ import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
-import com.cloud.agent.api.routing.IpAssocAnswer;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
-import com.cloud.agent.api.routing.SetNetworkACLAnswer;
-import com.cloud.agent.api.routing.SetNetworkACLCommand;
-import com.cloud.agent.api.routing.SetSourceNatAnswer;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
 import com.cloud.agent.api.storage.CopyVolumeAnswer;
 import com.cloud.agent.api.storage.CopyVolumeCommand;
@@ -201,6 +135,7 @@ import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.api.to.VolumeTO;
+import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.dc.Vlan;
 import com.cloud.exception.InternalErrorException;
@@ -250,17 +185,77 @@ import com.cloud.storage.template.Processor.FormatInfo;
 import com.cloud.storage.template.QCOW2Processor;
 import com.cloud.storage.template.TemplateLocation;
 import com.cloud.storage.template.TemplateProp;
+import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.PropertiesUtil;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.utils.script.OutputInterpreter;
+import com.cloud.utils.script.OutputInterpreter.AllLinesParser;
 import com.cloud.utils.script.Script;
+import com.cloud.utils.ssh.SshHelper;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
 import com.cloud.vm.VirtualMachine.State;
+import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
+import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
+import org.apache.cloudstack.storage.to.VolumeObjectTO;
+import org.apache.cloudstack.utils.qemu.QemuImg;
+import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
+import org.apache.cloudstack.utils.qemu.QemuImgException;
+import org.apache.cloudstack.utils.qemu.QemuImgFile;
+import org.apache.commons.io.FileUtils;
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.Domain;
+import org.libvirt.DomainBlockStats;
+import org.libvirt.DomainInfo;
+import org.libvirt.DomainInterfaceStats;
+import org.libvirt.DomainSnapshot;
+import org.libvirt.LibvirtException;
+import org.libvirt.NodeInfo;
+
+import javax.ejb.Local;
+import javax.naming.ConfigurationException;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * LibvirtComputingResource execute requests on the computing/routing host using
@@ -285,7 +280,7 @@ import com.cloud.vm.VirtualMachine.State;
  *         pool | the parent of the storage pool hierarchy * }
  **/
 @Local(value = {ServerResource.class})
-public class LibvirtComputingResource extends ServerResourceBase implements ServerResource {
+public class LibvirtComputingResource extends ServerResourceBase implements ServerResource, VirtualRouterDeployer {
     private static final Logger s_logger = Logger.getLogger(LibvirtComputingResource.class);
 
     private String _modifyVlanPath;
@@ -322,6 +317,58 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver";
     protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver";
 
+    @Override
+    public ExecutionResult executeInVR(String routerIp, String script, String args) {
+        final Script command = new Script(_routerProxyPath, _timeout, s_logger);
+        final AllLinesParser parser = new AllLinesParser();
+        command.add(script);
+        command.add(routerIp);
+        if (args != null) {
+            command.add(args);
+        }
+        String details = command.execute(parser);
+        if (details == null) {
+            details = parser.getLines();
+        }
+        return new ExecutionResult(command.getExitValue() == 0, details);
+    }
+
+    @Override
+    public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) {
+        File permKey = new File("/root/.ssh/id_rsa.cloud");
+        String error = null;
+
+        try {
+            SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null);
+        } catch (Exception e) {
+            s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e);
+            error = e.getMessage();
+        }
+        return new ExecutionResult(error == null, error);
+    }
+
+    @Override
+    public ExecutionResult prepareCommand(NetworkElementCommand cmd) {
+        //Update IP used to access router
+        cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
+
+        if (cmd instanceof IpAssocVpcCommand) {
+            return prepareNetworkElementCommand((IpAssocVpcCommand)cmd);
+        } else if (cmd instanceof IpAssocCommand) {
+            return prepareNetworkElementCommand((IpAssocCommand)cmd);
+        } else if (cmd instanceof SetupGuestNetworkCommand) {
+            return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd);
+        } else if (cmd instanceof SetSourceNatCommand) {
+            return prepareNetworkElementCommand((SetSourceNatCommand)cmd);
+        }
+        return new ExecutionResult(true, null);
+    }
+
+    @Override
+    public ExecutionResult cleanupCommand(NetworkElementCommand cmd) {
+        return new ExecutionResult(true, null);
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -537,7 +584,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
         params.put("domr.scripts.dir", domrScriptsDir);
 
-        _virtRouterResource = new VirtualRoutingResource();
+        _virtRouterResource = new VirtualRoutingResource(this);
         success = _virtRouterResource.configure(name, params);
 
         if (!success) {
@@ -1258,16 +1305,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((PlugNicCommand)cmd);
             } else if (cmd instanceof UnPlugNicCommand) {
                 return execute((UnPlugNicCommand)cmd);
-            } else if (cmd instanceof SetupGuestNetworkCommand) {
-                return execute((SetupGuestNetworkCommand)cmd);
-            } else if (cmd instanceof SetNetworkACLCommand) {
-                return execute((SetNetworkACLCommand)cmd);
-            } else if (cmd instanceof SetSourceNatCommand) {
-                return execute((SetSourceNatCommand)cmd);
-            } else if (cmd instanceof IpAssocVpcCommand) {
-                return execute((IpAssocVpcCommand)cmd);
-            } else if (cmd instanceof IpAssocCommand) {
-                return execute((IpAssocCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest(cmd);
             } else if (cmd instanceof CheckSshCommand) {
@@ -1977,25 +2014,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) {
+    private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) {
         Connect conn;
         NicTO nic = cmd.getNic();
-        String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String routerGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP);
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String gateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY);
-        String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
-        String domainName = cmd.getNetworkDomain();
-        String dns = cmd.getDefaultDns1();
-
-        if (dns == null || dns.isEmpty()) {
-            dns = cmd.getDefaultDns2();
-        } else {
-            String dns2 = cmd.getDefaultDns2();
-            if (dns2 != null && !dns2.isEmpty()) {
-                dns += "," + dns2;
-            }
-        }
 
         try {
             conn = LibvirtConnection.getConnectionByVmName(routerName);
@@ -2010,62 +2032,18 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             }
 
             if (routerNic == null) {
-                return new SetupGuestNetworkAnswer(cmd, false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName);
+                return new ExecutionResult(false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName);
             }
 
-            String dev = "eth" + nic.getDeviceId();
-            String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask());
-            String result = _virtRouterResource.assignGuestNetwork(dev, routerIP, routerGIP, gateway, cidr, netmask, dns, domainName);
-
-            if (result != null) {
-                return new SetupGuestNetworkAnswer(cmd, false, "Creating guest network failed due to " + result);
-            }
-            return new SetupGuestNetworkAnswer(cmd, true, "success");
+            return new ExecutionResult(true, null);
         } catch (LibvirtException e) {
             String msg = "Creating guest network failed due to " + e.toString();
             s_logger.warn(msg, e);
-            return new SetupGuestNetworkAnswer(cmd, false, msg);
+            return new ExecutionResult(false, msg);
         }
     }
 
-
-    private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) {
-        String[] results = new String[cmd.getRules().length];
-
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
-
-        try {
-            String[][] rules = cmd.generateFwRules();
-            String[] aclRules = rules[0];
-            NicTO nic = cmd.getNic();
-            String dev = "eth" + nic.getDeviceId();
-            String netmask = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
-            StringBuilder sb = new StringBuilder();
-
-            for (int i = 0; i < aclRules.length; i++) {
-                sb.append(aclRules[i]).append(',');
-            }
-
-            String rule = sb.toString();
-            String result = _virtRouterResource.assignNetworkACL(routerIp, dev, nic.getIp(), netmask, rule, privateGw);
-
-            if (result != null) {
-                for (int i = 0; i < results.length; i++) {
-                    results[i] = "Failed";
-                }
-                return new SetNetworkACLAnswer(cmd, false, results);
-            }
-
-            return new SetNetworkACLAnswer(cmd, true, results);
-        } catch (Exception e) {
-            String msg = "SetNetworkACL failed due to " + e.toString();
-            s_logger.error(msg, e);
-            return new SetNetworkACLAnswer(cmd, false, results);
-        }
-    }
-
-    protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) {
+    protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) {
         Connect conn;
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
@@ -2086,7 +2064,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                     /*skip over, no physical bridge device exists*/
                 } else if (pluggedVlanId == null) {
                     /*this should only be true in the case of link local bridge*/
-                    return new SetSourceNatAnswer(cmd, false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan +
+                    return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan +
                             " on router " + routerName);
                 } else if (pluggedVlanId.equals(pubVlan)) {
                     break;
@@ -2094,26 +2072,20 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 devNum++;
             }
 
-            String dev = "eth" + devNum;
-            String result = _virtRouterResource.assignSourceNat(routerIP, pubIP.getPublicIp(), dev);
+            pubIP.setNicDevId(devNum);
 
-            if (result != null) {
-                return new SetSourceNatAnswer(cmd, false, "KVM plugin \"vpc_snat\" failed:" + result);
-            }
-            return new SetSourceNatAnswer(cmd, true, "success");
+            return new ExecutionResult(true, "success");
         } catch (LibvirtException e) {
             String msg = "Ip SNAT failure due to " + e.toString();
             s_logger.error(msg, e);
-            return new SetSourceNatAnswer(cmd, false, msg);
+            return new ExecutionResult(false, msg);
         }
     }
 
-    protected IpAssocAnswer execute(IpAssocVpcCommand cmd) {
+    protected ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) {
         Connect conn;
-        String[] results = new String[cmd.getIpAddresses().length];
         int i = 0;
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
-        String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
 
         try {
             conn = LibvirtConnection.getConnectionByVmName(routerName);
@@ -2136,31 +2108,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             }
 
             for (IpAddressTO ip : ips) {
-                String nicName = "eth" + broadcastUriToNicNum.get(ip.getBroadcastUri());
-                String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
-                String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
-                _virtRouterResource.assignVpcIpToRouter(routerIP, ip.isAdd(), ip.getPublicIp(), nicName, ip.getVlanGateway(), netmask, subnet, ip.isSourceNat());
-                results[i++] = ip.getPublicIp() + " - success";
+                ip.setNicDevId(broadcastUriToNicNum.get(ip.getBroadcastUri()));
             }
 
+            return new ExecutionResult(true, null);
         } catch (LibvirtException e) {
             s_logger.error("Ip Assoc failure on applying one ip due to exception:  ", e);
-            results[i++] = IpAssocAnswer.errorResult;
-        } catch (InternalErrorException e) {
-            s_logger.error("Ip Assoc failure on applying one ip due to exception:  ", e);
-            results[i++] = IpAssocAnswer.errorResult;
+            return new ExecutionResult(false, e.getMessage());
         }
-
-        return new IpAssocAnswer(cmd, results);
     }
 
-    public Answer execute(IpAssocCommand cmd) {
+    public ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
         String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        String[] results = new String[cmd.getIpAddresses().length];
-        for (int i = 0; i < results.length; i++) {
-            results[i] = IpAssocAnswer.errorResult;
-        }
         Connect conn;
         try {
             conn = LibvirtConnection.getConnectionByVmName(routerName);
@@ -2182,11 +2142,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 nicPos++;
             }
             IpAddressTO[] ips = cmd.getIpAddresses();
-            int i = 0;
-            String result = null;
             int nicNum = 0;
-            boolean newNic = false;
             for (IpAddressTO ip : ips) {
+                boolean newNic = false;
                 if (!broadcastUriAllocatedToVM.containsKey(ip.getBroadcastUri())) {
                     /* plug a vif into router */
                     VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress());
@@ -2195,21 +2153,17 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 }
                 nicNum = broadcastUriAllocatedToVM.get(ip.getBroadcastUri());
                 networkUsage(routerIp, "addVif", "eth" + nicNum);
-                result =
-                        _virtRouterResource.assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(),
-                                ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), nicNum, newNic);
 
-                if (result == null) {
-                    results[i++] = ip.getPublicIp() + " - success";
-                }
+                ip.setNicDevId(nicNum);
+                ip.setNewNic(newNic);
             }
-            return new IpAssocAnswer(cmd, results);
+            return new ExecutionResult(true, null);
         } catch (LibvirtException e) {
             s_logger.error("ipassoccmd failed", e);
-            return new IpAssocAnswer(cmd, results);
+            return new ExecutionResult(false, e.getMessage());
         } catch (InternalErrorException e) {
             s_logger.error("ipassoccmd failed", e);
-            return new IpAssocAnswer(cmd, results);
+            return new ExecutionResult(false, e.getMessage());
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/utils/src/com/cloud/utils/script/OutputInterpreter.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/script/OutputInterpreter.java b/utils/src/com/cloud/utils/script/OutputInterpreter.java
index 5af607e..5845c9c 100755
--- a/utils/src/com/cloud/utils/script/OutputInterpreter.java
+++ b/utils/src/com/cloud/utils/script/OutputInterpreter.java
@@ -16,11 +16,11 @@
 // under the License.
 package com.cloud.utils.script;
 
+import org.apache.log4j.Logger;
+
 import java.io.BufferedReader;
 import java.io.IOException;
 
-import org.apache.log4j.Logger;
-
 /**
  */
 public abstract class OutputInterpreter {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/285f23f1/utils/src/com/cloud/utils/script/Script.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java
index 91f32de..8dad697 100755
--- a/utils/src/com/cloud/utils/script/Script.java
+++ b/utils/src/com/cloud/utils/script/Script.java
@@ -16,6 +16,11 @@
 // under the License.
 package com.cloud.utils.script;
 
+import com.cloud.utils.PropertiesUtil;
+import com.cloud.utils.concurrency.NamedThreadFactory;
+import com.cloud.utils.script.OutputInterpreter.TimedOutLogger;
+import org.apache.log4j.Logger;
+
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
@@ -35,12 +40,6 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.concurrency.NamedThreadFactory;
-import com.cloud.utils.script.OutputInterpreter.TimedOutLogger;
-
 public class Script implements Callable<String> {
     private static final Logger s_logger = Logger.getLogger(Script.class);
 
@@ -61,6 +60,10 @@ public class Script implements Callable<String> {
     Process _process;
     Thread _thread;
 
+    public int getExitValue()  {
+        return _process.exitValue();
+    }
+
     public Script(String command, long timeout, Logger logger) {
         _command = new ArrayList<String>();
         _command.add(command);