You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by hu...@apache.org on 2014/07/14 15:53:41 UTC

[2/3] git commit: updated refs/heads/master to 1ad1883

Refactor VirtualRoutingResource, put the ConfigItems in separate classes and create a separate ConfigHelper


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

Branch: refs/heads/master
Commit: c12767908deb8f038d62827ae30bd3cfa302c8a6
Parents: e7392cd
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Fri Jul 11 09:09:32 2014 +0200
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Mon Jul 14 15:32:31 2014 +0200

----------------------------------------------------------------------
 .../resource/virtualnetwork/ConfigHelper.java   | 691 ++++++++++++++
 .../resource/virtualnetwork/ConfigItem.java     |  16 +
 .../resource/virtualnetwork/FileConfigItem.java |  56 ++
 .../virtualnetwork/ScriptConfigItem.java        |  40 +
 .../resource/virtualnetwork/VRScripts.java      |  40 +
 .../virtualnetwork/VirtualRoutingResource.java  | 915 ++-----------------
 .../VirtualRoutingResourceTest.java             | 341 ++++---
 7 files changed, 1076 insertions(+), 1023 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/core/src/com/cloud/agent/resource/virtualnetwork/ConfigHelper.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/ConfigHelper.java b/core/src/com/cloud/agent/resource/virtualnetwork/ConfigHelper.java
new file mode 100644
index 0000000..31ddafb
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/ConfigHelper.java
@@ -0,0 +1,691 @@
+package com.cloud.agent.resource.virtualnetwork;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+
+import com.google.gson.Gson;
+
+import com.cloud.agent.api.BumpUpPriorityCommand;
+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;
+import com.cloud.agent.api.routing.DnsMasqConfigCommand;
+import com.cloud.agent.api.routing.IpAliasTO;
+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.SetFirewallRulesCommand;
+import com.cloud.agent.api.routing.SetMonitorServiceCommand;
+import com.cloud.agent.api.routing.SetNetworkACLCommand;
+import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
+import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
+import com.cloud.agent.api.routing.SetSourceNatCommand;
+import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
+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.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.network.HAProxyConfigurator;
+import com.cloud.network.LoadBalancerConfigurator;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.utils.net.NetUtils;
+
+public class ConfigHelper {
+
+    public static List<ConfigItem> generateCommandCfg(NetworkElementCommand cmd) {
+        List<ConfigItem> cfg;
+        if (cmd instanceof SetPortForwardingRulesVpcCommand) {
+            cfg = generateConfig((SetPortForwardingRulesVpcCommand)cmd);
+        } else if (cmd instanceof SetPortForwardingRulesCommand) {
+            cfg = generateConfig((SetPortForwardingRulesCommand)cmd);
+        } else if (cmd instanceof SetStaticRouteCommand) {
+            cfg = generateConfig((SetStaticRouteCommand)cmd);
+        } else if (cmd instanceof SetStaticNatRulesCommand) {
+            cfg = generateConfig((SetStaticNatRulesCommand)cmd);
+        } else if (cmd instanceof LoadBalancerConfigCommand) {
+            cfg = generateConfig((LoadBalancerConfigCommand)cmd);
+        } else if (cmd instanceof SavePasswordCommand) {
+            cfg = generateConfig((SavePasswordCommand)cmd);
+        } else if (cmd instanceof DhcpEntryCommand) {
+            cfg = generateConfig((DhcpEntryCommand)cmd);
+        } else if (cmd instanceof CreateIpAliasCommand) {
+            cfg = generateConfig((CreateIpAliasCommand)cmd);
+        } else if (cmd instanceof DnsMasqConfigCommand) {
+            cfg = generateConfig((DnsMasqConfigCommand)cmd);
+        } else if (cmd instanceof DeleteIpAliasCommand) {
+            cfg = generateConfig((DeleteIpAliasCommand)cmd);
+        } else if (cmd instanceof VmDataCommand) {
+            cfg = generateConfig((VmDataCommand)cmd);
+        } else if (cmd instanceof SetFirewallRulesCommand) {
+            cfg = generateConfig((SetFirewallRulesCommand)cmd);
+        } else if (cmd instanceof BumpUpPriorityCommand) {
+            cfg = generateConfig((BumpUpPriorityCommand)cmd);
+        } else if (cmd instanceof RemoteAccessVpnCfgCommand) {
+            cfg = generateConfig((RemoteAccessVpnCfgCommand)cmd);
+        } else if (cmd instanceof VpnUsersCfgCommand) {
+            cfg = generateConfig((VpnUsersCfgCommand)cmd);
+        } else if (cmd instanceof Site2SiteVpnCfgCommand) {
+            cfg = generateConfig((Site2SiteVpnCfgCommand)cmd);
+        } else if (cmd instanceof SetMonitorServiceCommand) {
+            cfg = generateConfig((SetMonitorServiceCommand)cmd);
+        } else if (cmd instanceof SetupGuestNetworkCommand) {
+            cfg = generateConfig((SetupGuestNetworkCommand)cmd);
+        } else if (cmd instanceof SetNetworkACLCommand) {
+            cfg = generateConfig((SetNetworkACLCommand)cmd);
+        } else if (cmd instanceof SetSourceNatCommand) {
+            cfg = generateConfig((SetSourceNatCommand)cmd);
+        } else if (cmd instanceof IpAssocCommand) {
+            cfg = generateConfig((IpAssocCommand)cmd);
+        } else {
+            return null;
+        }
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(VpnUsersCfgCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) {
+            String args = "";
+            if (!userpwd.isAdd()) {
+                args += "-U ";
+                args += userpwd.getUsername();
+            } else {
+                args += "-u ";
+                args += userpwd.getUsernamePassword();
+            }
+            cfg.add(new ScriptConfigItem(VRScripts.VPN_L2TP, args));
+        }
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(RemoteAccessVpnCfgCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        String args = "";
+        if (cmd.isCreate()) {
+            args += "-r ";
+            args += cmd.getIpRange();
+            args += " -p ";
+            args += cmd.getPresharedKey();
+            args += " -s ";
+            args += cmd.getVpnServerIp();
+            args += " -l ";
+            args += cmd.getLocalIp();
+            args += " -c ";
+        } else {
+            args += "-d ";
+            args += " -s ";
+            args += cmd.getVpnServerIp();
+        }
+        args += " -C " + cmd.getLocalCidr();
+        args += " -i " + cmd.getPublicInterface();
+        cfg.add(new ScriptConfigItem(VRScripts.VPN_L2TP, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetFirewallRulesCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
+
+        FirewallRuleTO[] allrules = cmd.getRules();
+        FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
+
+        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) {
+            cfg.add(new ScriptConfigItem(VRScripts.FIREWALL_EGRESS, args));
+        } else {
+            cfg.add(new ScriptConfigItem(VRScripts.FIREWALL_INGRESS, args));
+        }
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetPortForwardingRulesCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        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());
+            cfg.add(new ScriptConfigItem(VRScripts.FIREWALL_NAT, args.toString()));
+        }
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetStaticNatRulesCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        if (cmd.getVpcId() != null) {
+            for (StaticNatRuleTO rule : cmd.getRules()) {
+                String args = rule.revoked() ? " -D" : " -A";
+                args += " -l " + rule.getSrcIp();
+                args += " -r " + rule.getDstIp();
+
+                cfg.add(new ScriptConfigItem(VRScripts.VPC_STATIC_NAT, args));
+            }
+        } else {
+            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 ");
+
+                cfg.add(new ScriptConfigItem(VRScripts.FIREWALL_NAT, args.toString()));
+            }
+        }
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(LoadBalancerConfigCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        LoadBalancerConfigurator cfgtr = new HAProxyConfigurator();
+
+        String[] config = cfgtr.generateConfiguration(cmd);
+        StringBuffer buff = new StringBuffer();
+        for (int i = 0; i < config.length; i++) {
+            buff.append(config[i]);
+            buff.append("\n");
+        }
+        String tmpCfgFilePath = "/etc/haproxy/";
+        String tmpCfgFileName = "haproxy.cfg.new." + String.valueOf(System.currentTimeMillis());
+        cfg.add(new FileConfigItem(tmpCfgFilePath, tmpCfgFileName, buff.toString()));
+
+        String[][] rules = cfgtr.generateFwRules(cmd);
+
+        String[] addRules = rules[LoadBalancerConfigurator.ADD];
+        String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
+        String[] statRules = rules[LoadBalancerConfigurator.STATS];
+
+        String args = " -f " + tmpCfgFilePath + tmpCfgFileName;
+        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;
+            cfg.add(new ScriptConfigItem(VRScripts.LB, args));
+        } else {
+            args = " -i " + cmd.getNic().getIp() + args;
+            cfg.add(new ScriptConfigItem(VRScripts.VPC_LB, args));
+        }
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(VmDataCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        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;
+
+        cfg.add(new ScriptConfigItem(VRScripts.VMDATA, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SavePasswordCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        final String password = cmd.getPassword();
+        final String vmIpAddress = cmd.getVmIpAddress();
+
+        String args = "-v " + vmIpAddress;
+        args += " -p " + password;
+
+        cfg.add(new ScriptConfigItem(VRScripts.PASSWORD, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(DhcpEntryCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        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";
+        }
+        cfg.add(new ScriptConfigItem(VRScripts.DHCP, args));
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(CreateIpAliasCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
+        String args = "";
+        for (IpAliasTO ipaliasto : ipAliasTOs) {
+            args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
+        }
+
+        cfg.add(new ScriptConfigItem(VRScripts.IPALIAS_CREATE, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(DeleteIpAliasCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        StringBuffer buff = new StringBuffer();
+        List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
+        for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
+            buff.append(ipAliasTO.getAlias_count());
+            buff.append(":");
+            buff.append(ipAliasTO.getRouterip());
+            buff.append(":");
+            buff.append(ipAliasTO.getNetmask());
+            buff.append("-");
+        }
+        //this is to ensure that thre is some argument passed to the deleteipAlias script  when there are no revoked rules.
+        buff.append("- ");
+        List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
+        for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
+            buff.append(ipAliasTO.getAlias_count());
+            buff.append(":");
+            buff.append(ipAliasTO.getRouterip());
+            buff.append(":");
+            buff.append(ipAliasTO.getNetmask());
+            buff.append("-");
+        }
+        cfg.add(new ScriptConfigItem(VRScripts.IPALIAS_DELETE, buff.toString()));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(DnsMasqConfigCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        List<DhcpTO> dhcpTos = cmd.getIps();
+        StringBuffer buff = new StringBuffer();
+        for (DhcpTO dhcpTo : dhcpTos) {
+            buff.append(dhcpTo.getRouterIp());
+            buff.append(":");
+            buff.append(dhcpTo.getGateway());
+            buff.append(":");
+            buff.append(dhcpTo.getNetmask());
+            buff.append(":");
+            buff.append(dhcpTo.getStartIpOfSubnet());
+            buff.append("-");
+        }
+        cfg.add(new ScriptConfigItem(VRScripts.DNSMASQ_CONFIG, buff.toString()));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(BumpUpPriorityCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        cfg.add(new ScriptConfigItem(VRScripts.RVR_BUMPUP_PRI, null));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(Site2SiteVpnCfgCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        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();
+        }
+
+        cfg.add(new ScriptConfigItem(VRScripts.S2SVPN_IPSEC, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetMonitorServiceCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        String config = cmd.getConfiguration();
+        String disableMonitoring = cmd.getAccessDetail(NetworkElementCommand.ROUTER_MONITORING_ENABLE);
+
+        String args = " -c " + config;
+        if (disableMonitoring != null) {
+            args = args + " -d";
+        }
+
+        cfg.add(new ScriptConfigItem(VRScripts.MONITOR_SERVICE, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetupGuestNetworkCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        NicTO nic = cmd.getNic();
+        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;
+            }
+        }
+
+        String dev = "eth" + nic.getDeviceId();
+        String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask());
+        String args = "";
+        if (cmd.isAdd() == false) {
+            //pass the argument to script to delete the network
+            args += " -D";
+        } else {
+            // pass create option argument if the ip needs to be added to eth device
+            args += " -C";
+        }
+        args += " -M " + nic.getMac();
+        args += " -d " + dev;
+        args += " -i " + routerGIP;
+        args += " -g " + gateway;
+        args += " -m " + cidr;
+        args += " -n " + netmask;
+        if (dns != null && !dns.isEmpty()) {
+            args += " -s " + dns;
+        }
+        if (domainName != null && !domainName.isEmpty()) {
+            args += " -e " + domainName;
+        }
+
+        cfg.add(new ScriptConfigItem(VRScripts.VPC_GUEST_NETWORK, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetNetworkACLCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
+
+        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 args = " -d " + dev;
+        args += " -M " + nic.getMac();
+        if (privateGw != null) {
+            args += " -a " + rule;
+
+            cfg.add(new ScriptConfigItem(VRScripts.VPC_PRIVATEGW_ACL, args));
+        } else {
+            args += " -i " + nic.getIp();
+            args += " -m " + netmask;
+            args += " -a " + rule;
+            cfg.add(new ScriptConfigItem(VRScripts.VPC_ACL, args));
+        }
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetSourceNatCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        IpAddressTO pubIP = cmd.getIpAddress();
+        String dev = "eth" + pubIP.getNicDevId();
+        String args = "-A";
+        args += " -l ";
+        args += pubIP.getPublicIp();
+        args += " -c ";
+        args += dev;
+
+        cfg.add(new ScriptConfigItem(VRScripts.VPC_SOURCE_NAT, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetPortForwardingRulesVpcCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        for (PortForwardingRuleTO rule : cmd.getRules()) {
+            String 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(":", "-");
+
+            cfg.add(new ScriptConfigItem(VRScripts.VPC_PORTFORWARDING, args));
+        }
+
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(SetStaticRouteCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+
+        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();
+
+        cfg.add(new ScriptConfigItem(VRScripts.VPC_STATIC_ROUTE, args));
+        return cfg;
+    }
+
+    private static List<ConfigItem> generateConfig(IpAssocCommand cmd) {
+        LinkedList<ConfigItem> cfg = new LinkedList<>();
+        ConfigItem c;
+
+        //Gson gson = new Gson();
+        //ConfigItem ipAssociationsFile = new FileConfigItem(VRScripts.CONFIG_PERSIST_LOCATION, VRScripts.IP_ASSOCIATION_CONFIG, gson.toJson(cmd.getIpAddresses()));
+        //cfg.add(ipAssociationsFile);
+
+        if (cmd instanceof IpAssocVpcCommand) {
+            for (IpAddressTO ip : cmd.getIpAddresses()) {
+                String args = "";
+                String snatArgs = "";
+
+                if (ip.isAdd()) {
+                    args += " -A ";
+                    snatArgs += " -A ";
+                } else {
+                    args += " -D ";
+                    snatArgs += " -D ";
+                }
+
+                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());
+
+                c = new ScriptConfigItem(VRScripts.VPC_IPASSOC, args);
+                c.setInfo(ip.getPublicIp() + " - vpc_ipassoc");
+                cfg.add(c);
+
+                if (ip.isSourceNat()) {
+                    snatArgs += " -l " + ip.getPublicIp();
+                    snatArgs += " -c " + nicName;
+
+                    c = new ScriptConfigItem(VRScripts.VPC_PRIVATEGW, snatArgs);
+                    c.setInfo(ip.getPublicIp() + " - vpc_privategateway");
+                    cfg.add(c);
+                }
+            }
+        } else {
+            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;
+
+                String publicNic = "eth" + ip.getNicDevId();
+                args += " -c ";
+                args += publicNic;
+
+                args += " -g ";
+                args += ip.getVlanGateway();
+
+                if (ip.isNewNic()) {
+                    args += " -n";
+                }
+
+                c = new ScriptConfigItem(VRScripts.IPASSOC, args);
+                c.setInfo(ip.getPublicIp());
+                cfg.add(c);
+            }
+        }
+        return cfg;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/core/src/com/cloud/agent/resource/virtualnetwork/ConfigItem.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/ConfigItem.java b/core/src/com/cloud/agent/resource/virtualnetwork/ConfigItem.java
new file mode 100644
index 0000000..0d622ce
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/ConfigItem.java
@@ -0,0 +1,16 @@
+package com.cloud.agent.resource.virtualnetwork;
+
+public abstract class ConfigItem {
+    private String info;
+
+
+    public String getInfo() {
+        return info;
+    }
+
+    public void setInfo(String info) {
+        this.info = info;
+    }
+
+    public abstract String getAggregateCommand();
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/core/src/com/cloud/agent/resource/virtualnetwork/FileConfigItem.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/FileConfigItem.java b/core/src/com/cloud/agent/resource/virtualnetwork/FileConfigItem.java
new file mode 100644
index 0000000..20a09aa
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/FileConfigItem.java
@@ -0,0 +1,56 @@
+package com.cloud.agent.resource.virtualnetwork;
+
+public class FileConfigItem extends ConfigItem {
+    private String filePath;
+    private String fileName;
+    private String fileContents;
+
+    public FileConfigItem(String filePath, String fileName, String fileContents) {
+        this.filePath = filePath;
+        this.fileName = fileName;
+        this.fileContents = fileContents;
+    }
+
+    public String getFilePath() {
+        return filePath;
+    }
+
+    public void setFilePath(String filePath) {
+        this.filePath = filePath;
+    }
+
+    public String getFileName() {
+        return fileName;
+    }
+
+    public void setFileName(String fileName) {
+        this.fileName = fileName;
+    }
+
+    public String getFileContents() {
+        return fileContents;
+    }
+
+    public void setFileContents(String fileContents) {
+        this.fileContents = fileContents;
+    }
+
+    @Override
+    public String getAggregateCommand() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("<file>\n");
+        sb.append(filePath);
+
+        // Don't use File.pathSeparator here as the target is the unix based systemvm
+        if (!filePath.endsWith("/")) {
+            sb.append('/');
+        }
+
+        sb.append(fileName);
+        sb.append('\n');
+        sb.append(fileContents);
+        sb.append("\n</file>\n");
+        return sb.toString();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/core/src/com/cloud/agent/resource/virtualnetwork/ScriptConfigItem.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/ScriptConfigItem.java b/core/src/com/cloud/agent/resource/virtualnetwork/ScriptConfigItem.java
new file mode 100644
index 0000000..133d2aa
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/ScriptConfigItem.java
@@ -0,0 +1,40 @@
+package com.cloud.agent.resource.virtualnetwork;
+
+public class ScriptConfigItem extends ConfigItem {
+    private String script;
+    private String args;
+
+    public ScriptConfigItem(String script, String args) {
+        this.script = script;
+        this.args = args;
+    }
+
+    public String getScript() {
+        return script;
+    }
+
+    public void setScript(String script) {
+        this.script = script;
+    }
+
+    public String getArgs() {
+        return args;
+    }
+
+    public void setArgs(String args) {
+        this.args = args;
+    }
+
+    @Override
+    public String getAggregateCommand() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("<script>\n");
+        sb.append("/opt/cloud/bin/");
+        sb.append(script);
+        sb.append(' ');
+        sb.append(args);
+        sb.append("\n</script>\n");
+        return sb.toString();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
new file mode 100644
index 0000000..05ddab0
--- /dev/null
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
@@ -0,0 +1,40 @@
+package com.cloud.agent.resource.virtualnetwork;
+
+public class VRScripts {
+    protected final static String CONFIG_PERSIST_LOCATION = "/etc/cloudstack/";
+    protected final static String IP_ASSOCIATION_CONFIG = "ip_associations.json";
+    protected final static String CONFIG_CACHE_LOCATION = "/var/cache/cloud/";
+    protected final static int DEFAULT_EXECUTEINVR_TIMEOUT = 120; //Seconds
+
+    protected static final String S2SVPN_CHECK = "checkbatchs2svpn.sh";
+    protected static final String S2SVPN_IPSEC = "ipsectunnel.sh";
+    protected static final String DHCP = "edithosts.sh";
+    protected static final String DNSMASQ_CONFIG = "dnsmasq.sh";
+    protected static final String FIREWALL_EGRESS = "firewall_egress.sh";
+    protected static final String FIREWALL_INGRESS = "firewall_ingress.sh";
+    protected static final String FIREWALL_NAT = "firewall_nat.sh";
+    protected static final String IPALIAS_CREATE = "createipAlias.sh";
+    protected static final String IPALIAS_DELETE = "deleteipAlias.sh";
+    protected static final String IPASSOC = "ipassoc.sh";
+    protected static final String LB = "loadbalancer.sh";
+    protected static final String MONITOR_SERVICE = "monitor_service.sh";
+    protected static final String ROUTER_ALERTS = "getRouterAlerts.sh";
+    protected static final String PASSWORD = "savepassword.sh";
+    protected static final String RVR_CHECK = "checkrouter.sh";
+    protected static final String RVR_BUMPUP_PRI = "bumpup_priority.sh";
+    protected static final String VMDATA = "vmdata.py";
+    protected static final String VERSION = "get_template_version.sh";
+    protected static final String VPC_ACL = "vpc_acl.sh";
+    protected static final String VPC_GUEST_NETWORK = "vpc_guestnw.sh";
+    protected static final String VPC_IPASSOC = "vpc_ipassoc.sh";
+    protected static final String VPC_LB = "vpc_loadbalancer.sh";
+    protected static final String VPC_PRIVATEGW = "vpc_privateGateway.sh";
+    protected static final String VPC_PRIVATEGW_ACL = "vpc_privategw_acl.sh";
+    protected static final String VPC_PORTFORWARDING = "vpc_portforwarding.sh";
+    protected static final String VPC_SOURCE_NAT = "vpc_snat.sh";
+    protected static final String VPC_STATIC_NAT = "vpc_staticnat.sh";
+    protected static final String VPC_STATIC_ROUTE = "vpc_staticroute.sh";
+    protected static final String VPN_L2TP = "vpn_l2tp.sh";
+
+    protected static final String VR_CFG = "vr_cfg.sh";
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c1276790/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 de1049b..bb2dac9 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -16,71 +16,39 @@
 // under the License.
 package com.cloud.agent.resource.virtualnetwork;
 
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.UUID;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+
 import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.BumpUpPriorityCommand;
 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.GetDomRVersionAnswer;
 import com.cloud.agent.api.GetDomRVersionCmd;
-import com.cloud.agent.api.SetupGuestNetworkCommand;
+import com.cloud.agent.api.GetRouterAlertsAnswer;
 import com.cloud.agent.api.routing.AggregationControlCommand;
 import com.cloud.agent.api.routing.AggregationControlCommand.Action;
-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.GroupAnswer;
 import com.cloud.agent.api.routing.GetRouterAlertsCommand;
-import com.cloud.agent.api.GetRouterAlertsAnswer;
-import com.cloud.agent.api.routing.IpAliasTO;
-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.GroupAnswer;
 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.SetFirewallRulesCommand;
-import com.cloud.agent.api.routing.SetMonitorServiceCommand;
-import com.cloud.agent.api.routing.SetNetworkACLCommand;
-import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
-import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
-import com.cloud.agent.api.routing.SetSourceNatCommand;
-import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
-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.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.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.net.NetUtils;
-import com.google.gson.Gson;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-
-import javax.naming.ConfigurationException;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.channels.SocketChannel;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.UUID;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
+import com.cloud.utils.exception.CloudRuntimeException;
 
 /**
  * VirtualNetworkResource controls and configures virtual networking
@@ -91,43 +59,10 @@ import java.util.concurrent.locks.ReentrantLock;
  *  }
  **/
 public class VirtualRoutingResource {
-    protected class VRScripts {
-        protected static final String S2SVPN_CHECK = "checkbatchs2svpn.sh";
-        protected static final String S2SVPN_IPSEC = "ipsectunnel.sh";
-        protected static final String DHCP = "edithosts.sh";
-        protected static final String DNSMASQ_CONFIG = "dnsmasq.sh";
-        protected static final String FIREWALL_EGRESS = "firewall_egress.sh";
-        protected static final String FIREWALL_INGRESS = "firewall_ingress.sh";
-        protected static final String FIREWALL_NAT = "firewall_nat.sh";
-        protected static final String IPALIAS_CREATE = "createipAlias.sh";
-        protected static final String IPALIAS_DELETE = "deleteipAlias.sh";
-        protected static final String IPASSOC = "ipassoc.sh";
-        protected static final String LB = "loadbalancer.sh";
-        protected static final String MONITOR_SERVICE = "monitor_service.sh";
-        protected static final String ROUTER_ALERTS = "getRouterAlerts.sh";
-        protected static final String PASSWORD = "savepassword.sh";
-        protected static final String RVR_CHECK = "checkrouter.sh";
-        protected static final String RVR_BUMPUP_PRI = "bumpup_priority.sh";
-        protected static final String VMDATA = "vmdata.py";
-        protected static final String VERSION = "get_template_version.sh";
-        protected static final String VPC_ACL = "vpc_acl.sh";
-        protected static final String VPC_GUEST_NETWORK = "vpc_guestnw.sh";
-        protected static final String VPC_IPASSOC = "vpc_ipassoc.sh";
-        protected static final String VPC_LB = "vpc_loadbalancer.sh";
-        protected static final String VPC_PRIVATEGW = "vpc_privateGateway.sh";
-        protected static final String VPC_PRIVATEGW_ACL = "vpc_privategw_acl.sh";
-        protected static final String VPC_PORTFORWARDING = "vpc_portforwarding.sh";
-        protected static final String VPC_SOURCE_NAT = "vpc_snat.sh";
-        protected static final String VPC_STATIC_NAT = "vpc_staticnat.sh";
-        protected static final String VPC_STATIC_ROUTE = "vpc_staticroute.sh";
-        protected static final String VPN_L2TP = "vpn_l2tp.sh";
-
-        protected static final String VR_CFG = "vr_cfg.sh";
-    }
 
     private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class);
     private VirtualRouterDeployer _vrDeployer;
-    private Map <String, Queue> _vrAggregateCommandsSet;
+    private Map<String, Queue<NetworkElementCommand>> _vrAggregateCommandsSet;
     protected Map<String, Lock> _vrLockMap = new HashMap<String, Lock>();
 
     private String _name;
@@ -139,7 +74,7 @@ public class VirtualRoutingResource {
     private String _cfgVersion = "1.0";
 
     public VirtualRoutingResource(VirtualRouterDeployer deployer) {
-        this._vrDeployer = deployer;
+        _vrDeployer = deployer;
     }
 
     public Answer executeRequest(final NetworkElementCommand cmd) {
@@ -198,81 +133,6 @@ public class VirtualRoutingResource {
         }
     }
 
-    protected class ConfigItem {
-        private String script;
-        private String args;
-        private String info;
-        private String filePath;
-        private String fileName;
-        private String fileContents;
-        private boolean isFile;
-
-        public ConfigItem(String script, String args) {
-            this.script = script;
-            this.args = args;
-            this.isFile = false;
-        }
-
-        public ConfigItem(String filePath, String fileName, String fileContents) {
-            this.filePath = filePath;
-            this.fileName = fileName;
-            this.fileContents = fileContents;
-            this.isFile = true;
-        }
-
-        public String getScript() {
-            return script;
-        }
-
-        public void setScript(String script) {
-            this.script = script;
-        }
-
-        public String getArgs() {
-            return args;
-        }
-
-        public void setArgs(String args) {
-            this.args = args;
-        }
-
-        public String getInfo() {
-            return info;
-        }
-
-        public void setInfo(String info) {
-            this.info = info;
-        }
-
-        public String getFilePath() {
-            return filePath;
-        }
-
-        public void setFilePath(String filePath) {
-            this.filePath = filePath;
-        }
-
-        public String getFileName() {
-            return fileName;
-        }
-
-        public void setFileName(String fileName) {
-            this.fileName = fileName;
-        }
-
-        public String getFileContents() {
-            return fileContents;
-        }
-
-        public void setFileContents(String fileContents) {
-            this.fileContents = fileContents;
-        }
-
-        public boolean isFile() {
-            return isFile;
-        }
-    }
-
     private Answer executeQueryCommand(NetworkElementCommand cmd) {
         if (cmd instanceof CheckRouterCommand) {
             return execute((CheckRouterCommand)cmd);
@@ -288,370 +148,48 @@ public class VirtualRoutingResource {
         }
     }
 
-    private ExecutionResult applyConfigToVR(NetworkElementCommand cmd, ConfigItem c) {
-        if (c.isFile()) {
-            return _vrDeployer.createFileInVR(cmd.getRouterAccessIp(), c.getFilePath(), c.getFileName(), c.getFileContents());
-        } else {
-            return _vrDeployer.executeInVR(cmd.getRouterAccessIp(), c.getScript(), c.getArgs());
-        }
-    }
-
-    private Answer applyConfig(NetworkElementCommand cmd, List<ConfigItem> cfg) {
-        int answersCount = cmd.getAnswersCount();
-
-        // Use the last answer as final answer
-        if (answersCount == 1) {
-            ExecutionResult result = new ExecutionResult(true, "No configure to be applied");
-            for (ConfigItem c : cfg) {
-                result = applyConfigToVR(cmd, c);
-                if (!result.isSuccess()) {
-                    break;
-                }
-            }
-            return new Answer(cmd, result.isSuccess(), result.getDetails());
-        }
-
-        ExecutionResult[] results = new ExecutionResult[answersCount];
-        String[] resultsString = new String[answersCount];
-        boolean finalResult = true;
-        int i = 0, j;
-        for (ConfigItem c : cfg) {
-            results[i] = applyConfigToVR(cmd, c);
-            if (c.getInfo() != null) {
-                if (results[i].isSuccess()) {
-                    results[i].setDetails(c.getInfo() + " - success: " + results[i].getDetails());
-                } else {
-                    results[i].setDetails(c.getInfo() + " - failed: " + results[i].getDetails());
-                }
-            }
-            i ++;
-        }
-        i = 0; j = 0;
-        while (j < answersCount) {
-            resultsString[j] = results[i].getDetails();
-            if (!results[i].isSuccess()) {
-                finalResult = false;
-            }
-            // Fill the resultsString with the last result of execution, mostly in 1:n
-            if (i < cfg.size() - 1) {
-                i ++;
-            }
-            j ++;
-        }
-        return new GroupAnswer(cmd, finalResult, answersCount, resultsString);
-    }
-
-    private List<ConfigItem> generateConfig(VpnUsersCfgCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) {
-            String args = "";
-            if (!userpwd.isAdd()) {
-                args += "-U ";
-                args += userpwd.getUsername();
-            } else {
-                args += "-u ";
-                args += userpwd.getUsernamePassword();
-            }
-            cfg.add(new ConfigItem(VRScripts.VPN_L2TP, args));
-        }
-        return cfg;
+    private ExecutionResult applyConfigToVR(String routerAccessIp, ConfigItem c) {
+        return applyConfigToVR(routerAccessIp, c, VRScripts.DEFAULT_EXECUTEINVR_TIMEOUT);
     }
 
-    private List<ConfigItem> generateConfig(RemoteAccessVpnCfgCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        String args = "";
-        if (cmd.isCreate()) {
-            args += "-r ";
-            args += cmd.getIpRange();
-            args += " -p ";
-            args += cmd.getPresharedKey();
-            args += " -s ";
-            args += cmd.getVpnServerIp();
-            args += " -l ";
-            args += cmd.getLocalIp();
-            args += " -c ";
-        } else {
-            args += "-d ";
-            args += " -s ";
-            args += cmd.getVpnServerIp();
+    private ExecutionResult applyConfigToVR(String routerAccessIp, ConfigItem c, int timeout) {
+        if (c instanceof FileConfigItem) {
+            FileConfigItem configItem = (FileConfigItem)c;
+            return _vrDeployer.createFileInVR(routerAccessIp, configItem.getFilePath(), configItem.getFileName(), configItem.getFileContents());
+        } else if (c instanceof ScriptConfigItem) {
+            ScriptConfigItem configItem = (ScriptConfigItem)c;
+            return _vrDeployer.executeInVR(routerAccessIp, configItem.getScript(), configItem.getArgs(), timeout);
         }
-        args += " -C " + cmd.getLocalCidr();
-        args += " -i " + cmd.getPublicInterface();
-        cfg.add(new ConfigItem(VRScripts.VPN_L2TP, args));
-        return cfg;
+        throw new CloudRuntimeException("Unable to apply unknown configitem of type " + c.getClass().getSimpleName());
     }
 
-    private List<ConfigItem> generateConfig(SetFirewallRulesCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
-
-        FirewallRuleTO[] allrules = cmd.getRules();
-        FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
-
-        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) {
-            cfg.add(new ConfigItem(VRScripts.FIREWALL_EGRESS, args));
-        } else {
-            cfg.add(new ConfigItem(VRScripts.FIREWALL_INGRESS, args));
-        }
-
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(SetPortForwardingRulesCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        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());
-            cfg.add(new ConfigItem(VRScripts.FIREWALL_NAT, args.toString()));
-        }
-
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(SetStaticNatRulesCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        if (cmd.getVpcId() != null) {
-            for (StaticNatRuleTO rule : cmd.getRules()) {
-                String args = rule.revoked() ? " -D" : " -A";
-                args += " -l " + rule.getSrcIp();
-                args += " -r " + rule.getDstIp();
-
-                cfg.add(new ConfigItem(VRScripts.VPC_STATIC_NAT, args));
-            }
-        } else {
-            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 ");
-
-                cfg.add(new ConfigItem(VRScripts.FIREWALL_NAT, args.toString()));
-            }
-        }
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(LoadBalancerConfigCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
-        LoadBalancerConfigurator cfgtr = new HAProxyConfigurator();
-
-        String[] config = cfgtr.generateConfiguration(cmd);
-        StringBuffer buff = new StringBuffer();
-        for (int i = 0; i < config.length; i++) {
-            buff.append(config[i]);
-            buff.append("\n");
-        }
-        String tmpCfgFilePath = "/etc/haproxy/";
-        String tmpCfgFileName = "haproxy.cfg.new." + String.valueOf(System.currentTimeMillis());
-        cfg.add(new ConfigItem(tmpCfgFilePath, tmpCfgFileName, buff.toString()));
-
-        String[][] rules = cfgtr.generateFwRules(cmd);
-
-        String[] addRules = rules[LoadBalancerConfigurator.ADD];
-        String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
-        String[] statRules = rules[LoadBalancerConfigurator.STATS];
-
-        String args = " -f " + tmpCfgFilePath + tmpCfgFileName;
-        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(',');
+    private Answer applyConfig(NetworkElementCommand cmd, List<ConfigItem> cfg) {
+        List<ExecutionResult> results = new ArrayList<ExecutionResult>();
+        List<String> details = new ArrayList<String>();
+        boolean finalResult = false;
+        for (ConfigItem configItem : cfg) {
+            ExecutionResult result = applyConfigToVR(cmd.getRouterAccessIp(), configItem);
+            if (result == null) {
+                result = new ExecutionResult(false, "null execution result");
             }
-
-            args += " -d " + sb.toString();
+            results.add(result);
+            details.add(configItem.getInfo() + (result.isSuccess() ? " - success: " : " - failed: ") + result.getDetails());
+            finalResult = result.isSuccess();
         }
 
-        sb = new StringBuilder();
-        if (statRules.length > 0) {
-            for (int i = 0; i < statRules.length; i++) {
-                sb.append(statRules[i]).append(',');
-            }
-
-            args += " -s " + sb.toString();
+        // Not sure why this matters, but log it anyway
+        if (cmd.getAnswersCount() != results.size()) {
+            s_logger.warn("Expected " + cmd.getAnswersCount() + " answers while executing " + cmd.getClass().getSimpleName() + " but received " + results.size());
         }
 
-        if (cmd.getVpcId() == null) {
-            args = " -i " + routerIp + args;
-            cfg.add(new ConfigItem(VRScripts.LB, args));
+        if (results.size() == 1) {
+            return new Answer(cmd, finalResult, results.get(0).getDetails());
         } else {
-            args = " -i " + cmd.getNic().getIp() + args;
-            cfg.add(new ConfigItem(VRScripts.VPC_LB, args));
-        }
-
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(VmDataCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        Map<String, List<String[]>> data = new HashMap<String, List<String[]>>();
-        data.put(cmd.getVmIpAddress(), cmd.getVmData());
-
-        String json = new Gson().toJson(data);
-        s_logger.debug("JSON IS:" + json);
-
-        json = Base64.encodeBase64String(json.getBytes());
-
-        String args = "-d " + json;
-
-        cfg.add(new ConfigItem(VRScripts.VMDATA, args));
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(SavePasswordCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        final String password = cmd.getPassword();
-        final String vmIpAddress = cmd.getVmIpAddress();
-
-        String args = "-v " + vmIpAddress;
-        args += " -p " + password;
-
-        cfg.add(new ConfigItem(VRScripts.PASSWORD, args));
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(DhcpEntryCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String args = " -m " + cmd.getVmMac();
-        if (cmd.getVmIpAddress() != null) {
-            args += " -4 " + cmd.getVmIpAddress();
+            return new GroupAnswer(cmd, finalResult, results.size(), details.toArray(new String[details.size()]));
         }
-        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";
-        }
-        cfg.add(new ConfigItem(VRScripts.DHCP, args));
-
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(CreateIpAliasCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
-        String args = "";
-        for (IpAliasTO ipaliasto : ipAliasTOs) {
-            args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
-        }
-
-        cfg.add(new ConfigItem(VRScripts.IPALIAS_CREATE, args));
-        return cfg;
     }
 
-    private List<ConfigItem> generateConfig(DeleteIpAliasCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String args = "";
-        StringBuffer buff = new StringBuffer();
-        List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
-        for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
-            buff.append(ipAliasTO.getAlias_count());
-            buff.append(":");
-            buff.append(ipAliasTO.getRouterip());
-            buff.append(":");
-            buff.append(ipAliasTO.getNetmask());
-            buff.append("-");
-         }
-        //this is to ensure that thre is some argument passed to the deleteipAlias script  when there are no revoked rules.
-        buff.append("- ");
-        List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
-        for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
-            buff.append(ipAliasTO.getAlias_count());
-            buff.append(":");
-            buff.append(ipAliasTO.getRouterip());
-            buff.append(":");
-            buff.append(ipAliasTO.getNetmask());
-            buff.append("-");
-        }
-        cfg.add(new ConfigItem(VRScripts.IPALIAS_DELETE, buff.toString()));
-        return cfg;
-    }
-
-    private List<ConfigItem> generateConfig(DnsMasqConfigCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        List<DhcpTO> dhcpTos = cmd.getIps();
-        StringBuffer buff = new StringBuffer();
-        for (DhcpTO dhcpTo : dhcpTos) {
-            buff.append(dhcpTo.getRouterIp());
-            buff.append(":");
-            buff.append(dhcpTo.getGateway());
-            buff.append(":");
-            buff.append(dhcpTo.getNetmask());
-            buff.append(":");
-            buff.append(dhcpTo.getStartIpOfSubnet());
-            buff.append("-");
-        }
-        cfg.add(new ConfigItem(VRScripts.DNSMASQ_CONFIG, buff.toString()));
-        return cfg;
-    }
 
     private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
 
@@ -693,12 +231,6 @@ public class VirtualRoutingResource {
         return new CheckRouterAnswer(cmd, result.getDetails(), true);
     }
 
-    private List<ConfigItem> generateConfig(BumpUpPriorityCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        cfg.add(new ConfigItem(VRScripts.RVR_BUMPUP_PRI, null));
-        return cfg;
-    }
-
     protected Answer execute(GetDomRVersionCmd cmd) {
         final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), VRScripts.VERSION, null);
         if (!result.isSuccess()) {
@@ -711,277 +243,6 @@ public class VirtualRoutingResource {
         return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]);
     }
 
-    private List<ConfigItem> generateConfig(Site2SiteVpnCfgCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        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();
-        }
-
-        cfg.add(new ConfigItem(VRScripts.S2SVPN_IPSEC, args));
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetMonitorServiceCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String config = cmd.getConfiguration();
-        String disableMonitoring =  cmd.getAccessDetail(NetworkElementCommand.ROUTER_MONITORING_ENABLE);
-
-        String args = " -c " + config;
-        if (disableMonitoring != null) {
-            args = args + " -d";
-        }
-
-        cfg.add(new ConfigItem(VRScripts.MONITOR_SERVICE, args));
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetupGuestNetworkCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        NicTO nic = cmd.getNic();
-        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;
-            }
-        }
-
-        String dev = "eth" + nic.getDeviceId();
-        String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask());
-        String args = "";
-        if(cmd.isAdd() == false) {
-            //pass the argument to script to delete the network
-            args +=" -D";
-        } else {
-            // pass create option argument if the ip needs to be added to eth device
-            args +=" -C";
-        }
-        args += " -M " + nic.getMac();
-        args += " -d " + dev;
-        args += " -i " + routerGIP;
-        args += " -g " + gateway;
-        args += " -m " + cidr;
-        args += " -n " + netmask;
-        if (dns != null && !dns.isEmpty()) {
-            args += " -s " + dns;
-        }
-        if (domainName != null && !domainName.isEmpty()) {
-            args += " -e " + domainName;
-        }
-
-        cfg.add(new ConfigItem(VRScripts.VPC_GUEST_NETWORK, args));
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetNetworkACLCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
-
-        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 args = " -d " + dev;
-        args += " -M " + nic.getMac();
-        if (privateGw != null) {
-            args += " -a " + rule;
-
-            cfg.add(new ConfigItem(VRScripts.VPC_PRIVATEGW_ACL, args));
-        } else {
-            args += " -i " + nic.getIp();
-            args += " -m " + netmask;
-            args += " -a " + rule;
-            cfg.add(new ConfigItem(VRScripts.VPC_ACL, args));
-        }
-
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetSourceNatCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        IpAddressTO pubIP = cmd.getIpAddress();
-        String dev = "eth" + pubIP.getNicDevId();
-        String args = "-A";
-        args += " -l ";
-        args += pubIP.getPublicIp();
-        args += " -c ";
-        args += dev;
-
-        cfg.add(new ConfigItem(VRScripts.VPC_SOURCE_NAT, args));
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetPortForwardingRulesVpcCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        for (PortForwardingRuleTO rule : cmd.getRules()) {
-            String 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(":", "-");
-
-            cfg.add(new ConfigItem(VRScripts.VPC_PORTFORWARDING, args));
-        }
-
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(SetStaticRouteCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-
-        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();
-
-        cfg.add(new ConfigItem(VRScripts.VPC_STATIC_ROUTE, args));
-        return cfg;
-    }
-
-    protected List<ConfigItem> generateConfig(IpAssocCommand cmd) {
-        LinkedList<ConfigItem> cfg = new LinkedList<>();
-        ConfigItem c;
-
-        if (cmd instanceof IpAssocVpcCommand) {
-            for (IpAddressTO ip : cmd.getIpAddresses()) {
-                String args = "";
-                String snatArgs = "";
-
-                if (ip.isAdd()) {
-                    args += " -A ";
-                    snatArgs += " -A ";
-                } else {
-                    args += " -D ";
-                    snatArgs += " -D ";
-                }
-
-                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());
-
-                c = new ConfigItem(VRScripts.VPC_IPASSOC, args);
-                c.setInfo(ip.getPublicIp() + " - vpc_ipassoc");
-                cfg.add(c);
-
-                if (ip.isSourceNat()) {
-                    snatArgs += " -l " + ip.getPublicIp();
-                    snatArgs += " -c " + nicName;
-
-                    c = new ConfigItem(VRScripts.VPC_PRIVATEGW, snatArgs);
-                    c.setInfo(ip.getPublicIp() + " - vpc_privategateway");
-                    cfg.add(c);
-                }
-            }
-        } else {
-            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;
-
-                String publicNic = "eth" + ip.getNicDevId();
-                args += " -c ";
-                args += publicNic;
-
-                args += " -g ";
-                args += ip.getVlanGateway();
-
-                if (ip.isNewNic()) {
-                    args += " -n";
-                }
-
-                c = new ConfigItem(VRScripts.IPASSOC, args);
-                c.setInfo(ip.getPublicIp());
-                cfg.add(c);
-            }
-        }
-        return cfg;
-    }
 
     public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
         _name = name;
@@ -1083,53 +344,7 @@ public class VirtualRoutingResource {
     }
 
     private List<ConfigItem> generateCommandCfg(NetworkElementCommand cmd) {
-        List<ConfigItem> cfg;
-        if (cmd instanceof SetPortForwardingRulesVpcCommand) {
-            cfg = generateConfig((SetPortForwardingRulesVpcCommand)cmd);
-        } else if (cmd instanceof SetPortForwardingRulesCommand) {
-            cfg = generateConfig((SetPortForwardingRulesCommand)cmd);
-        } else if (cmd instanceof SetStaticRouteCommand) {
-            cfg = generateConfig((SetStaticRouteCommand)cmd);
-        } else if (cmd instanceof SetStaticNatRulesCommand) {
-            cfg = generateConfig((SetStaticNatRulesCommand)cmd);
-        } else if (cmd instanceof LoadBalancerConfigCommand) {
-            cfg = generateConfig((LoadBalancerConfigCommand)cmd);
-        } else if (cmd instanceof SavePasswordCommand) {
-            cfg = generateConfig((SavePasswordCommand)cmd);
-        } else if (cmd instanceof DhcpEntryCommand) {
-            cfg = generateConfig((DhcpEntryCommand)cmd);
-        } else if (cmd instanceof CreateIpAliasCommand) {
-            cfg = generateConfig((CreateIpAliasCommand)cmd);
-        } else if (cmd instanceof DnsMasqConfigCommand) {
-            cfg = generateConfig((DnsMasqConfigCommand)cmd);
-        } else if (cmd instanceof DeleteIpAliasCommand) {
-            cfg = generateConfig((DeleteIpAliasCommand)cmd);
-        } else if (cmd instanceof VmDataCommand) {
-            cfg = generateConfig((VmDataCommand)cmd);
-        } else if (cmd instanceof SetFirewallRulesCommand) {
-            cfg = generateConfig((SetFirewallRulesCommand)cmd);
-        } else if (cmd instanceof BumpUpPriorityCommand) {
-            cfg = generateConfig((BumpUpPriorityCommand)cmd);
-        } else if (cmd instanceof RemoteAccessVpnCfgCommand) {
-            cfg = generateConfig((RemoteAccessVpnCfgCommand)cmd);
-        } else if (cmd instanceof VpnUsersCfgCommand) {
-            cfg = generateConfig((VpnUsersCfgCommand)cmd);
-        } else if (cmd instanceof Site2SiteVpnCfgCommand) {
-            cfg = generateConfig((Site2SiteVpnCfgCommand)cmd);
-        } else if (cmd instanceof SetMonitorServiceCommand) {
-            cfg = generateConfig((SetMonitorServiceCommand)cmd);
-        } else if (cmd instanceof SetupGuestNetworkCommand) {
-            cfg = generateConfig((SetupGuestNetworkCommand)cmd);
-        } else if (cmd instanceof SetNetworkACLCommand) {
-            cfg = generateConfig((SetNetworkACLCommand)cmd);
-        } else if (cmd instanceof SetSourceNatCommand) {
-            cfg = generateConfig((SetSourceNatCommand)cmd);
-        } else if (cmd instanceof IpAssocCommand) {
-            cfg = generateConfig((IpAssocCommand)cmd);
-        } else {
-            return null;
-        }
-        return cfg;
+        return ConfigHelper.generateCommandCfg(cmd);
     }
 
     private Answer execute(AggregationControlCommand cmd) {
@@ -1160,34 +375,30 @@ public class VirtualRoutingResource {
                     }
 
                     for (ConfigItem c : cfg) {
-                        if (c.isFile()) {
-                            sb.append("<file>\n");
-                            sb.append(c.getFilePath() + c.getFileName() + "\n");
-                            sb.append(c.getFileContents() + "\n");
-                            sb.append("</file>\n");
-                        } else {
-                            sb.append("<script>\n");
-                            sb.append("/opt/cloud/bin/" + c.getScript() + " " + c.getArgs() + "\n");
-                            sb.append("</script>\n");
-                        }
+                        sb.append(c.getAggregateCommand());
                     }
                 }
-                String cfgFilePath = "/var/cache/cloud/";
-                String cfgFileName = "VR-"+ UUID.randomUUID().toString() + ".cfg";
-                ExecutionResult result = _vrDeployer.createFileInVR(cmd.getRouterAccessIp(), cfgFilePath, cfgFileName, sb.toString());
-                if (!result.isSuccess()) {
-                    return new Answer(cmd, false, result.getDetails());
-                }
 
+                // TODO replace with applyConfig with a stop on fail
+                String cfgFileName = "VR-"+ UUID.randomUUID().toString() + ".cfg";
+                FileConfigItem fileConfigItem = new FileConfigItem(VRScripts.CONFIG_CACHE_LOCATION, cfgFileName, sb.toString());
+                ScriptConfigItem scriptConfigItem = new ScriptConfigItem(VRScripts.VR_CFG, "-c " + VRScripts.CONFIG_CACHE_LOCATION + cfgFileName);
                 // 120s is the minimal timeout
                 int timeout = answerCounts * _eachTimeout;
                 if (timeout < 120) {
                     timeout = 120;
                 }
-                result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), VRScripts.VR_CFG, "-c " + cfgFilePath + cfgFileName, timeout);
+
+                ExecutionResult result = applyConfigToVR(cmd.getRouterAccessIp(), fileConfigItem);
+                if (!result.isSuccess()) {
+                    return new Answer(cmd, false, result.getDetails());
+                }
+
+                result = applyConfigToVR(cmd.getRouterAccessIp(), scriptConfigItem, timeout);
                 if (!result.isSuccess()) {
                     return new Answer(cmd, false, result.getDetails());
                 }
+
                 return new Answer(cmd);
             } finally {
                 queue.clear();