diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java index 109801c315a..a2515056be1 100644 --- a/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java @@ -45,37 +45,25 @@ public class VRScripts { // New scripts for use with chef public static final String UPDATE_CONFIG = "update_config.py"; + // Script still in use - mostly by HyperV public static final String S2SVPN_CHECK = "checkbatchs2svpn.sh"; public static final String S2SVPN_IPSEC = "ipsectunnel.sh"; public static final String DHCP = "edithosts.sh"; public static final String DNSMASQ_CONFIG = "dnsmasq.sh"; - public static final String FIREWALL_EGRESS = "firewall_egress.sh"; - public static final String FIREWALL_INGRESS = "firewall_ingress.sh"; - public static final String FIREWALL_NAT = "firewall_nat.sh"; - public static final String IPALIAS_CREATE = "createipAlias.sh"; - public static final String IPALIAS_DELETE = "deleteipAlias.sh"; public static final String IPASSOC = "ipassoc.sh"; public static final String LB = "loadbalancer.sh"; public static final String MONITOR_SERVICE = "monitor_service.sh"; - public static final String ROUTER_ALERTS = "getRouterAlerts.sh"; public static final String PASSWORD = "savepassword.sh"; + public static final String ROUTER_ALERTS = "getRouterAlerts.sh"; public static final String RVR_CHECK = "checkrouter.sh"; - public static final String RVR_BUMPUP_PRI = "bumpup_priority.sh"; public static final String VMDATA = "vmdata.py"; + public static final String RVR_BUMPUP_PRI = "bumpup_priority.sh"; public static final String VERSION = "get_template_version.sh"; - public static final String VPC_ACL = "vpc_acl.sh"; - public static final String VPC_GUEST_NETWORK = "vpc_guestnw.sh"; - public static final String VPC_IPASSOC = "vpc_ipassoc.sh"; - public static final String VPC_LB = "vpc_loadbalancer.sh"; - public static final String VPC_PRIVATEGW = "vpc_privateGateway.sh"; - public static final String VPC_PRIVATEGW_ACL = "vpc_privategw_acl.sh"; - public static final String VPC_PORTFORWARDING = "vpc_portforwarding.sh"; public static final String VPC_SOURCE_NAT = "vpc_snat.sh"; - public static final String VPC_STATIC_NAT = "vpc_staticnat.sh"; public static final String VPC_STATIC_ROUTE = "vpc_staticroute.sh"; public static final String VPN_L2TP = "vpn_l2tp.sh"; public static final String UPDATE_HOST_PASSWD = "update_host_passwd.sh"; public static final String VR_CFG = "vr_cfg.sh"; -} +} \ No newline at end of file diff --git a/core/test/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResourceTest.java b/core/test/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResourceTest.java index 5942a171871..c4e134bd261 100644 --- a/core/test/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResourceTest.java +++ b/core/test/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResourceTest.java @@ -24,8 +24,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -83,9 +81,6 @@ import com.cloud.network.vpc.NetworkACLItem.TrafficType; import com.cloud.network.vpc.VpcGateway; import com.cloud.utils.ExecutionResult; import com.cloud.utils.net.NetUtils; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) @@ -154,18 +149,14 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { private void verifyFile(final NetworkElementCommand cmd, final String path, final String filename, final String content) { if (cmd instanceof AggregationControlCommand) { - verifyFile((AggregationControlCommand)cmd, path, filename, content); + verifyFile(cmd, path, filename, content); } else if (cmd instanceof LoadBalancerConfigCommand) { verifyFile((LoadBalancerConfigCommand)cmd, path, filename, content); } } protected void verifyCommand(final NetworkElementCommand cmd, final String script, final String args) { - if (cmd instanceof SetPortForwardingRulesVpcCommand) { - verifyArgs((SetPortForwardingRulesVpcCommand) cmd, script, args); - } else if (cmd instanceof SetPortForwardingRulesCommand) { - verifyArgs((SetPortForwardingRulesCommand) cmd, script, args); - } else if (cmd instanceof SetStaticRouteCommand) { + if (cmd instanceof SetStaticRouteCommand) { verifyArgs((SetStaticRouteCommand) cmd, script, args); } else if (cmd instanceof SetStaticNatRulesCommand) { verifyArgs((SetStaticNatRulesCommand) cmd, script, args); @@ -175,18 +166,10 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { verifyArgs((SavePasswordCommand)cmd, script, args); } else if (cmd instanceof DhcpEntryCommand) { verifyArgs((DhcpEntryCommand)cmd, script, args); - } else if (cmd instanceof CreateIpAliasCommand) { - verifyArgs((CreateIpAliasCommand)cmd, script, args); } else if (cmd instanceof DnsMasqConfigCommand) { verifyArgs((DnsMasqConfigCommand)cmd, script, args); - } else if (cmd instanceof DeleteIpAliasCommand) { - verifyArgs((DeleteIpAliasCommand)cmd, script, args); } else if (cmd instanceof VmDataCommand) { verifyArgs((VmDataCommand)cmd, script, args); - } else if (cmd instanceof SetFirewallRulesCommand) { - verifyArgs((SetFirewallRulesCommand)cmd, script, args); - } else if (cmd instanceof BumpUpPriorityCommand) { - verifyArgs((BumpUpPriorityCommand)cmd, script, args); } else if (cmd instanceof RemoteAccessVpnCfgCommand) { verifyArgs((RemoteAccessVpnCfgCommand)cmd, script, args); } else if (cmd instanceof VpnUsersCfgCommand) { @@ -229,11 +212,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { assertTrue(answer.getResult()); } - private void verifyArgs(final BumpUpPriorityCommand cmd, final String script, final String args) { - assertEquals(script, VRScripts.RVR_BUMPUP_PRI); - assertEquals(args, null); - } - @Test public void testSetPortForwardingRulesVpcCommand() { final SetPortForwardingRulesVpcCommand cmd = generateSetPortForwardingRulesVpcCommand(); @@ -257,21 +235,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { return cmd; } - private void verifyArgs(final SetPortForwardingRulesVpcCommand cmd, final String script, final String args) { - assertTrue(script.equals(VRScripts.VPC_PORTFORWARDING)); - _count ++; - switch (_count) { - case 1: - assertEquals(args, "-A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80"); - break; - case 2: - assertEquals(args, "-D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080"); - break; - default: - fail("Failed to recongize the match!"); - } - } - @Test public void testSetPortForwardingRulesCommand() { final SetPortForwardingRulesCommand cmd = generateSetPortForwardingRulesCommand(); @@ -294,21 +257,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { return cmd; } - private void verifyArgs(final SetPortForwardingRulesCommand cmd, final String script, final String args) { - assertTrue(script.equals(VRScripts.FIREWALL_NAT)); - _count ++; - switch (_count) { - case 1: - assertEquals(args, "-A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80"); - break; - case 2: - assertEquals(args, "-D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080"); - break; - default: - fail("Failed to recongize the match!"); - } - } - @Test public void testIpAssocCommand() { final IpAssocCommand cmd = generateIpAssocCommand(); @@ -383,22 +331,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { assertEquals(VRScripts.UPDATE_CONFIG, script); assertEquals(VRScripts.IP_ASSOCIATION_CONFIG, args); break; - case 2: - assertEquals(script, VRScripts.VPC_PRIVATEGW); - assertEquals(args, " -A -l 64.1.1.10 -c eth2"); - break; - case 3: - assertEquals(script, VRScripts.VPC_IPASSOC); - assertEquals(args, " -D -l 64.1.1.11 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0"); - break; - case 4: - assertEquals(script, VRScripts.VPC_PRIVATEGW); - assertEquals(args, " -D -l 64.1.1.11 -c eth2"); - break; - case 5: - assertEquals(script, VRScripts.VPC_IPASSOC); - assertEquals(args, " -A -l 65.1.1.11 -c eth2 -g 65.1.1.1 -m 24 -n 65.1.1.0"); - break; default: fail("Failed to recongize the match!"); } @@ -676,17 +608,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { return cmd; } - private void verifyArgs(final SetFirewallRulesCommand cmd, final String script, final String args) { - assertEquals(script, VRScripts.FIREWALL_INGRESS); - - //Since the arguments are generated with a Set - //one can not make a bet on the order - assertTrue(args.startsWith(" -F -a ")); - assertTrue(args.contains("64.10.10.10:ICMP:0:0:10.10.1.1/24-10.10.1.2/24:")); - assertTrue(args.contains("64.10.10.10:reverted:0:0:0:")); - assertTrue(args.contains("64.10.10.10:TCP:22:80:10.10.1.1/24-10.10.1.2/24:")); - } - @Test public void testVmDataCommand() { final Answer answer = _resource.executeRequest(generateVmDataCommand()); @@ -804,11 +725,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { return cmd; } - private void verifyArgs(final CreateIpAliasCommand cmd, final String script, final String args) { - assertEquals(script, VRScripts.IPALIAS_CREATE); - assertEquals(args, "1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-"); - } - @Test public void testDeleteIpAliasCommand() { final Answer answer = _resource.executeRequest(generateDeleteIpAliasCommand()); @@ -825,11 +741,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { return cmd; } - private void verifyArgs(final DeleteIpAliasCommand cmd, final String script, final String args) { - assertEquals(script, VRScripts.IPALIAS_DELETE); - assertEquals(args, "1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-- 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-"); - } - @Test public void testDnsMasqConfigCommand() { final Answer answer = _resource.executeRequest(generateDnsMasqConfigCommand()); @@ -951,10 +862,6 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { assertEquals(script, VRScripts.LB); assertEquals(args, " -i 10.1.10.2 -f " + _file + " -a 64.10.1.10:80:, -s 10.1.10.2:8081:0/0:,,"); break; - case 4: - assertEquals(script, VRScripts.VPC_LB); - assertEquals(args, " -i 10.1.10.2 -f " + _file + " -a 64.10.1.10:80:, -s 10.1.10.2:8081:0/0:,,"); - break; default: fail(); } @@ -1009,122 +916,4 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer { assertTrue(args.startsWith("-c /var/cache/cloud/VR-")); assertTrue(args.endsWith(".cfg")); } - - protected void verifyFile(final AggregationControlCommand cmd, final String path, final String filename, final String content) { - assertEquals(path, "/var/cache/cloud/"); - assertTrue(filename.startsWith("VR-")); - assertTrue(filename.endsWith(".cfg")); - final Collection filteredScripts = Collections2.transform(Collections2.filter ( - Arrays.asList(content.split("")), new Predicate() { - - @Override - public boolean apply(final String str) { - return str.trim().startsWith("/opt/cloud"); - } - }), new Function() { - - @Override - public String apply(final String str) { - return str.trim(); - } - }); - final String[] scripts = filteredScripts.toArray(new String[filteredScripts - .size()]); - - assertEquals( - "/opt/cloud/bin/ipassoc.sh -A -s -f -l 64.1.1.10/24 -c eth2 -g 64.1.1.1", - scripts[0]); - - assertEquals( - "/opt/cloud/bin/ipassoc.sh -D -l 64.1.1.11/24 -c eth2 -g 64.1.1.1", - scripts[1]); - - assertEquals( - "/opt/cloud/bin/ipassoc.sh -A -l 65.1.1.11/24 -c eth2 -g 65.1.1.1", - scripts[2]); - assertEquals( - "/opt/cloud/bin/vpc_ipassoc.sh -A -l 64.1.1.10 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0", - scripts[3]); - assertEquals( - "/opt/cloud/bin/vpc_privateGateway.sh -A -l 64.1.1.10 -c eth2", - scripts[4]); - assertEquals( - "/opt/cloud/bin/vpc_ipassoc.sh -D -l 64.1.1.11 -c eth2 -g 64.1.1.1 -m 24 -n 64.1.1.0", - scripts[5]); - assertEquals( - "/opt/cloud/bin/vpc_privateGateway.sh -D -l 64.1.1.11 -c eth2", - scripts[6]); - assertEquals( - "/opt/cloud/bin/vpc_ipassoc.sh -A -l 65.1.1.11 -c eth2 -g 65.1.1.1 -m 24 -n 65.1.1.0", - scripts[7]); - //the list generated by SetFirewallCmd is actually generated through a Set - //therefore we can not bet on the order of the parameters - assertTrue( - scripts[8].matches("/opt/cloud/bin/firewall_ingress.sh -F -a .*")); - assertTrue( - scripts[8].contains("64.10.10.10:ICMP:0:0:10.10.1.1/24-10.10.1.2/24:")); - assertTrue( - scripts[8].contains("64.10.10.10:TCP:22:80:10.10.1.1/24-10.10.1.2/24:")); - assertTrue( - scripts[8].contains("64.10.10.10:reverted:0:0:0:")); - - assertEquals( - "/opt/cloud/bin/firewall_nat.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80", - scripts[9]); - assertEquals( - "/opt/cloud/bin/firewall_nat.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080", - scripts[10]); - assertEquals( - "/opt/cloud/bin/vpc_portforwarding.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80", - scripts[11]); - assertEquals( - "/opt/cloud/bin/vpc_portforwarding.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080", - scripts[12]); - assertEquals( - "/opt/cloud/bin/createIpAlias.sh 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-", - scripts[13]); - assertEquals( - "/opt/cloud/bin/deleteIpAlias.sh 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-- 1:169.254.3.10:255.255.255.0-2:169.254.3.11:255.255.255.0-3:169.254.3.12:255.255.255.0-", - scripts[14]); - assertEquals( - "/opt/cloud/bin/dnsmasq.sh 10.1.20.2:10.1.20.1:255.255.255.0:10.1.20.5-10.1.21.2:10.1.21.1:255.255.255.0:10.1.21.5-", - scripts[15]); - assertEquals( - "/opt/cloud/bin/vpn_l2tp.sh -r 10.10.1.10-10.10.1.20 -p sharedkey -s 124.10.10.10 -l 10.10.1.1 -c -C 10.1.1.1/24 -i eth2", - scripts[16]); - assertEquals( - "/opt/cloud/bin/vpn_l2tp.sh -d -s 124.10.10.10 -C 10.1.1.1/24 -i eth2", - scripts[17]); - assertEquals( - "/opt/cloud/bin/vpn_l2tp.sh -r 10.10.1.10-10.10.1.20 -p sharedkey -s 124.10.10.10 -l 10.10.1.1 -c -C 10.1.1.1/24 -i eth1", - scripts[18]); - assertEquals( - "/opt/cloud/bin/firewall_nat.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22:80", - scripts[19]); - assertEquals( - "/opt/cloud/bin/firewall_nat.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080:8080", - scripts[20]); - assertEquals( - "/opt/cloud/bin/vpc_portforwarding.sh -A -P tcp -l 64.1.1.10 -p 22:80 -r 10.10.1.10 -d 22-80", - scripts[21]); - assertEquals( - "/opt/cloud/bin/vpc_portforwarding.sh -D -P udp -l 64.1.1.11 -p 8080:8080 -r 10.10.1.11 -d 8080-8080", - scripts[22]); - assertEquals( - "/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -4 10.1.10.2 -h vm1", - scripts[23]); - assertEquals( - "/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -h vm1 -6 2001:db8:0:0:0:ff00:42:8329 -u 00:03:00:01:12:34:56:78:90:AB", - scripts[24]); - assertEquals( - "/opt/cloud/bin/edithosts.sh -m 12:34:56:78:90:AB -4 10.1.10.2 -h vm1 -6 2001:db8:0:0:0:ff00:42:8329 -u 00:03:00:01:12:34:56:78:90:AB", - scripts[25]); - assertEquals("/opt/cloud/bin/savepassword.sh -v 10.1.10.4 -p 123pass", - scripts[26]); - assertEquals( - "/opt/cloud/bin/vmdata.py -d eyIxMC4xLjEwLjQiOltbInVzZXJkYXRhIiwidXNlci1kYXRhIiwidXNlci1kYXRhIl0sWyJtZXRhZGF0YSIsInNlcnZpY2Utb2ZmZXJpbmciLCJzZXJ2aWNlT2ZmZXJpbmciXSxbIm1ldGFkYXRhIiwiYXZhaWxhYmlsaXR5LXpvbmUiLCJ6b25lTmFtZSJdLFsibWV0YWRhdGEiLCJsb2NhbC1pcHY0IiwiMTAuMS4xMC40Il0sWyJtZXRhZGF0YSIsImxvY2FsLWhvc3RuYW1lIiwidGVzdC12bSJdLFsibWV0YWRhdGEiLCJwdWJsaWMtaXB2NCIsIjExMC4xLjEwLjQiXSxbIm1ldGFkYXRhIiwicHVibGljLWhvc3RuYW1lIiwiaG9zdG5hbWUiXSxbIm1ldGFkYXRhIiwiaW5zdGFuY2UtaWQiLCJpLTQtVk0iXSxbIm1ldGFkYXRhIiwidm0taWQiLCI0Il0sWyJtZXRhZGF0YSIsInB1YmxpYy1rZXlzIiwicHVibGlja2V5Il0sWyJtZXRhZGF0YSIsImNsb3VkLWlkZW50aWZpZXIiLCJDbG91ZFN0YWNrLXt0ZXN0fSJdXX0=", - scripts[27]); - } - -} - +} \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java index 17c5708a322..5b5ec57a889 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java @@ -43,6 +43,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringEscapeUtils; import org.apache.http.HttpResponse; @@ -62,11 +63,6 @@ import org.apache.http.impl.conn.BasicClientConnectionManager; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import org.apache.cloudstack.storage.command.CopyCommand; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; @@ -133,6 +129,7 @@ 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.VirtualMachineTO; +import com.cloud.agent.resource.virtualnetwork.VRScripts; import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.dc.DataCenter.NetworkType; @@ -156,6 +153,8 @@ import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachineName; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; /** @@ -207,13 +206,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S public final StartupCommand[] initialize() { // assert if (!_configureCalled) { - String errMsg = this.getClass().getName() + " requires configure() be called before" + " initialize()"; + final String errMsg = this.getClass().getName() + " requires configure() be called before" + " initialize()"; s_logger.error(errMsg); } // Create default StartupRoutingCommand, then customise - StartupRoutingCommand defaultStartRoutCmd = - new StartupRoutingCommand(0, 0, 0, 0, null, Hypervisor.HypervisorType.Hyperv, RouterPrivateIpStrategy.HostLocal); + final StartupRoutingCommand defaultStartRoutCmd = + new StartupRoutingCommand(0, 0, 0, 0, null, Hypervisor.HypervisorType.Hyperv, RouterPrivateIpStrategy.HostLocal); // Identity within the data centre is decided by CloudStack kernel, // and passed via ServerResource.configure() @@ -234,20 +233,20 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // comes from the host itself. CloudStack sanity checks network // configuration // and uses capacity info for resource allocation. - Command[] startCmds = requestStartupCommand(new Command[] {defaultStartRoutCmd}); + final Command[] startCmds = requestStartupCommand(new Command[] {defaultStartRoutCmd}); // TODO: may throw, is this okay? - StartupRoutingCommand startCmd = (StartupRoutingCommand)startCmds[0]; + final StartupRoutingCommand startCmd = (StartupRoutingCommand)startCmds[0]; // Assert that host identity is consistent with existing values. if (startCmd == null) { - String errMsg = String.format("Host %s (IP %s)" + "did not return a StartupRoutingCommand", _name, _agentIp); + final String errMsg = String.format("Host %s (IP %s)" + "did not return a StartupRoutingCommand", _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; } if (!startCmd.getDataCenter().equals(defaultStartRoutCmd.getDataCenter())) { - String errMsg = + final String errMsg = String.format("Host %s (IP %s) changed zone/data center. Was " + defaultStartRoutCmd.getDataCenter() + " NOW its " + startCmd.getDataCenter(), _name, _agentIp); s_logger.error(errMsg); @@ -255,26 +254,26 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return null; } if (!startCmd.getPod().equals(defaultStartRoutCmd.getPod())) { - String errMsg = String.format("Host %s (IP %s) changed pod. Was " + defaultStartRoutCmd.getPod() + " NOW its " + startCmd.getPod(), _name, _agentIp); + final String errMsg = String.format("Host %s (IP %s) changed pod. Was " + defaultStartRoutCmd.getPod() + " NOW its " + startCmd.getPod(), _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; } if (!startCmd.getCluster().equals(defaultStartRoutCmd.getCluster())) { - String errMsg = + final String errMsg = String.format("Host %s (IP %s) changed cluster. Was " + defaultStartRoutCmd.getCluster() + " NOW its " + startCmd.getCluster(), _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; } if (!startCmd.getGuid().equals(defaultStartRoutCmd.getGuid())) { - String errMsg = String.format("Host %s (IP %s) changed guid. Was " + defaultStartRoutCmd.getGuid() + " NOW its " + startCmd.getGuid(), _name, _agentIp); + final String errMsg = String.format("Host %s (IP %s) changed guid. Was " + defaultStartRoutCmd.getGuid() + " NOW its " + startCmd.getGuid(), _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; } if (!startCmd.getPrivateIpAddress().equals(defaultStartRoutCmd.getPrivateIpAddress())) { - String errMsg = + final String errMsg = String.format("Host %s (IP %s) IP address. Was " + defaultStartRoutCmd.getPrivateIpAddress() + " NOW its " + startCmd.getPrivateIpAddress(), _name, _agentIp); s_logger.error(errMsg); @@ -282,7 +281,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return null; } if (!startCmd.getName().equals(defaultStartRoutCmd.getName())) { - String errMsg = String.format("Host %s (IP %s) name. Was " + startCmd.getName() + " NOW its " + defaultStartRoutCmd.getName(), _name, _agentIp); + final String errMsg = String.format("Host %s (IP %s) name. Was " + startCmd.getName() + " NOW its " + defaultStartRoutCmd.getName(), _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; @@ -301,8 +300,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S storePoolCmd = (StartupStorageCommand)startCmds[1]; // TODO: is this assertion required? if (storePoolCmd == null) { - String frmtStr = "Host %s (IP %s) sent incorrect Command, " + "second parameter should be a " + "StartupStorageCommand"; - String errMsg = String.format(frmtStr, _name, _agentIp); + final String frmtStr = "Host %s (IP %s) sent incorrect Command, " + "second parameter should be a " + "StartupStorageCommand"; + final String errMsg = String.format(frmtStr, _name, _agentIp); s_logger.error(errMsg); // TODO: valid to return null, or should we throw? return null; @@ -316,13 +315,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S @Override public final PingCommand getCurrentStatus(final long id) { - PingCommand pingCmd = new PingRoutingCommand(getType(), id, getHostVmStateReport()); + final PingCommand pingCmd = new PingRoutingCommand(getType(), id, getHostVmStateReport()); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping host " + _name + " (IP " + _agentIp + ")"); } - Answer pingAns = executeRequest(pingCmd); + final Answer pingAns = executeRequest(pingCmd); if (pingAns == null || !pingAns.getResult()) { s_logger.info("Cannot ping host " + _name + " (IP " + _agentIp + "), pingAns (blank means null) is:" + pingAns); @@ -335,12 +334,12 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S URI agentUri = null; try { agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + HOST_VM_STATE_REPORT_COMMAND, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); return null; } - String incomingCmd = postHttpRequest("{}", agentUri); + final String incomingCmd = postHttpRequest("{}", agentUri); if (incomingCmd == null) { return null; @@ -349,8 +348,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S try { result = s_gson.fromJson(incomingCmd, new TypeToken>>() { }.getType()); - } catch (Exception ex) { - String errMsg = "Failed to deserialize Command[] " + incomingCmd; + } catch (final Exception ex) { + final String errMsg = "Failed to deserialize Command[] " + incomingCmd; s_logger.error(errMsg, ex); } s_logger.debug("HostVmStateReportCommand received response " @@ -367,13 +366,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S protected HashMap getHostVmStateReport() { final HashMap vmStates = new HashMap(); - ArrayList> vmList = requestHostVmStateReport(); + final ArrayList> vmList = requestHostVmStateReport(); if (vmList == null) { return null; } - for (Map vmMap : vmList) { - String name = (String)vmMap.keySet().toArray()[0]; + for (final Map vmMap : vmList) { + final String name = (String)vmMap.keySet().toArray()[0]; vmStates.put(name, new HostVmStateReportEntry(PowerState.valueOf(vmMap.get(name)), _guid)); } return vmStates; @@ -388,17 +387,17 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html URI agentUri = null; try { - String cmdName = StartupCommand.class.getName(); + final String cmdName = StartupCommand.class.getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { // TODO add proper logging - String errMsg = "Could not generate URI for Hyper-V agent"; + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); return null; } - String incomingCmd = postHttpRequest(s_gson.toJson(cmd), agentUri); + final String incomingCmd = postHttpRequest(s_gson.toJson(cmd), agentUri); if (incomingCmd == null) { return null; @@ -406,8 +405,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S Command[] result = null; try { result = s_gson.fromJson(incomingCmd, Command[].class); - } catch (Exception ex) { - String errMsg = "Failed to deserialize Command[] " + incomingCmd; + } catch (final Exception ex) { + final String errMsg = "Failed to deserialize Command[] " + incomingCmd; s_logger.error(errMsg, ex); } s_logger.debug("requestStartupCommand received response " + s_gson.toJson(result)); @@ -424,16 +423,16 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // Using java.net.URI, see // http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html URI agentUri = null; - Class clazz = cmd.getClass(); + final Class clazz = cmd.getClass(); Answer answer = null; try { - String cmdName = cmd.getClass().getName(); + final String cmdName = cmd.getClass().getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { // TODO add proper logging - String errMsg = "Could not generate URI for Hyper-V agent"; + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); return null; } @@ -494,10 +493,10 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { if (clazz == StartCommand.class) { - VirtualMachineTO vmSpec = ((StartCommand)cmd).getVirtualMachine(); + final VirtualMachineTO vmSpec = ((StartCommand)cmd).getVirtualMachine(); if (vmSpec.getType() != VirtualMachine.Type.User) { if (s_hypervMgr != null) { - String secondary = s_hypervMgr.prepareSecondaryStorageStore(Long.parseLong(_zoneId)); + final String secondary = s_hypervMgr.prepareSecondaryStorageStore(Long.parseLong(_zoneId)); if (secondary != null) { ((StartCommand)cmd).setSecondaryStorage(secondary); } @@ -508,14 +507,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } // Send the cmd to hyperv agent. - String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); + final String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); if (ansStr == null) { return Answer.createUnsupportedCommandAnswer(cmd); } // Only Answer instances are returned by remote agents. // E.g. see Response.getAnswers() - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); - String logResult = cleanPassword(s_gson.toJson(result)); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String logResult = cleanPassword(s_gson.toJson(result)); s_logger.debug("executeRequest received response " + logResult); if (result.length > 0) { return result[0]; @@ -524,15 +523,15 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return answer; } - private Answer execute(CopyCommand cmd) { + private Answer execute(final CopyCommand cmd) { URI agentUri = null; try { - String cmdName = cmd.getClass().getName(); + final String cmdName = cmd.getClass().getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); return null; } @@ -540,13 +539,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S cleanPassword(cmd.getDestTO().getDataStore()); // Send the cmd to hyperv agent. - String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); + final String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); if (ansStr == null) { return Answer.createUnsupportedCommandAnswer(cmd); } - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); - String logResult = cleanPassword(s_gson.toJson(result)); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String logResult = cleanPassword(s_gson.toJson(result)); s_logger.debug("executeRequest received response " + logResult); if (result.length > 0) { return result[0]; @@ -555,79 +554,79 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return null; } - private void cleanPassword(DataStoreTO dataStoreTO) { + private void cleanPassword(final DataStoreTO dataStoreTO) { if (dataStoreTO instanceof NfsTO) { - NfsTO nfsTO = (NfsTO)dataStoreTO; - String url = nfsTO.getUrl(); + final NfsTO nfsTO = (NfsTO)dataStoreTO; + final String url = nfsTO.getUrl(); if (url.contains("cifs") && url.contains("password")) { nfsTO.setUrl(url.substring(0, url.indexOf('?'))); } } } - private PlugNicAnswer execute(PlugNicCommand cmd) { + private PlugNicAnswer execute(final PlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PlugNicCommand " + s_gson.toJson(cmd)); } try { - String vmName = cmd.getVmName(); - NicTO nic = cmd.getNic(); - URI broadcastUri = nic.getBroadcastUri(); + final String vmName = cmd.getVmName(); + final NicTO nic = cmd.getNic(); + final URI broadcastUri = nic.getBroadcastUri(); if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + nic.getBroadcastUri()); } - String vlanId = BroadcastDomainType.getValue(broadcastUri); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); int publicNicInfo = -1; publicNicInfo = getVmFreeNicIndex(vmName); if (publicNicInfo > 0) { modifyNicVlan(vmName, vlanId, publicNicInfo, true, cmd.getNic().getName()); return new PlugNicAnswer(cmd, true, "success"); } - String msg = " Plug Nic failed for the vm as it has reached max limit of NICs to be added"; + final String msg = " Plug Nic failed for the vm as it has reached max limit of NICs to be added"; s_logger.warn(msg); return new PlugNicAnswer(cmd, false, msg); - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Unexpected exception: ", e); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + e.toString()); } } - private UnPlugNicAnswer execute(UnPlugNicCommand cmd) { + private UnPlugNicAnswer execute(final UnPlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource UnPlugNicCommand " + s_gson.toJson(cmd)); } try { - String vmName = cmd.getVmName(); - NicTO nic = cmd.getNic(); - URI broadcastUri = nic.getBroadcastUri(); + final String vmName = cmd.getVmName(); + final NicTO nic = cmd.getNic(); + final URI broadcastUri = nic.getBroadcastUri(); if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { throw new InternalErrorException("Unable to unassign a public IP to a VIF on network " + nic.getBroadcastUri()); } - String vlanId = BroadcastDomainType.getValue(broadcastUri); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); int publicNicInfo = -1; publicNicInfo = getVmNics(vmName, vlanId); if (publicNicInfo > 0) { modifyNicVlan(vmName, "2", publicNicInfo, false, ""); } return new UnPlugNicAnswer(cmd, true, "success"); - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Unexpected exception: ", e); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + e.toString()); } } @Override - public ExecutionResult executeInVR(String routerIP, String script, String args) { + public ExecutionResult executeInVR(final String routerIP, final String script, final String args) { return executeInVR(routerIP, script, args, 120); } @Override - public ExecutionResult executeInVR(String routerIP, String script, String args, int timeout) { + public ExecutionResult executeInVR(final String routerIP, final String script, final String args, final int timeout) { Pair result; //TODO: Password should be masked, cannot output to log directly @@ -638,8 +637,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S try { result = SshHelper.sshExecute(routerIP, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/" + script + " " + args, 60000, 60000, timeout * 1000); - } catch (Exception e) { - String msg = "Command failed due to " + e ; + } catch (final Exception e) { + final String msg = "Command failed due to " + e ; s_logger.error(msg); result = new Pair(false, msg); } @@ -650,11 +649,11 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } @Override - public ExecutionResult createFileInVR(String routerIp, String filePath, String fileName, String content) { - File keyFile = getSystemVMKeyFile(); + public ExecutionResult createFileInVR(final String routerIp, final String filePath, final String fileName, final String content) { + final File keyFile = getSystemVMKeyFile(); try { SshHelper.scpTo(routerIp, 3922, "root", keyFile, null, filePath, content.getBytes(Charset.forName("UTF-8")), fileName, null); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Fail to create file " + filePath + fileName + " in VR " + routerIp, e); return new ExecutionResult(false, e.getMessage()); } @@ -662,7 +661,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } @Override - public ExecutionResult prepareCommand(NetworkElementCommand cmd) { + public ExecutionResult prepareCommand(final NetworkElementCommand cmd) { //Update IP used to access router cmd.setRouterAccessIp(getRouterSshControlIp(cmd)); assert cmd.getRouterAccessIp() != null; @@ -681,22 +680,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new ExecutionResult(true, null); } - private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) { + private ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) { try { - IpAddressTO[] ips = cmd.getIpAddresses(); - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String controlIp = getRouterSshControlIp(cmd); + final IpAddressTO[] ips = cmd.getIpAddresses(); + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + final String controlIp = getRouterSshControlIp(cmd); - for (IpAddressTO ip : ips) { + for (final IpAddressTO ip : ips) { /** * TODO support other networks */ - URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + final URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + ip.getBroadcastUri()); } - String vlanId = BroadcastDomainType.getValue(broadcastUri); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); int publicNicInfo = -1; publicNicInfo = getVmNics(routerName, vlanId); @@ -709,7 +708,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } if (addVif) { - Pair nicdevice = findRouterFreeEthDeviceIndex(controlIp); + final Pair nicdevice = findRouterFreeEthDeviceIndex(controlIp); publicNicInfo = nicdevice.first(); if (publicNicInfo > 0) { modifyNicVlan(routerName, vlanId, nicdevice.second()); @@ -720,7 +719,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { // we didn't find any eth device available in VR to configure the ip range with new VLAN - String msg = "No Nic is available on DomR VIF to associate/disassociate IP with."; + final String msg = "No Nic is available on DomR VIF to associate/disassociate IP with."; s_logger.error(msg); throw new InternalErrorException(msg); } @@ -730,29 +729,29 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S ip.setNicDevId(publicNicInfo); } } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); return new ExecutionResult(false, e.toString()); } return new ExecutionResult(true, null); } - protected ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) { - NicTO nic = cmd.getNic(); - String domrName = + protected ExecutionResult prepareNetworkElementCommand(final SetupGuestNetworkCommand cmd) { + final NicTO nic = cmd.getNic(); + final String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { - URI broadcastUri = nic.getBroadcastUri(); - String vlanId = BroadcastDomainType.getValue(broadcastUri); - int ethDeviceNum = getVmNics(domrName, vlanId); + final URI broadcastUri = nic.getBroadcastUri(); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); + final int ethDeviceNum = getVmNics(domrName, vlanId); if (ethDeviceNum > 0) { nic.setDeviceId(ethDeviceNum); } else { return new ExecutionResult(false, "Prepare SetupGuestNetwork failed due to unable to find the nic"); } - } catch (Exception e) { - String msg = "Prepare SetupGuestNetwork failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Prepare SetupGuestNetwork failed due to " + e.toString(); s_logger.warn(msg, e); return new ExecutionResult(false, msg); } @@ -760,17 +759,17 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } - private ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) { - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + private ExecutionResult prepareNetworkElementCommand(final IpAssocVpcCommand cmd) { + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { - IpAddressTO[] ips = cmd.getIpAddresses(); - for (IpAddressTO ip : ips) { - URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + final IpAddressTO[] ips = cmd.getIpAddresses(); + for (final IpAddressTO ip : ips) { + final URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { throw new InternalErrorException("Invalid Broadcast URI " + ip.getBroadcastUri()); } - String vlanId = BroadcastDomainType.getValue(broadcastUri); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); int publicNicInfo = -1; publicNicInfo = getVmNics(routerName, vlanId); if (publicNicInfo < 0) { @@ -784,7 +783,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S ip.setNicDevId(publicNicInfo); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Prepare Ip Assoc failure on applying one ip due to exception: ", e); return new ExecutionResult(false, e.toString()); } @@ -792,43 +791,43 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new ExecutionResult(true, null); } - protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) { - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - IpAddressTO pubIp = cmd.getIpAddress(); + protected ExecutionResult prepareNetworkElementCommand(final SetSourceNatCommand cmd) { + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + final IpAddressTO pubIp = cmd.getIpAddress(); try { - String broadcastUri = pubIp.getBroadcastUri(); - String vlanId = BroadcastDomainType.getValue(broadcastUri); - int ethDeviceNum = getVmNics(routerName, vlanId); + final String broadcastUri = pubIp.getBroadcastUri(); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); + final int ethDeviceNum = getVmNics(routerName, vlanId); if (ethDeviceNum > 0) { pubIp.setNicDevId(ethDeviceNum); } else { return new ExecutionResult(false, "Prepare Ip SNAT failed due to unable to find the nic"); } - } catch (Exception e) { - String msg = "Prepare Ip SNAT failure due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Prepare Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new ExecutionResult(false, e.toString()); } return new ExecutionResult(true, null); } - private ExecutionResult prepareNetworkElementCommand(SetNetworkACLCommand cmd) { - NicTO nic = cmd.getNic(); - String routerName = + private ExecutionResult prepareNetworkElementCommand(final SetNetworkACLCommand cmd) { + final NicTO nic = cmd.getNic(); + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { - URI broadcastUri = nic.getBroadcastUri(); - String vlanId = BroadcastDomainType.getValue(broadcastUri); - int ethDeviceNum = getVmNics(routerName, vlanId); + final URI broadcastUri = nic.getBroadcastUri(); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); + final int ethDeviceNum = getVmNics(routerName, vlanId); if (ethDeviceNum > 0) { nic.setDeviceId(ethDeviceNum); } else { return new ExecutionResult(false, "Prepare SetNetworkACL failed due to unable to find the nic"); } - } catch (Exception e) { - String msg = "Prepare SetNetworkACL failed due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Prepare SetNetworkACL failed due to " + e.toString(); s_logger.error(msg, e); return new ExecutionResult(false, msg); } @@ -836,13 +835,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } @Override - public ExecutionResult cleanupCommand(NetworkElementCommand cmd) { + public ExecutionResult cleanupCommand(final NetworkElementCommand cmd) { return new ExecutionResult(true, null); } protected Answer execute(final RemoteAccessVpnCfgCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - StringBuffer argsBuf = new StringBuffer(); + final String controlIp = getRouterSshControlIp(cmd); + final StringBuffer argsBuf = new StringBuffer(); if (cmd.isCreate()) { argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) .append(" -c "); @@ -854,12 +853,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S argsBuf.append(" -i ").append(cmd.getPublicInterface()); try { + final String command = String.format("%s%s %s", "/opt/cloud/bin/", VRScripts.VPN_L2TP, argsBuf.toString()); if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); + s_logger.debug("Executing " + command); } - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); @@ -871,12 +871,12 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); } - } catch (Throwable e) { + } catch (final Throwable e) { if (e instanceof RemoteException) { s_logger.warn(e.getMessage()); } - String msg = "RemoteAccessVpnCfg command failed due to " + e.getMessage(); + final String msg = "RemoteAccessVpnCfg command failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -886,9 +886,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S protected Answer execute(final VpnUsersCfgCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { - StringBuffer argsBuf = new StringBuffer(); + final String controlIp = getRouterSshControlIp(cmd); + for (final VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { + final StringBuffer argsBuf = new StringBuffer(); if (!userpwd.isAdd()) { argsBuf.append(" -U ").append(userpwd.getUsername()); } else { @@ -901,19 +901,19 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", 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) { + } catch (final Throwable e) { if (e instanceof RemoteException) { s_logger.warn(e.getMessage()); } - String msg = "VpnUserCfg command failed due to " + e.getMessage(); + final String msg = "VpnUserCfg command failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -921,34 +921,37 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new Answer(cmd); } - private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { + private SetStaticRouteAnswer execute(final SetStaticRouteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetStaticRouteCommand: " + s_gson.toJson(cmd)); } boolean endResult = true; - String controlIp = getRouterSshControlIp(cmd); + final String controlIp = getRouterSshControlIp(cmd); String args = ""; - String[] results = new String[cmd.getStaticRoutes().length]; + final String[] results = new String[cmd.getStaticRoutes().length]; 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(); + final String[] rules = cmd.generateSRouteRules(); + final StringBuilder sb = new StringBuilder(); for (int j = 0; j < rules.length; j++) { sb.append(rules[j]).append(','); } args += " -a " + sb.toString(); + final String command = String.format("%s%s %s", "/opt/cloud/bin/", VRScripts.VPC_STATIC_ROUTE, args); + // Send over the command for execution, via ssh, to the VR. try { - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticroute.sh " + args); + final Pair result = + SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args); + } if (!result.first()) { s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args); @@ -957,7 +960,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { results[i++] = null; } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + e); results[i++] = "Failed"; endResult = false; @@ -966,17 +969,20 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } - protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { + protected CheckS2SVpnConnectionsAnswer execute(final CheckS2SVpnConnectionsCommand cmd) { + final StringBuilder cmdline = new StringBuilder(); + cmdline.append("/opt/cloud/bin/"); + cmdline.append(VRScripts.S2SVPN_CHECK); + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + s_gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + cmdline.toString()); } Pair result; try { - String controlIp = getRouterSshControlIp(cmd); - StringBuilder cmdline = new StringBuilder("/opt/cloud/bin/checkbatchs2svpn.sh "); - for (String ip : cmd.getVpnIps()) { + final String controlIp = getRouterSshControlIp(cmd); + for (final String ip : cmd.getVpnIps()) { cmdline.append(" "); cmdline.append(ip); } @@ -993,20 +999,20 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S 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 " + e; + } catch (final Throwable e) { + final String msg = "CheckS2SVpnConnectionsCommand failed due to " + e; s_logger.error(msg, e); return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); } return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); } - protected Answer execute(Site2SiteVpnCfgCommand cmd) { + protected Answer execute(final Site2SiteVpnCfgCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource Site2SiteVpnCfgCommand " + s_gson.toJson(cmd)); } - String routerIp = getRouterSshControlIp(cmd); + final String routerIp = getRouterSshControlIp(cmd); String args = ""; if (cmd.isCreate()) { @@ -1049,7 +1055,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S Pair result; try { - result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipsectunnel.sh " + args); + final String command = String.format("%s%s %s", "/opt/cloud/bin/", VRScripts.S2SVPN_IPSEC, args); + result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); @@ -1060,24 +1067,24 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S 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 " + e.getMessage(); + } catch (final Throwable e) { + final String msg = "Setup site2site VPN falied due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, "Setup site2site VPN failed due to " + e.getMessage()); } return new Answer(cmd, true, result.second()); } - protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { + protected SetSourceNatAnswer execute(final SetSourceNatCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetSourceNatCommand " + s_gson.toJson(cmd)); } - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = getRouterSshControlIp(cmd); - IpAddressTO pubIp = cmd.getIpAddress(); + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + final String routerIp = getRouterSshControlIp(cmd); + final IpAddressTO pubIp = cmd.getIpAddress(); try { - int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); + final int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); String args = ""; args += " -A "; args += " -l "; @@ -1086,35 +1093,37 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += " -c "; args += "eth" + ethDeviceNum; - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_snat.sh " + args); + final String command = String.format("%s%s %s", "/opt/cloud/bin/", VRScripts.VPC_SOURCE_NAT, args); + + final Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { - String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); + final String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetSourceNatAnswer(cmd, false, msg); } return new SetSourceNatAnswer(cmd, true, "success"); - } catch (Exception e) { - String msg = "Ip SNAT failure due to " + e.toString(); + } catch (final Exception e) { + final String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new SetSourceNatAnswer(cmd, false, msg); } } - protected Answer execute(SetPortForwardingRulesCommand cmd) { + protected Answer execute(final SetPortForwardingRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesCommand: " + s_gson.toJson(cmd)); } - String controlIp = getRouterSshControlIp(cmd); + final String controlIp = getRouterSshControlIp(cmd); String args = ""; - String[] results = new String[cmd.getRules().length]; + final String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { + for (final PortForwardingRuleTO rule : cmd.getRules()) { args += rule.revoked() ? " -D " : " -A "; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); @@ -1123,10 +1132,11 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += " -d " + rule.getStringDstPortRange(); try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + } if (!result.first()) { s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); @@ -1135,7 +1145,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { results[i++] = null; } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + e.getMessage()); results[i++] = "Failed"; endResult = false; @@ -1145,17 +1155,19 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new SetPortForwardingRulesAnswer(cmd, results, endResult); } - protected Answer execute(CheckRouterCommand cmd) { + protected Answer execute(final CheckRouterCommand cmd) { + final String command = String.format("%s%s", "/opt/cloud/bin/", VRScripts.RVR_CHECK); + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckRouterCommand: " + s_gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh "); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + command); } Pair result; try { - String controlIp = getRouterSshControlIp(cmd); - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/checkrouter.sh "); + final String controlIp = getRouterSshControlIp(cmd); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); @@ -1166,15 +1178,15 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S 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 " + e.getMessage(); + } catch (final Throwable e) { + final String msg = "CheckRouterCommand failed due to " + e.getMessage(); s_logger.error(msg, e); return new CheckRouterAnswer(cmd, msg); } return new CheckRouterAnswer(cmd, result.second(), true); } - protected Answer execute(SetStaticNatRulesCommand cmd) { + protected Answer execute(final SetStaticNatRulesCommand cmd) { if (cmd.getVpcId() != null) { //return SetVPCStaticNatRules(cmd); @@ -1185,10 +1197,10 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } String args = null; - String[] results = new String[cmd.getRules().length]; + final String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { + for (final StaticNatRuleTO rule : cmd.getRules()) { // 1:1 NAT needs instanceip;publicip;domrip;op args = rule.revoked() ? " -D " : " -A "; @@ -1203,11 +1215,12 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += " -G "; try { - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + final String controlIp = getRouterSshControlIp(cmd); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + } if (!result.first()) { s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); @@ -1216,7 +1229,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { results[i++] = null; } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + e.getMessage()); results[i++] = "Failed"; endResult = false; @@ -1225,17 +1238,18 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new SetStaticNatRulesAnswer(cmd, results, endResult); } - protected Answer execute(PingTestCommand cmd) { + protected Answer execute(final PingTestCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PingTestCommand: " + s_gson.toJson(cmd)); } - String controlIp = cmd.getRouterIp(); - String args = " -c 1 -n -q " + cmd.getPrivateIp(); + final String controlIp = cmd.getRouterIp(); + final String args = " -c 1 -n -q " + cmd.getPrivateIp(); try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/bin/ping" + args); - if (result.first()) + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/bin/ping" + args); + if (result.first()) { return new Answer(cmd); - } catch (Exception e) { + } + } catch (final Exception e) { s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + e.getMessage()); } return new Answer(cmd, false, "PingTestCommand failed"); @@ -1243,13 +1257,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S protected Answer execute(final DeleteIpAliasCommand cmd) { cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); - List activeIpAliasTOs = cmd.getCreateIpAliasTos(); + final List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); + final List activeIpAliasTOs = cmd.getCreateIpAliasTos(); if (s_logger.isInfoEnabled()) { s_logger.info("Executing deleteIpAlias command: " + s_gson.toJson(cmd)); } - StringBuilder args = new StringBuilder(); - for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { + final StringBuilder args = new StringBuilder(); + for (final IpAliasTO ipAliasTO : revokedIpAliasTOs) { args.append(ipAliasTO.getAlias_count()); args.append(":"); args.append(ipAliasTO.getRouterip()); @@ -1258,7 +1272,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args.append("-"); } args.append("- "); - for (IpAliasTO ipAliasTO : activeIpAliasTOs) { + for (final IpAliasTO ipAliasTO : activeIpAliasTOs) { args.append(ipAliasTO.getAlias_count()); args.append(":"); args.append(ipAliasTO.getRouterip()); @@ -1271,8 +1285,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } try { - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/deleteIpAlias.sh " + args); + final String controlIp = getRouterSshControlIp(cmd); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/deleteIpAlias.sh " + args); if (!result.first()) { s_logger.error("deleteIpAlias command on domr " + controlIp + " failed, message: " + result.second()); @@ -1284,8 +1298,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("deleteIpAlias command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "deleteIpAlias failed due to " + e.getMessage(); + } catch (final Throwable e) { + final String msg = "deleteIpAlias failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -1299,19 +1313,19 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S //return VPCLoadBalancerConfig(cmd); } - File keyFile = getSystemVMKeyFile(); + final File keyFile = getSystemVMKeyFile(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); + final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + final String controlIp = getRouterSshControlIp(cmd); - assert (controlIp != null); + assert controlIp != null; - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); + final LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); + final String[] config = cfgtr.generateConfiguration(cmd); - String[][] rules = cfgtr.generateFwRules(cmd); - String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; - StringBuilder tmpCfgFileContents = new StringBuilder(); + final String[][] rules = cfgtr.generateFwRules(cmd); + final String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; + final StringBuilder tmpCfgFileContents = new StringBuilder(); for (int i = 0; i < config.length; i++) { tmpCfgFileContents.append(config[i]); tmpCfgFileContents.append("\n"); @@ -1322,9 +1336,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S ".cfg", null); try { - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; + final String[] addRules = rules[LoadBalancerConfigurator.ADD]; + final String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; + final String[] statRules = rules[LoadBalancerConfigurator.STATS]; String args = ""; args += "-i " + routerIp; @@ -1365,14 +1379,16 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); } + final String command = String.format("%s%s %s", "/root/", VRScripts.LB, args); + if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); + s_logger.debug("Run command on domain router " + routerIp + command); } - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { - String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); + final String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new Answer(cmd, false, msg); @@ -1386,37 +1402,34 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } return new Answer(cmd); - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + e.getMessage()); } } - protected Answer execute(SavePasswordCommand cmd) { + protected Answer execute(final SavePasswordCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } - String controlIp = getRouterSshControlIp(cmd); + final String controlIp = getRouterSshControlIp(cmd); final String password = cmd.getPassword(); final String vmIpAddress = cmd.getVmIpAddress(); // Run save_password_to_domr.sh - String args = " -v " + vmIpAddress; + final String command = String.format("%s%s %s %s %s %s", "/opt/cloud/bin/", VRScripts.PASSWORD, "-v", vmIpAddress, "-p", password); if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + controlIp + ", /opt/cloud/bin/savepassword.sh " + args + " -p " + - StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + final String debugCommand = String.format("%s%s %s %s %s %s", "/opt/cloud/bin/", VRScripts.PASSWORD, "-v", vmIpAddress, "-p", StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + s_logger.debug("Run command on domain router " + controlIp + debugCommand); } - args += " -p " + password; - try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + - args); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); @@ -1428,22 +1441,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("savepassword command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "SavePasswordCommand failed due to " + e; + } catch (final Throwable e) { + final String msg = "SavePasswordCommand failed due to " + e; s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } - protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - String[] results = new String[cmd.getRules().length]; - FirewallRuleTO[] allrules = cmd.getRules(); - FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); - String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); + protected SetFirewallRulesAnswer execute(final SetFirewallRulesCommand cmd) { + final String controlIp = getRouterSshControlIp(cmd); + final String[] results = new String[cmd.getRules().length]; + final FirewallRuleTO[] allrules = cmd.getRules(); + final FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); + final String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); - String[][] rules = cmd.generateFwRules(); + final String[][] rules = cmd.generateFwRules(); String args = ""; args += " -F "; if (trafficType == FirewallRule.TrafficType.Egress) { @@ -1457,8 +1470,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } } - StringBuilder sb = new StringBuilder(); - String[] fwRules = rules[0]; + final StringBuilder sb = new StringBuilder(); + final String[] fwRules = rules[0]; if (fwRules.length > 0) { for (int i = 0; i < fwRules.length; i++) { sb.append(fwRules[i]).append(','); @@ -1492,7 +1505,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new SetFirewallRulesAnswer(cmd, false, results); } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to ", e); //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++) { @@ -1504,23 +1517,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new SetFirewallRulesAnswer(cmd, true, results); } - protected Answer execute(VmDataCommand cmd) { + protected Answer execute(final VmDataCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource VmDataCommand: " + s_gson.toJson(cmd)); } - String controlIp = getRouterSshControlIp(cmd); - Map> data = new HashMap>(); + final String controlIp = getRouterSshControlIp(cmd); + final Map> data = new HashMap>(); data.put(cmd.getVmIpAddress(), cmd.getVmData()); String json = new Gson().toJson(data); s_logger.debug("VM data JSON IS:" + json); json = Base64.encodeBase64String(json.getBytes(Charset.forName("UTF-8"))); - - String args = "-d " + json; + final String command = String.format("%s%s %s %s", "/opt/cloud/bin/", VRScripts.VMDATA, "-d", json); try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vmdata.py " + args); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); 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()); @@ -1529,15 +1541,15 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S if (s_logger.isInfoEnabled()) { s_logger.info("vm_data command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "VmDataCommand failed due to " + e.getMessage(); + } catch (final Throwable e) { + final String msg = "VmDataCommand failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } - protected Answer execute(DhcpEntryCommand cmd) { + protected Answer execute(final DhcpEntryCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DhcpEntryCommand: " + s_gson.toJson(cmd)); } @@ -1571,13 +1583,15 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += " -N"; } + final String command = String.format("%s%s %s", "/root/", VRScripts.DHCP, args); + if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + command); } try { - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/edithosts.sh " + args); + final String controlIp = getRouterSshControlIp(cmd); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); @@ -1589,8 +1603,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "DhcpEntryCommand failed due to " + e; + } catch (final Throwable e) { + final String msg = "DhcpEntryCommand failed due to " + e; s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -1603,9 +1617,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("Executing createIpAlias command: " + s_gson.toJson(cmd)); } cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List ipAliasTOs = cmd.getIpAliasList(); - StringBuilder args = new StringBuilder(); - for (IpAliasTO ipaliasto : ipAliasTOs) { + final List ipAliasTOs = cmd.getIpAliasList(); + final StringBuilder args = new StringBuilder(); + for (final IpAliasTO ipaliasto : ipAliasTOs) { args.append(ipaliasto.getAlias_count()); args.append(":"); args.append(ipaliasto.getRouterip()); @@ -1618,8 +1632,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } try { - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/createIpAlias.sh " + args); + final String controlIp = getRouterSshControlIp(cmd); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/createIpAlias.sh " + args); if (!result.first()) { s_logger.error("CreateIpAlias command on domr " + controlIp + " failed, message: " + result.second()); @@ -1631,8 +1645,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.info("createIpAlias command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "createIpAlias failed due to " + e; + } catch (final Throwable e) { + final String msg = "createIpAlias failed due to " + e; s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -1644,14 +1658,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S if (s_logger.isInfoEnabled()) { s_logger.info("Executing dnsmasqConfig command: " + s_gson.toJson(cmd)); } - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); + final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + final String controlIp = getRouterSshControlIp(cmd); - assert (controlIp != null); + assert controlIp != null; - List dhcpTos = cmd.getIps(); - StringBuilder args = new StringBuilder(); - for (DhcpTO dhcpTo : dhcpTos) { + final List dhcpTos = cmd.getIps(); + final StringBuilder args = new StringBuilder(); + for (final DhcpTO dhcpTo : dhcpTos) { args.append(dhcpTo.getRouterIp()); args.append(":"); args.append(dhcpTo.getGateway()); @@ -1663,7 +1677,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/dnsmasq.sh " + args); + final String command = String.format("%s%s %s", "/root/", VRScripts.DHCP, args); + + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/dnsmasq.sh"); } @@ -1676,8 +1692,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S 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 " + e.getMessage(); + } catch (final Throwable e) { + final String msg = "Dnsmasqconfig command failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } @@ -1701,34 +1717,37 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // // - private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { + private int findRouterEthDeviceIndex(final String domrName, final String routerIp, final String mac) throws Exception { s_logger.info("findRouterEthDeviceIndex. mac: " + mac); // TODO : this is a temporary very inefficient solution, will refactor it later - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + final Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS // we use a waiting loop here as a workaround to synchronize activities in systems - long startTick = System.currentTimeMillis(); + final long startTick = System.currentTimeMillis(); while (System.currentTimeMillis() - startTick < 15000) { if (result.first()) { - String[] tokens = result.second().split("\\s+"); - for (String token : tokens) { + final String[] tokens = result.second().split("\\s+"); + for (final String token : tokens) { if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { - String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + final String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Run domr script " + cmd); - Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + } + final Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, // TODO need to find the dev index inside router based on IP address cmd); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); + } - if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) + if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) { return Integer.parseInt(token.substring(3)); + } } } } @@ -1740,36 +1759,39 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return -1; } - private Pair findRouterFreeEthDeviceIndex(String routerIp) throws Exception { + private Pair findRouterFreeEthDeviceIndex(final String routerIp) throws Exception { s_logger.info("findRouterFreeEthDeviceIndex. mac: "); // TODO : this is a temporary very inefficient solution, will refactor it later - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + final Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "ip address | grep DOWN| cut -f2 -d :"); // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS // we use a waiting loop here as a workaround to synchronize activities in systems - long startTick = System.currentTimeMillis(); + final long startTick = System.currentTimeMillis(); while (System.currentTimeMillis() - startTick < 15000) { if (result.first() && !result.second().isEmpty()) { - String[] tokens = result.second().split("\\n"); - for (String token : tokens) { + final String[] tokens = result.second().split("\\n"); + for (final String token : tokens) { if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { //String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); //TODO: don't check for eth0,1,2, as they will be empty by default. //String cmd = String.format("ip address show %s ", token); - String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); - if (s_logger.isDebugEnabled()) + final String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + if (s_logger.isDebugEnabled()) { s_logger.debug("Run domr script " + cmd); - Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + } + final Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, // TODO need to find the dev index inside router based on IP address cmd); - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); + } - if (result2.first() && result2.second().trim().length() > 0) + if (result2.first() && result2.second().trim().length() > 0) { return new Pair(Integer.parseInt(token.trim().substring(3)), result2.second().trim()) ; + } } } } @@ -1781,20 +1803,20 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new Pair(-1, ""); } - protected Answer execute(IpAssocCommand cmd) { + protected Answer execute(final IpAssocCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IPAssocCommand: " + s_gson.toJson(cmd)); } int i = 0; - String[] results = new String[cmd.getIpAddresses().length]; + final String[] results = new String[cmd.getIpAddresses().length]; try { - IpAddressTO[] ips = cmd.getIpAddresses(); - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String controlIp = getRouterSshControlIp(cmd); - for (IpAddressTO ip : ips) { + final IpAddressTO[] ips = cmd.getIpAddresses(); + final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + final String controlIp = getRouterSshControlIp(cmd); + for (final IpAddressTO ip : ips) { assignPublicIpAddress(routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress()); results[i++] = ip.getPublicIp() + " - success"; @@ -1803,7 +1825,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S for (; i < cmd.getIpAddresses().length; i++) { results[i++] = IpAssocAnswer.errorResult; } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); for (; i < cmd.getIpAddresses().length; i++) { @@ -1815,27 +1837,27 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } - protected int getVmFreeNicIndex(String vmName) { - GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName); + protected int getVmFreeNicIndex(final String vmName) { + final GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName); URI agentUri = null; int nicposition = -1; try { - String cmdName = GetVmConfigCommand.class.getName(); + final String cmdName = GetVmConfigCommand.class.getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); } - String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri); - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); s_logger.debug("GetVmConfigCommand response received " + s_gson.toJson(result)); if (result.length > 0) { - GetVmConfigAnswer ans = ((GetVmConfigAnswer)result[0]); - List nics = ans.getNics(); - for (NicDetails nic : nics) { + final GetVmConfigAnswer ans = (GetVmConfigAnswer)result[0]; + final List nics = ans.getNics(); + for (final NicDetails nic : nics) { if (nic.getState() == false) { nicposition = nics.indexOf(nic); break; @@ -1845,30 +1867,30 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return nicposition; } - protected int getVmNics(String vmName, String vlanid) { - GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName); + protected int getVmNics(final String vmName, String vlanid) { + final GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName); URI agentUri = null; int nicposition = -1; if(vlanid.equalsIgnoreCase("untagged")) { vlanid = "-1"; } try { - String cmdName = GetVmConfigCommand.class.getName(); + final String cmdName = GetVmConfigCommand.class.getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); } - String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri); - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); s_logger.debug("executeRequest received response " + s_gson.toJson(result)); if (result.length > 0) { - GetVmConfigAnswer ans = ((GetVmConfigAnswer)result[0]); - List nics = ans.getNics(); - for (NicDetails nic : nics) { + final GetVmConfigAnswer ans = (GetVmConfigAnswer)result[0]; + final List nics = ans.getNics(); + for (final NicDetails nic : nics) { nicposition++; if (nicposition > 1 && nic.getVlanid().equals(vlanid)) { break; @@ -1878,41 +1900,41 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return nicposition; } - protected void modifyNicVlan(String vmName, String vlanId, String macAddress) { - ModifyVmNicConfigCommand modifynic = new ModifyVmNicConfigCommand(vmName, vlanId, macAddress); + protected void modifyNicVlan(final String vmName, final String vlanId, final String macAddress) { + final ModifyVmNicConfigCommand modifynic = new ModifyVmNicConfigCommand(vmName, vlanId, macAddress); URI agentUri = null; try { - String cmdName = ModifyVmNicConfigCommand.class.getName(); + final String cmdName = ModifyVmNicConfigCommand.class.getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); } - String ansStr = postHttpRequest(s_gson.toJson(modifynic), agentUri); - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String ansStr = postHttpRequest(s_gson.toJson(modifynic), agentUri); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); s_logger.debug("executeRequest received response " + s_gson.toJson(result)); if (result.length > 0) { } } - protected void modifyNicVlan(String vmName, String vlanId, int pos, boolean enable, String switchLabelName) { - ModifyVmNicConfigCommand modifyNic = new ModifyVmNicConfigCommand(vmName, vlanId, pos, enable); + protected void modifyNicVlan(final String vmName, final String vlanId, final int pos, final boolean enable, final String switchLabelName) { + final ModifyVmNicConfigCommand modifyNic = new ModifyVmNicConfigCommand(vmName, vlanId, pos, enable); modifyNic.setSwitchLableName(switchLabelName); URI agentUri = null; try { - String cmdName = ModifyVmNicConfigCommand.class.getName(); + final String cmdName = ModifyVmNicConfigCommand.class.getName(); agentUri = new URI("https", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); - } catch (URISyntaxException e) { - String errMsg = "Could not generate URI for Hyper-V agent"; + } catch (final URISyntaxException e) { + final String errMsg = "Could not generate URI for Hyper-V agent"; s_logger.error(errMsg, e); } - String ansStr = postHttpRequest(s_gson.toJson(modifyNic), agentUri); - Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + final String ansStr = postHttpRequest(s_gson.toJson(modifyNic), agentUri); + final Answer[] result = s_gson.fromJson(ansStr, Answer[].class); s_logger.debug("executeRequest received response " + s_gson.toJson(result)); if (result.length > 0) { @@ -1922,11 +1944,11 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String broadcastId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { - URI broadcastUri = BroadcastDomainType.fromString(broadcastId); + final URI broadcastUri = BroadcastDomainType.fromString(broadcastId); if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + broadcastId); } - String vlanId = BroadcastDomainType.getValue(broadcastUri); + final String vlanId = BroadcastDomainType.getValue(broadcastUri); int publicNicInfo = -1; publicNicInfo = getVmNics(vmName, vlanId); @@ -1944,7 +1966,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } if (addVif) { - Pair nicdevice = findRouterFreeEthDeviceIndex(privateIpAddress); + final Pair nicdevice = findRouterFreeEthDeviceIndex(privateIpAddress); publicNicInfo = nicdevice.first(); if (publicNicInfo > 0) { modifyNicVlan(vmName, vlanId, nicdevice.second()); @@ -1955,7 +1977,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else { // we didn't find any eth device available in VR to configure the ip range with new VLAN - String msg = "No Nic is available on DomR VIF to associate/disassociate IP with."; + final String msg = "No Nic is available on DomR VIF to associate/disassociate IP with."; s_logger.error(msg); throw new InternalErrorException(msg); } @@ -1975,7 +1997,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S if (firstIP) { args += " -f "; } - String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); + final String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); args += " -l "; args += publicIpAddress + "/" + cidrSize; @@ -1989,12 +2011,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += " -n "; } + final String command = String.format("%s%s %s","/opt/cloud/bin/", VRScripts.IPASSOC ,args); + if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args); + s_logger.debug("Run command on domain router " + privateIpAddress + command); } - Pair result = - SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); + final Pair result = + SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); @@ -2006,16 +2030,18 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } } - protected Answer execute(GetDomRVersionCmd cmd) { + protected Answer execute(final GetDomRVersionCmd cmd) { + final String command = String.format("%s%s", "/opt/cloud/bin/", VRScripts.VERSION); + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource GetDomRVersionCmd: " + s_gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh "); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + command); } Pair result; try { - String controlIp = getRouterSshControlIp(cmd); - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/get_template_version.sh "); + final String controlIp = getRouterSshControlIp(cmd); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); @@ -2026,36 +2052,38 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S 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 " + e; + } catch (final Throwable e) { + final String msg = "GetDomRVersionCmd failed due to " + e; s_logger.error(msg, e); return new GetDomRVersionAnswer(cmd, msg); } - String[] lines = result.second().split("&"); + final String[] lines = result.second().split("&"); if (lines.length != 2) { return new GetDomRVersionAnswer(cmd, result.second()); } return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); } - private static String getRouterSshControlIp(NetworkElementCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); - String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); + private static String getRouterSshControlIp(final NetworkElementCommand cmd) { + final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + final String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); + final String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); if (routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); + } return routerGuestIp; } - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); + } return routerIp; } - protected Answer execute(NetworkUsageCommand cmd) { + protected Answer execute(final NetworkUsageCommand cmd) { if (cmd.isForVpc()) { //return VPCNetworkUsage(cmd); } @@ -2064,78 +2092,77 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } if (cmd.getOption() != null && cmd.getOption().equals("create")) { networkUsage(cmd.getPrivateIP(), "create", null); - NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "true", 0L, 0L); + final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "true", 0L, 0L); return answer; } - long[] stats = getNetworkStats(cmd.getPrivateIP()); + final long[] stats = getNetworkStats(cmd.getPrivateIP()); - NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); + final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); return answer; } - private long[] getNetworkStats(String privateIP) { - String result = networkUsage(privateIP, "get", null); - long[] stats = new long[2]; + private long[] getNetworkStats(final String privateIP) { + final String result = networkUsage(privateIP, "get", null); + final long[] stats = new long[2]; if (result != null) { try { - String[] splitResult = result.split(":"); + final String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += Long.parseLong(splitResult[i++]); stats[1] += Long.parseLong(splitResult[i++]); } - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); } } return stats; } - protected Answer execute(SetMonitorServiceCommand cmd) { + protected Answer execute(final SetMonitorServiceCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetMonitorServiceCommand: " + s_gson.toJson(cmd)); } - String controlIp = getRouterSshControlIp(cmd); - String config = cmd.getConfiguration(); + final String controlIp = getRouterSshControlIp(cmd); + final String config = cmd.getConfiguration(); + final String args = String.format(" %s %s", "-c", config); - String args = ""; - - args += " -c " + config; + final String command = String.format("%s%s %s", "/opt/cloud/bin/", VRScripts.MONITOR_SERVICE, args); try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/monitor_service.sh " + args); + final Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, command); if (!result.first()) { - String msg= "monitor_service.sh failed on domain router " + controlIp + " failed " + result.second(); + final 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) { + } catch (final Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "SetMonitorServiceCommand failed due to " + e); } } - protected CheckSshAnswer execute(CheckSshCommand cmd) { - String vmName = cmd.getName(); - String privateIp = cmd.getIp(); - int cmdPort = cmd.getPort(); + protected CheckSshAnswer execute(final CheckSshCommand cmd) { + final String vmName = cmd.getName(); + final String privateIp = cmd.getIp(); + final int cmdPort = cmd.getPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } try { - String result = connect(cmd.getName(), privateIp, cmdPort); + final String result = connect(cmd.getName(), privateIp, cmdPort); if (result != null) { s_logger.error("Can not ping System vm " + vmName + "due to:" + result); return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Can not ping System vm " + vmName + "due to exception"); return new CheckSshAnswer(cmd, e); } @@ -2175,7 +2202,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress); } - Pair result = + final Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args); if (!result.first()) { @@ -2183,7 +2210,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } return result.second(); - } catch (Throwable e) { + } catch (final Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + e); } @@ -2191,7 +2218,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } public File getSystemVMKeyFile() { - URL url = this.getClass().getClassLoader().getResource("scripts/vm/systemvm/id_rsa.cloud"); + final URL url = this.getClass().getClassLoader().getResource("scripts/vm/systemvm/id_rsa.cloud"); File keyFile = null; if (url != null) { keyFile = new File(url.getPath()); @@ -2199,7 +2226,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S if (keyFile == null || !keyFile.exists()) { keyFile = new File("/usr/share/cloudstack-common/scripts/vm/systemvm/id_rsa.cloud"); } - assert (keyFile != null); + assert keyFile != null; if (!keyFile.exists()) { s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile.toString()); } @@ -2219,27 +2246,27 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // Create request HttpClient httpClient = null; - TrustStrategy easyStrategy = new TrustStrategy() { + final TrustStrategy easyStrategy = new TrustStrategy() { @Override - public boolean isTrusted(X509Certificate[] chain, String authType) + public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; try { - SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); - SchemeRegistry registry = new SchemeRegistry(); + final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); + final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf)); - ClientConnectionManager ccm = new BasicClientConnectionManager(registry); + final ClientConnectionManager ccm = new BasicClientConnectionManager(registry); httpClient = new DefaultHttpClient(ccm); - } catch (KeyManagementException e) { + } catch (final KeyManagementException e) { s_logger.error("failed to initialize http client " + e.getMessage()); - } catch (UnrecoverableKeyException e) { + } catch (final UnrecoverableKeyException e) { s_logger.error("failed to initialize http client " + e.getMessage()); - } catch (NoSuchAlgorithmException e) { + } catch (final NoSuchAlgorithmException e) { s_logger.error("failed to initialize http client " + e.getMessage()); - } catch (KeyStoreException e) { + } catch (final KeyStoreException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } @@ -2247,39 +2274,39 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // TODO: are there timeout settings and worker thread settings to tweak? try { - HttpPost request = new HttpPost(agentUri); + final HttpPost request = new HttpPost(agentUri); // JSON encode command // Assumes command sits comfortably in a string, i.e. not used for // large data transfers - StringEntity cmdJson = new StringEntity(jsonCmd); + final StringEntity cmdJson = new StringEntity(jsonCmd); request.addHeader("content-type", "application/json"); request.setEntity(cmdJson); s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage); - HttpResponse response = httpClient.execute(request); + final HttpResponse response = httpClient.execute(request); // Unsupported commands will not route. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode(); + final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode(); s_logger.error(errMsg); - String unsupportMsg = "Unsupported command " + agentUri.getPath() + ". Are you sure you got the right type of" + " server?"; - Answer ans = new UnsupportedAnswer(null, unsupportMsg); + final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ". Are you sure you got the right type of" + " server?"; + final Answer ans = new UnsupportedAnswer(null, unsupportMsg); s_logger.error(ans); result = s_gson.toJson(new Answer[] {ans}); } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { - String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode(); + final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode(); s_logger.error(errMsg); return null; } else { result = EntityUtils.toString(response.getEntity()); - String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result)); + final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result)); s_logger.debug("POST response is " + logResult); } - } catch (ClientProtocolException protocolEx) { + } catch (final ClientProtocolException protocolEx) { // Problem with HTTP message exchange s_logger.error(protocolEx); - } catch (IOException connEx) { + } catch (final IOException connEx) { // Problem with underlying communications s_logger.error(connEx); } finally { @@ -2356,7 +2383,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } protected String connect(final String vmName, final String ipAddress, final int port) { - long startTick = System.currentTimeMillis(); + final long startTick = System.currentTimeMillis(); // wait until we have at least been waiting for _ops_timeout time or // at least have tried _retry times, this is to coordinate with system @@ -2368,10 +2395,10 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S sch.configureBlocking(true); sch.socket().setSoTimeout(5000); // we need to connect to the control ip address to check the status of the system vm - InetSocketAddress addr = new InetSocketAddress(ipAddress, port); + final InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; - } catch (IOException e) { + } catch (final IOException e) { s_logger.info("Could] not connect to " + ipAddress + " due to " + e.toString()); if (e instanceof ConnectException) { // if connection is refused because of VM is being started, @@ -2379,7 +2406,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // to avoid running out of retry quota too quickly try { Thread.sleep(5000); - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { s_logger.debug("[ignored] interupted while waiting to retry connecting to vm after exception: "+e.getLocalizedMessage()); } } @@ -2387,7 +2414,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S try { Thread.sleep(1000); - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { s_logger.debug("[ignored] interupted while connecting to vm."); } } @@ -2397,18 +2424,18 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return "Unable to connect"; } - public static String cleanPassword(String logString) { + public static String cleanPassword(final String logString) { String cleanLogString = null; if (logString != null) { cleanLogString = logString; - String[] temp = logString.split(","); + final String[] temp = logString.split(","); int i = 0; if (temp != null) { while (i < temp.length) { temp[i] = StringUtils.cleanString(temp[i]); i++; } - List stringList = new ArrayList(); + final List stringList = new ArrayList(); Collections.addAll(stringList, temp); cleanLogString = StringUtils.join(stringList, ","); } 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 11317afe5e2..6560a382052 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 @@ -85,6 +85,7 @@ 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.VirtualMachineTO; +import com.cloud.agent.resource.virtualnetwork.VRScripts; import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.dc.Vlan; @@ -614,7 +615,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv _clusterId = (String)params.get("cluster"); - _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, "update_host_passwd.sh"); + _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD); if (_updateHostPasswdPath == null) { throw new ConfigurationException("Unable to find update_host_passwd.sh"); } @@ -968,11 +969,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected void configureDiskActivityChecks(final Map params) { _diskActivityCheckEnabled = Boolean.parseBoolean((String)params.get("vm.diskactivity.checkenabled")); if (_diskActivityCheckEnabled) { - int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0); + final int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0); if (timeout > 0) { _diskActivityCheckTimeoutSeconds = timeout; } - long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L); + final long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L); if (inactiveTime > 0) { _diskActivityInactiveThresholdMilliseconds = inactiveTime; } @@ -1187,8 +1188,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv * @return */ boolean isInterface(final String fname) { - StringBuffer commonPattern = new StringBuffer(); - for (String ifNamePrefix : _ifNamePrefixes) { + final StringBuffer commonPattern = new StringBuffer(); + for (final String ifNamePrefix : _ifNamePrefixes) { commonPattern.append("|(").append(ifNamePrefix).append(".*)"); } if(fname.matches(commonPattern.toString())) { @@ -2076,7 +2077,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv s_logger.debug("Checking physical disk file at path " + volPath + " for disk activity to ensure vm is not running elsewhere"); try { HypervisorUtils.checkVolumeFileForActivity(volPath, _diskActivityCheckTimeoutSeconds, _diskActivityInactiveThresholdMilliseconds, _diskActivityCheckFileSizeMin); - } catch (IOException ex) { + } catch (final IOException ex) { throw new CloudRuntimeException("Unable to check physical disk file for activity", ex); } s_logger.debug("Disk activity check cleared"); diff --git a/systemvm/patches/debian/config/opt/cloud/bin/createIpAlias.sh b/systemvm/patches/debian/config/opt/cloud/bin/createIpAlias.sh deleted file mode 100755 index 160bc5e887b..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/createIpAlias.sh +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env bash -# 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. - -usage() { - printf " %s \n" $(basename $0) >&2 -} -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -PORTS_CONF=/etc/apache2/ports.conf -PORTS_CONF_BAK=/etc/ports.conf.bak -FAIL_DIR=/etc/failure_config -CMDLINE=$(cat /var/cache/cloud/cmdline | tr '\n' ' ') - -if [ ! -d "$FAIL_DIR" ] - then - mkdir "$FAIL_DIR" -fi -#bakup ports.conf -cp "$PORTS_CONF" "$PORTS_CONF_BAK" - -domain=$(echo "$CMDLINE" | grep -o " domain=.* " | sed -e 's/domain=//' | awk '{print $1}') - -setup_apache2() { - local ip=$1 - logger -t cloud "Setting up apache web server for $ip" - cp /etc/apache2/sites-available/default /etc/apache2/sites-available/ipAlias.${ip}.meta-data - cp /etc/apache2/sites-available/default-ssl /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data - cp /etc/apache2/ports.conf /etc/apache2/conf.d/ports.${ip}.meta-data.conf - sed -i -e "s//\nServerName $domain/" /etc/apache2/sites-available/ipAlias.${ip}.meta-data - sed -i -e "s//\nServerName $domain/" /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data - sed -i -e "/NameVirtualHost .*:80/d" /etc/apache2/conf.d/ports.${ip}.meta-data.conf - sed -i -e "s/Listen .*:80/Listen $ip:80/g" /etc/apache2/conf.d/ports.${ip}.meta-data.conf - sed -i -e "s/Listen .*:443/Listen $ip:443/g" /etc/apache2/conf.d/ports.${ip}.meta-data.conf - ln -s /etc/apache2/sites-available/ipAlias.${ip}.meta-data /etc/apache2/sites-enabled/ipAlias.${ip}.meta-data - ln -s /etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data /etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data -} - -var="$1" -cert="/root/.ssh/id_rsa.cloud" -config_ips="" -setDnsRules=0 - -while [ -n "$var" ] -do - var1=$(echo $var | cut -f1 -d "-") - alias_count=$( echo $var1 | cut -f1 -d ":" ) - routerip=$(echo $var1 | cut -f2 -d ":") - netmask=$(echo $var1 | cut -f3 -d ":") - ifconfig eth0:$alias_count $routerip netmask $netmask up - setup_apache2 "$routerip" - config_ips="${config_ips}"$routerip":" - var=$( echo $var | sed "s/${var1}-//" ) - setDnsRules=1 -done - -#restarting the apache server for the config to take effect. -service apache2 restart -result=$? -if [ "$result" -ne "0" ] -then - logger -t cloud "createIpAlias.sh: could not configure apache2 server" - logger -t cloud "createIpAlias.sh: reverting to the old config" - logger -t cloud "createIpAlias.sh: moving out the failure config to $FAIL_DIR" - while [ -n "$config_ips" ] - do - ip=$( echo $config_ips | cut -f1 -d ":" ) - mv "/etc/apache2/sites-available/ipAlias.${ip}.meta-data" "$FAIL_DIR/ipAlias.${ip}.meta-data" - mv "/etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data" "$FAIL_DIR/ipAlias.${ip}-ssl.meta-data" - mv "/etc/apache2/conf.d/ports.${ip}.meta-data.conf" "$FAIL_DIR/ports.${ip}.meta-data.conf" - rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}.meta-data" - rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data" - config_ips=$( echo $config_ips | sed "s/${ip}://" ) - done - service apache2 restart - unlock_exit $result $lock $locked -fi - -if [ "$setDnsRules" -eq 1 ] -then - //check wether chain exist - iptables-save -t filter | grep 'dnsIpAlias_allow' - - if [ $? -eq 0 ] - then - iptables -F dnsIpAlias_allow - else - //if not exist create it - iptables -N dnsIpAlias_allow - iptables -A INPUT -i eth0 -p tcp --dport 53 -j dnsIpAlias_allow - iptables -A INPUT -i eth0 -p udp --dport 53 -j dnsIpAlias_allow - fi - - for cidr in $(ip addr | grep eth0 | grep inet | awk '{print $2}'); - do - iptables -A dnsIpAlias_allow -i eth0 -p tcp --dport 53 -s $cidr -j ACCEPT - iptables -A dnsIpAlias_allow -i eth0 -p udp --dport 53 -s $cidr -j ACCEPT - done -else - iptables -D INPUT -i eth0 -p tcp --dport 53 -j dnsIpAlias_allow - iptables -D INPUT -i eth0 -p udp --dport 53 -j dnsIpAlias_allow - iptables -X dnsIpAlias_allow -fi - - -#restaring the password service to enable it on the ip aliases -/etc/init.d/cloud-passwd-srvr restart -unlock_exit $? $lock $locked \ No newline at end of file diff --git a/systemvm/patches/debian/config/opt/cloud/bin/deleteIpAlias.sh b/systemvm/patches/debian/config/opt/cloud/bin/deleteIpAlias.sh deleted file mode 100755 index 5c07028532d..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/deleteIpAlias.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env bash -# 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. - -usage() { - printf " %s \n" $(basename $0) >&2 -} - -source /root/func.sh -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -remove_apache_config() { -local ip=$1 - logger -t cloud "removing apache web server config for $ip" - rm -f "/etc/apache2/sites-available/ipAlias.${ip}.meta-data" - rm -f "/etc/apache2/sites-available/ipAlias.${ip}-ssl.meta-data" - rm -f "/etc/apache2/conf.d/ports.${ip}.meta-data.conf" - rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}-ssl.meta-data" - rm -f "/etc/apache2/sites-enabled/ipAlias.${ip}.meta-data" -} - -var="$1" -cert="/root/.ssh/id_rsa.cloud" - -while [[ !( "$var" == "-" ) ]] -do - var1=$(echo $var | cut -f1 -d "-") - alias_count=$( echo $var1 | cut -f1 -d ":" ) - routerip=$( echo $var1 | cut -f2 -d ":" ) - ifconfig eth0:$alias_count down - remove_apache_config "$routerip" - var=$( echo $var | sed "s/${var1}-//" ) -done -#restarting the apache server for the config to take effect. -service apache2 restart - -releaseLockFile $lock $locked - -iptables -F dnsIpAlias_allow - -#recreating the active ip aliases -/opt/cloud/bin/createIpAlias.sh $2 -unlock_exit $? $lock $locked \ No newline at end of file diff --git a/systemvm/patches/debian/config/opt/cloud/bin/firewall_egress.sh b/systemvm/patches/debian/config/opt/cloud/bin/firewall_egress.sh deleted file mode 100755 index 6eb0531c5bb..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/firewall_egress.sh +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env bash -# 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. -# $Id: firewallRule_egress.sh 9947 2013-01-17 19:34:24Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/patches/xenserver/root/firewallRule_egress.sh $ -# firewallRule_egress.sh -- allow some ports / protocols from vm instances -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi -#set -x -usage() { - printf "Usage: %s: -a protocol:startport:endport:sourcecidrs> \n" $(basename $0) >&2 - printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n" -} - -fw_egress_remove_backup() { - # remove backup rules, ignore errors as they could not be present - sudo iptables -D FW_OUTBOUND -j _FW_EGRESS_RULES >/dev/null 2>&1 - sudo iptables -F _FW_EGRESS_RULES >/dev/null 2>&1 - sudo iptables -X _FW_EGRESS_RULES >/dev/null 2>&1 -} - -fw_egress_save() { - sudo iptables -E FW_EGRESS_RULES _FW_EGRESS_RULES -} - -fw_egress_chain () { -#supress errors 2>/dev/null - fw_egress_remove_backup - fw_egress_save - sudo iptables -N FW_EGRESS_RULES - sudo iptables -A FW_OUTBOUND -j FW_EGRESS_RULES -} - -fw_egress_backup_restore() { - sudo iptables -A FW_OUTBOUND -j FW_EGRESS_RULES - sudo iptables -E _FW_EGRESS_RULES FW_EGRESS_RULES - fw_egress_remove_backup -} - - -fw_entry_for_egress() { - local rule=$1 - - local prot=$(echo $rule | cut -d: -f2) - local sport=$(echo $rule | cut -d: -f3) - local eport=$(echo $rule | cut -d: -f4) - local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g') - if [ "$sport" == "0" -a "$eport" == "0" ] - then - DPORT="" - else - DPORT="--dport $sport:$eport" - fi - logger -t cloud "$(basename $0): enter apply fw egress rules for guest $prot:$sport:$eport:$cidrs" - - for lcidr in $cidrs - do - [ "$prot" == "reverted" ] && continue; - if [ "$prot" == "icmp" ] - then - typecode="$sport/$eport" - [ "$eport" == "-1" ] && typecode="$sport" - [ "$sport" == "-1" ] && typecode="any" - sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr --icmp-type $typecode \ - -j $target - result=$? - elif [ "$prot" == "all" ] - then - sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr -j $target - result=$? - else - sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr $DPORT -j $target - result=$? - fi - - [ $result -gt 0 ] && - logger -t cloud "Error adding iptables entry for guest network $prot:$sport:$eport:$cidrs" && - break - done - - logger -t cloud "$(basename $0): exit apply egress firewall rules for guest network" - return $result -} - - -aflag=0 -rules="" -rules_list="" -ip="" -dev="" -pflag=0 -shift -shift -while getopts 'a:P:' OPTION -do - case $OPTION in - a) aflag=1 - rules="$OPTARG" - ;; - P) pflag=1 - pvalue="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -if [ "$aflag" != "1" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ -n "$rules" ] -then - rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ") -fi - -# rule format -# protocal:sport:eport:cidr -#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32 -# if any entry is reverted , entry will be in the format reverted:0:0:0 -# example : tcp:80:80:0.0.0.0/0:, tcp:220:220:0.0.0.0/0:,200.1.1.2:reverted:0:0:0 - -success=0 - -if [ "$pvalue" == "1" -o "$pvalue" == "2" ] - then - target="DROP" - else - target="ACCEPT" - fi - -fw_egress_chain -for r in $rules_list -do - fw_entry_for_egress $r - success=$? - if [ $success -gt 0 ] - then - logger -t cloud "failure to apply fw egress rules " - break - else - logger -t cloud "successful in applying fw egress rules" - fi -done - -if [ $success -gt 0 ] -then - logger -t cloud "restoring from backup for guest network" - fw_egress_backup_restore -else - logger -t cloud "deleting backup for guest network" - if [ "$pvalue" == "1" ] - then - #Adding default policy rule - sudo iptables -A FW_EGRESS_RULES -j ACCEPT - fi - -fi - -fw_egress_remove_backup - -unlock_exit $success $lock $locked - - diff --git a/systemvm/patches/debian/config/opt/cloud/bin/firewall_ingress.sh b/systemvm/patches/debian/config/opt/cloud/bin/firewall_ingress.sh deleted file mode 100755 index 9e459f02ea9..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/firewall_ingress.sh +++ /dev/null @@ -1,202 +0,0 @@ -#!/usr/bin/env bash -# 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. -# firewall_rule.sh -- allow some ports / protocols to vm instances -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: -a \n" $(basename $0) >&2 - printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n" -} -#set -x -#FIXME: eating up the error code during execution of iptables -fw_remove_backup() { - local pubIp=$1 - sudo iptables -t mangle -F _FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -D PREROUTING -d $pubIp -j _FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -X _FIREWALL_$pubIp 2> /dev/null -} - -fw_restore() { - local pubIp=$1 - sudo iptables -t mangle -F FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -D PREROUTING -d $pubIp -j FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -X FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -E _FIREWALL_$pubIp FIREWALL_$pubIp 2> /dev/null -} - -fw_chain_for_ip () { - local pubIp=$1 - fw_remove_backup $1 - sudo iptables -t mangle -E FIREWALL_$pubIp _FIREWALL_$pubIp 2> /dev/null - sudo iptables -t mangle -N FIREWALL_$pubIp 2> /dev/null - # drop if no rules match (this will be the last rule in the chain) - sudo iptables -t mangle -A FIREWALL_$pubIp -j DROP> /dev/null - # ensure outgoing connections are maintained (first rule in chain) - sudo iptables -t mangle -I FIREWALL_$pubIp -m state --state RELATED,ESTABLISHED -j ACCEPT> /dev/null - #ensure that this table is after VPN chain - sudo iptables -t mangle -I PREROUTING 2 -d $pubIp -j FIREWALL_$pubIp - success=$? - if [ $success -gt 0 ] - then - # if VPN chain is not present for various reasons, try to add in to the first slot */ - sudo iptables -t mangle -I PREROUTING -d $pubIp -j FIREWALL_$pubIp - fi -} - -fw_entry_for_public_ip() { - local rules=$1 - - local pubIp=$(echo $rules | cut -d: -f1) - local prot=$(echo $rules | cut -d: -f2) - local sport=$(echo $rules | cut -d: -f3) - local eport=$(echo $rules | cut -d: -f4) - local scidrs=$(echo $rules | cut -d: -f5 | sed 's/-/ /g') - - logger -t cloud "$(basename $0): enter apply firewall rules for public ip $pubIp:$prot:$sport:$eport:$scidrs" - - - # note that rules are inserted after the RELATED,ESTABLISHED rule - # but before the DROP rule - for src in $scidrs - do - [ "$prot" == "reverted" ] && continue; - if [ "$prot" == "icmp" ] - then - typecode="$sport/$eport" - [ "$eport" == "-1" ] && typecode="$sport" - [ "$sport" == "-1" ] && typecode="any" - sudo iptables -t mangle -I FIREWALL_$pubIp 2 -s $src -p $prot \ - --icmp-type $typecode -j RETURN - else - sudo iptables -t mangle -I FIREWALL_$pubIp 2 -s $src -p $prot \ - --dport $sport:$eport -j RETURN - fi - result=$? - [ $result -gt 0 ] && - logger -t cloud "Error adding iptables entry for $pubIp:$prot:$sport:$eport:$src" && - break - done - - logger -t cloud "$(basename $0): exit apply firewall rules for public ip $pubIp" - return $result -} - -get_vif_list() { - local vif_list="" - for i in /sys/class/net/eth*; do - vif=$(basename $i); - if [ "$vif" != "eth0" ] && [ "$vif" != "eth1" ] - then - vif_list="$vif_list $vif"; - fi - done - if [ "$vif_list" == "" ] - then - vif_list="eth0" - fi - - logger -t cloud "FirewallRule public interfaces = $vif_list" - echo $vif_list -} - -shift -rules= -while getopts 'a:' OPTION -do - case $OPTION in - a) aflag=1 - rules="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -VIF_LIST=$(get_vif_list) - -if [ "$rules" == "" ] -then - rules="none" -fi - -#-a 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32 -# if any entry is reverted , entry will be in the format :reverted:0:0:0 -# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:,200.1.1.2:reverted:0:0:0 -# The reverted entries will fix the following partially -#FIXME: rule leak: when there are multiple ip address, there will chance that entry will be left over if the ipadress does not appear in the current execution when compare to old one -# example : In the below first transaction have 2 ip's whereas in second transaction it having one ip, so after the second trasaction 200.1.2.3 ip will have rules in mangle table. -# 1) -a 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:, -# 2) -a 172.16.92.44:tcp:80:80:0.0.0.0/0:,172.16.92.44:tcp:220:220:0.0.0.0/0:, - - -success=0 -publicIps= -rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ") -for r in $rules_list -do - pubIp=$(echo $r | cut -d: -f1) - publicIps="$pubIp $publicIps" -done - -unique_ips=$(echo $publicIps| tr " " "\n" | sort | uniq | tr "\n" " ") - -for u in $unique_ips -do - fw_chain_for_ip $u -done - -for r in $rules_list -do - pubIp=$(echo $r | cut -d: -f1) - fw_entry_for_public_ip $r - success=$? - if [ $success -gt 0 ] - then - logger -t cloud "$(basename $0): failure to apply fw rules for ip $pubIp" - break - else - logger -t cloud "$(basename $0): successful in applying fw rules for ip $pubIp" - fi -done - -if [ $success -gt 0 ] -then - for p in $unique_ips - do - logger -t cloud "$(basename $0): restoring from backup for ip: $p" - fw_restore $p - done -fi -for p in $unique_ips -do - logger -t cloud "$(basename $0): deleting backup for ip: $p" - fw_remove_backup $p -done - -unlock_exit $success $lock $locked - diff --git a/systemvm/patches/debian/config/opt/cloud/bin/firewall_nat.sh b/systemvm/patches/debian/config/opt/cloud/bin/firewall_nat.sh deleted file mode 100755 index 8c0e0fc526a..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/firewall_nat.sh +++ /dev/null @@ -1,358 +0,0 @@ -#!/usr/bin/env bash -# 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. -# $Id: firewall.sh 9947 2010-06-25 19:34:24Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/patches/xenserver/root/firewall.sh $ -# firewall.sh -- allow some ports / protocols to vm instances -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -vpnoutmark="0x525" - -usage() { - printf "Usage: %s: (-A|-D) -r -P protocol (-p port_range | -t icmp_type_code) -l -d -s [-G] \n" $(basename $0) >&2 -} - -#set -x - -get_dev_list() { - ip link show | grep -e eth[2-9] | awk -F ":" '{print $2}' - ip link show | grep -e eth1[0-9] | awk -F ":" '{print $2}' -} - -ip_to_dev() { - local ip=$1 - - for dev in $DEV_LIST; do - ip addr show dev $dev | grep inet | grep $ip &>> /dev/null - [ $? -eq 0 ] && echo $dev && return 0 - done - return 1 -} - -doHairpinNat () { - local vrGuestIPNetwork=$(sudo ip addr show dev eth0 | grep inet | grep eth0 | awk '{print $2}' | head -1) - local vrGuestIP=$(echo $vrGuestIPNetwork | awk -F'/' '{print $1}') - - local publicIp=$1 - local prot=$2 - local port=$3 - local guestVmIp=$4 - local guestPort=$(echo $5 | sed 's/:/-/') - local op=$6 - local destPort=$5 - logger -t cloud "$(basename $0): create HairPin entry : public ip=$publicIp \ - instance ip=$guestVmIp proto=$proto portRange=$guestPort op=$op" - - if [ "$prot" == "all" ] - then - logger -t cloud "creating hairpin nat rules for static nat" - (sudo iptables -t nat $op PREROUTING -d $publicIp -i eth0 -j DNAT --to-destination $guestVmIp &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t nat $op POSTROUTING -s $vrGuestIPNetwork -d $guestVmIp -j SNAT -o eth0 --to-source $vrGuestIP &>> $OUTFILE || [ "$op" == "-D" ]) - else - (sudo iptables -t nat $op PREROUTING -d $publicIp -i eth0 -p $prot --dport $port -j DNAT --to-destination $guestVmIp:$guestPort &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t nat $op POSTROUTING -s $vrGuestIPNetwork -p $prot --dport $destPort -d $guestVmIp -j SNAT -o eth0 --to-source $vrGuestIP &>> $OUTFILE || [ "$op" == "-D" ]) - fi -} - -#Port (address translation) forwarding for tcp or udp -tcp_or_udp_entry() { - local instIp=$1 - local dport0=$2 - local dport=$(echo $2 | sed 's/:/-/') - local publicIp=$3 - local port=$4 - local op=$5 - local proto=$6 - local cidrs=$7 - - logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \ - instance ip=$instIp proto=$proto port=$port dport=$dport op=$op" - - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && tcp_or_udp_entry $instIp $dport0 $publicIp $port "-D" $proto $cidrs - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - local dev=$(ip_to_dev $publicIp) - local tableNo=$(echo $dev | awk -F'eth' '{print $2}') - # shortcircuit the process if error and it is an append operation - # continue if it is delete - (sudo iptables -t nat $op PREROUTING --proto $proto -i $dev -d $publicIp \ - --destination-port $port -j DNAT \ - --to-destination $instIp:$dport &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t mangle $op PREROUTING --proto $proto -i $dev -d $publicIp \ - --destination-port $port -j MARK --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t mangle $op PREROUTING --proto $proto -i $dev -d $publicIp \ - --destination-port $port -m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) && - (doHairpinNat $publicIp $proto $port $instIp $dport0 $op) && - (sudo iptables -t nat $op OUTPUT --proto $proto -d $publicIp \ - --destination-port $port -j DNAT \ - --to-destination $instIp:$dport &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables $op FORWARD -p $proto -s $cidrs -d $instIp -m state \ - --state ESTABLISHED,RELATED -m comment --comment "$publicIp:$port" -j ACCEPT &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables $op FORWARD -p $proto -s $cidrs -d $instIp \ - --destination-port $dport0 -m state --state NEW -m comment --comment "$publicIp:$port" -j ACCEPT &>> $OUTFILE) - - - local result=$? - logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result" - return $result -} - - -#Forward icmp -icmp_entry() { - local instIp=$1 - local icmptype=$2 - local publicIp=$3 - local op=$4 - - logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \ - instance ip=$instIp proto=icmp port=$port dport=$dport op=$op" - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && icmp_entry $instIp $icmpType $publicIp "-D" - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - local dev=$(ip_to_dev $publicIp) - sudo iptables -t nat $op PREROUTING --proto icmp -i $dev -d $publicIp --icmp-type $icmptype -j DNAT --to-destination $instIp &>> $OUTFILE - - sudo iptables -t nat $op OUTPUT --proto icmp -d $publicIp --icmp-type $icmptype -j DNAT --to-destination $instIp &>> $OUTFILE - sudo iptables $op FORWARD -p icmp -s 0/0 -d $instIp --icmp-type $icmptype -j ACCEPT &>> $OUTFILE - - result=$? - logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result" - return $result -} - - - -one_to_one_fw_entry() { - local publicIp=$1 - local instIp=$2 - local proto=$3 - local portRange=$4 - local op=$5 - logger -t cloud "$(basename $0): create firewall entry for static nat: public ip=$publicIp \ - instance ip=$instIp proto=$proto portRange=$portRange op=$op" - - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && one_to_one_fw_entry $publicIp $instIp $proto $portRange "-D" - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - - local dev=$(ip_to_dev $publicIp) - [ $? -ne 0 ] && echo "Could not find device associated with $publicIp" && return 1 - - # shortcircuit the process if error and it is an append operation - # continue if it is delete - (sudo iptables -t nat $op PREROUTING -i $dev -d $publicIp --proto $proto \ - --destination-port $portRange -j DNAT \ - --to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) && - (doHairpinNat $publicIp $proto $portRange $instIp $portRange $op) && - (sudo iptables $op FORWARD -i $dev -o eth0 -d $instIp --proto $proto \ - --destination-port $portRange -m state \ - --state NEW -j ACCEPT &>> $OUTFILE ) - - result=$? - logger -t cloud "$(basename $0): done firewall entry public ip=$publicIp op=$op result=$result" - return $result -} - -fw_chain_for_ip() { - local pubIp=$1 - if iptables -t mangle -N FIREWALL_$pubIp &> /dev/null - then - logger -t cloud "$(basename $0): created a firewall chain for $pubIp" - (sudo iptables -t mangle -A FIREWALL_$pubIp -j DROP) && - (sudo iptables -t mangle -I FIREWALL_$pubIp -m state --state RELATED,ESTABLISHED -j ACCEPT ) && - (sudo iptables -t mangle -I PREROUTING 2 -d $pubIp -j FIREWALL_$pubIp) - return $? - fi - logger -t cloud "fw chain for $pubIp already exists" - return 0 -} - -static_nat() { - local publicIp=$1 - local instIp=$2 - local op=$3 - local op2="-D" - local rulenum= - local proto="all" - - logger -t cloud "$(basename $0): static nat: public ip=$publicIp \ - instance ip=$instIp op=$op" - - #TODO check error below - fw_chain_for_ip $publicIp - - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && static_nat $publicIp $instIp "-D" - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - [ "$op" == "-A" ] && op2="-I" - if [ "$op" == "-A" ] - then - # put static nat rule one rule after VPN no-NAT rule - # rule chain can be used to improve it later - iptables-save -t nat|grep "POSTROUTING" | grep $vpnoutmark > /dev/null - if [ $? -eq 0 ] - then - rulenum=2 - else - rulenum=1 - fi - fi - - local dev=$(ip_to_dev $publicIp) - [ $? -ne 0 ] && echo "Could not find device associated with $publicIp" && return 1 - local tableNo=$(echo $dev | awk -F'eth' '{print $2}') - - # shortcircuit the process if error and it is an append operation - # continue if it is delete - (sudo iptables -t mangle $op PREROUTING -i $dev -d $publicIp \ - -j MARK -m state --state NEW --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t mangle $op PREROUTING -i $dev -d $publicIp \ - -m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t mangle $op PREROUTING -s $instIp -i eth0 \ - -j MARK -m state --state NEW --set-mark $tableNo &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t mangle $op PREROUTING -s $instIp -i eth0 \ - -m state --state NEW -j CONNMARK --save-mark &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t nat $op PREROUTING -i $dev -d $publicIp -j DNAT \ - --to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables $op FORWARD -i $dev -o eth0 -d $instIp -m state \ - --state NEW -j ACCEPT &>> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t nat $op2 POSTROUTING $rulenum -s $instIp -j SNAT \ - -o $dev --to-source $publicIp &>> $OUTFILE || [ "$op" == "-D" ]) && - (doHairpinNat $publicIp $proto "all" $instIp "0:65535" $op) - - result=$? - logger -t cloud "$(basename $0): done static nat entry public ip=$publicIp op=$op result=$result" - return $result -} - - - -rflag= -Pflag= -pflag= -tflag= -lflag= -dflag= -sflag= -Gflag= -op="" - -while getopts 'ADr:P:p:t:l:d:s:G' OPTION -do - case $OPTION in - A) op="-A" - ;; - D) op="-D" - ;; - r) rflag=1 - instanceIp="$OPTARG" - ;; - P) Pflag=1 - protocol="$OPTARG" - ;; - p) pflag=1 - ports="$OPTARG" - ;; - t) tflag=1 - icmptype="$OPTARG" - ;; - l) lflag=1 - publicIp="$OPTARG" - ;; - s) sflag=1 - cidrs="$OPTARG" - ;; - d) dflag=1 - dport="$OPTARG" - ;; - G) Gflag=1 - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -DEV_LIST=$(get_dev_list) -OUTFILE=$(mktemp) - -#Firewall ports for one-to-one/static NAT -if [ "$Gflag" == "1" ] -then - if [ "$protocol" == "" ] - then - static_nat $publicIp $instanceIp $op - else - one_to_one_fw_entry $publicIp $instanceIp $protocol $dport $op - fi - result=$? - if [ "$result" -ne 0 ] && [ "$op" != "-D" ]; then - cat $OUTFILE >&2 - fi - rm -f $OUTFILE - if [ "$op" == "-D" ];then - result=0 - fi - unlock_exit $result $lock $locked -fi - -if [ "$sflag" != "1" ] -then - cidrs="0/0" -fi - -case $protocol in - tcp|udp) - tcp_or_udp_entry $instanceIp $dport $publicIp $ports $op $protocol $cidrs - result=$? - if [ "$result" -ne 0 ] && [ "$op" != "-D" ];then - cat $OUTFILE >&2 - fi - rm -f $OUTFILE - if [ "$op" == "-D" ];then - result=0 - fi - unlock_exit $result $lock $locked - ;; - "icmp") - - icmp_entry $instanceIp $icmptype $publicIp $op - if [ "$op" == "-D" ];then - result=0 - fi - unlock_exit $? $lock $locked - ;; - *) - printf "Invalid protocol-- must be tcp, udp or icmp\n" >&2 - unlock_exit 5 $lock $locked - ;; -esac - -unlock_exit 0 $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/getRouterAlerts.sh b/systemvm/patches/debian/config/opt/cloud/bin/getRouterAlerts.sh deleted file mode 100644 index 3f5f4a3b05c..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/getRouterAlerts.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -# 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. - -# getRouterAlerts.sh --- Send the alerts from routerServiceMonitor.log to Management Server - -#set -x - -filename=/var/log/routerServiceMonitor.log #Monitor service log file -if [ -n "$1" -a -n "$2" ] -then - reqDateVal=$(date -d "$1 $2" "+%s"); -else - reqDateVal=0 -fi -if [ -f $filename ] -then - while read line - do - if [ -n "$line" ] - then - dateval=`echo $line |awk '{print $1, $2}'` - IFS=',' read -a array <<< "$dateval" - dateval=${array[0]} - - toDateVal=$(date -d "$dateval" "+%s") - - if [ "$toDateVal" -gt "$reqDateVal" ] - then - alerts="$line\n$alerts" - else - break - fi - fi - done < <(tac $filename) -fi -if [ -n "$alerts" ]; then - echo $alerts -else - echo "No Alerts" -fi \ No newline at end of file diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_acl.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_acl.sh deleted file mode 100755 index 0a791c6c290..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_acl.sh +++ /dev/null @@ -1,250 +0,0 @@ -#!/usr/bin/env bash -# 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. -# firewall_rule.sh -- allow some ports / protocols to vm instances -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: -a \n" $(basename $0) >&2 - printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n" -} -#set -x -#FIXME: eating up the error code during execution of iptables - -acl_switch_to_new() { - sudo iptables -D FORWARD -o $dev -d $gcidr -j _ACL_INBOUND_$dev 2>/dev/null - sudo iptables-save | grep "\-j _ACL_INBOUND_$dev" | grep "\-A" | while read rule; - do - rule1=$(echo $rule | sed 's/\_ACL_INBOUND/ACL_INBOUND/') - sudo iptables $rule1 - rule2=$(echo $rule | sed 's/\-A/\-D/') - sudo iptables $rule2 - done - sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_remove_backup() { - sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -D FORWARD -o $dev -d $gcidr -j _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_remove() { - sudo iptables -F ACL_INBOUND_$dev 2>/dev/null - sudo iptables -D FORWARD -o $dev -d $gcidr -j ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_restore() { - acl_remove - sudo iptables -E _ACL_INBOUND_$dev ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -E _ACL_OUTBOUND_$dev ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_save() { - acl_remove_backup - sudo iptables -E ACL_INBOUND_$dev _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -E ACL_OUTBOUND_$dev _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_chain_for_guest_network () { - acl_save - # inbound - sudo iptables -N ACL_INBOUND_$dev 2>/dev/null - # drop if no rules match (this will be the last rule in the chain) - sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null - sudo iptables -A FORWARD -o $dev -d $gcidr -j ACL_INBOUND_$dev 2>/dev/null - # outbound - sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -s $gcidr ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null -} - - - -acl_entry_for_guest_network() { - local rule=$1 - - local ttype=$(echo $rule | cut -d: -f1) - local prot=$(echo $rule | cut -d: -f2) - local sport=$(echo $rule | cut -d: -f3) - local eport=$(echo $rule | cut -d: -f4) - local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g') - local action=$(echo $rule | cut -d: -f6) - if [ "$sport" == "0" -a "$eport" == "0" ] - then - DPORT="" - else - DPORT="--dport $sport:$eport" - fi - logger -t cloud "$(basename $0): enter apply acl rules for guest network: $gcidr, inbound:$inbound:$prot:$sport:$eport:$cidrs" - - # note that rules are inserted after the RELATED,ESTABLISHED rule - # but before the DROP rule - for lcidr in $cidrs - do - [ "$prot" == "reverted" ] && continue; - if [ "$prot" == "icmp" ] - then - typecode="$sport/$eport" - [ "$eport" == "-1" ] && typecode="$sport" - [ "$sport" == "-1" ] && typecode="any" - if [ "$ttype" == "Ingress" ] - then - sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \ - --icmp-type $typecode -j $action - else - let egress++ - sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \ - --icmp-type $typecode -j $action - fi - else - if [ "$ttype" == "Ingress" ] - then - sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \ - $DPORT -j $action - else - let egress++ - sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \ - $DPORT -j $action - fi - fi - result=$? - [ $result -gt 0 ] && - logger -t cloud "Error adding iptables entry for guest network : $gcidr,inbound:$inbound:$prot:$sport:$eport:$cidrs" && - break - done - - logger -t cloud "$(basename $0): exit apply acl rules for guest network : $gcidr" - return $result -} - - -dflag=0 -gflag=0 -aflag=0 -Mflag=0 -rules="" -rules_list="" -ip="" -dev="" -mac="" -while getopts 'd:i:m:M:a:' OPTION -do - case $OPTION in - d) dflag=1 - dev="$OPTARG" - ;; - i) iflag=1 - ip="$OPTARG" - ;; - m) mflag=1 - mask="$OPTARG" - ;; - M) Mflag=1 - mac="$OPTARG" - ;; - a) aflag=1 - rules="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -if [ "$dflag$iflag$mflag$aflag" != "1111" ] -then - usage - unlock_exit 2 $lock $locked -fi - -# override dev with mac address match, if provided -if [[ ! -z "$mac" ]]; then - logger -t cloud "$(basename $0): mac $mac passed, trying to match to device" - for i in `ls /sys/class/net`; do - if grep -q $mac /sys/class/net/$i/address; then - dev=$i - logger -t cloud "$(basename $0): matched dev $i to mac $mac, dev is now $dev" - break - fi - done -fi - -gcidr="$ip/$mask" -if [ -n "$rules" ] -then - rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ") -fi - -# rule format -# protocal:sport:eport:cidr -#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32 -# if any entry is reverted , entry will be in the format :reverted:0:0:0 -# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:ACCEPT:,172.16.92.44:tcp:220:220:0.0.0.0/0:DROP,200.1.1.2:reverted:0:0:0 - -success=0 - -acl_chain_for_guest_network -egress=0 -for r in $rules_list -do - acl_entry_for_guest_network $r - success=$? - if [ $success -gt 0 ] - then - logger -t cloud "$(basename $0): failure to apply fw rules for guest network: $gcidr" - break - else - logger -t cloud "$(basename $0): successful in applying fw rules for guest network: $gcidr" - fi -done - -if [ $success -gt 0 ] -then - logger -t cloud "$(basename $0): restoring from backup for guest network: $gcidr" - acl_restore -else - logger -t cloud "$(basename $0): deleting backup for guest network: $gcidr" - if [ $egress -eq 0 ] - then - sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null - else - sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j DROP 2>/dev/null - fi - acl_switch_to_new -fi -unlock_exit $success $lock $locked - diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_guestnw.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_guestnw.sh deleted file mode 100755 index a7881345a01..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_guestnw.sh +++ /dev/null @@ -1,316 +0,0 @@ -#!/usr/bin/env bash -# 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. - -# guestnw.sh -- create/destroy guest network -# @VERSION@ - -source /root/func.sh -source /opt/cloud/bin/vpc_func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage:\n %s -A -M -d -i -g -m -s -e < domain> [-f] \n" $(basename $0) >&2 - printf " %s -D -d -i \n" $(basename $0) >&2 -} - - -destroy_acl_chain() { - sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -s $subnet/$mask ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -F ACL_INBOUND_$dev 2>/dev/null - sudo iptables -D FORWARD -o $dev -d $subnet/$mask -j ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X ACL_INBOUND_$dev 2>/dev/null - -} - -create_acl_chain() { - destroy_acl_chain - sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null - sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -s $subnet/$mask ! -d $ip -j ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -N ACL_INBOUND_$dev 2>/dev/null - # drop if no rules match (this will be the last rule in the chain) - sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null - sudo iptables -A FORWARD -o $dev -d $subnet/$mask -j ACL_INBOUND_$dev 2>/dev/null -} - - -setup_apache2() { - logger -t cloud "Setting up apache web server for $dev" - cp /etc/apache2/vhostexample.conf /etc/apache2/conf.d/vhost$dev.conf - sed -i -e "s///" /etc/apache2/conf.d/vhost$dev.conf - sed -i -e "s///" /etc/apache2/conf.d/vhost$dev.conf - sed -i -e "s/\tServerName.*/\tServerName vhost$dev.cloudinternal.com/" /etc/apache2/conf.d/vhost$dev.conf - sed -i -e "s/Listen .*:80/Listen $ip:80/g" /etc/apache2/conf.d/vhost$dev.conf - sed -i -e "s/Listen .*:443/Listen $ip:443/g" /etc/apache2/conf.d/vhost$dev.conf - service apache2 restart - sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT - sudo iptables -A INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT -} - -desetup_apache2() { - logger -t cloud "Desetting up apache web server for $dev" - rm -f /etc/apache2/conf.d/vhost$dev.conf - service apache2 restart - sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 80 -j ACCEPT -} - - -setup_dnsmasq() { - logger -t cloud "Setting up dnsmasq for network $ip/$mask " - # setup rules to allow dhcp/dns request - sudo iptables -D INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT - sudo iptables -D INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT - sudo iptables -D INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT - sudo iptables -A INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT - sudo iptables -A INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT - sudo iptables -A INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT - # setup static - sed -i -e "/^[#]*dhcp-range=interface:$dev/d" /etc/dnsmasq.d/cloud.conf - echo "dhcp-range=interface:$dev,set:interface-$dev,$ip,static" >> /etc/dnsmasq.d/cloud.conf - # setup DOMAIN - [ -z $DOMAIN ] && DOMAIN="cloudnine.internal" - - sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,15.*$/d" /etc/dnsmasq.d/cloud.conf - echo "dhcp-option=tag:interface-$dev,15,$DOMAIN" >> /etc/dnsmasq.d/cloud.conf - service dnsmasq restart - sleep 1 -} - -desetup_dnsmasq() { - logger -t cloud "Desetting up dnsmasq for network $ip/$mask " - # remove rules to allow dhcp/dns request - sudo iptables -D INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT - sudo iptables -D INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT - sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,option:router.*$/d" /etc/dnsmasq.d/cloud.conf - sed -i -e "/^[#]*dhcp-option=tag:interface-$dev,6.*$/d" /etc/dnsmasq.d/cloud.conf - sed -i -e "/^[#]*dhcp-range=interface:$dev/d" /etc/dnsmasq.d/cloud.conf - service dnsmasq restart - sleep 1 -} - -setup_passwdsvcs() { - logger -t cloud "Setting up password service for network $ip/$mask, eth $dev " - sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT - sudo iptables -A INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT - nohup bash /opt/cloud/bin/vpc_passwd_server $ip >/dev/null 2>&1 & -} - -desetup_passwdsvcs() { - logger -t cloud "Desetting up password service for network $ip/$mask, eth $dev " - sudo iptables -D INPUT -i $dev -d $ip -p tcp -m state --state NEW --dport 8080 -j ACCEPT - pid=`ps -ef | grep passwd_server_ip.py | grep $ip | grep -v grep | awk '{print $2}'` - if [ -n "$pid" ] - then - kill -9 $pid - fi -} - -create_guest_network() { - # need to wait for eth device to appear before configuring it - timer=0 - - # match dev based on mac, if passed - if [[ ! -z "$mac" ]]; then - logger -t cloud "$(basename $0): mac $mac passed, trying to match to device" - while [ ! $timer -gt 15 ]; do - for i in `ls /sys/class/net`; do - if grep -q $mac /sys/class/net/$i/address; then - dev=$i - logger -t cloud "$(basename $0): matched dev $i to mac $mac, dev is now $dev" - timer=15 - break - fi - done - sleep 1; - timer=$[timer + 1] - done - else - while ! `grep -q $dev /proc/net/dev` ; do - logger -t cloud "$(basename $0):Waiting for interface $dev to appear, $timer seconds" - sleep 1; - if [ $timer -gt 15 ]; then - logger -t cloud "$(basename $0):interface $dev never appeared" - break - fi - timer=$[timer + 1] - done - fi - - logger -t cloud " $(basename $0): Create network on interface $dev, gateway $gw, network $ip/$mask " - # setup ip configuration - sudo ip addr add dev $dev $ip/$mask brd + - sudo ip link set $dev up - sudo arping -c 3 -I $dev -A -U -s $ip $ip - echo 1 > /proc/sys/net/ipv4/conf/$dev/rp_filter - # restore mark from connection mark - local tableName="Table_$dev" - sudo ip route add $subnet/$mask dev $dev table $tableName proto static - sudo iptables -t mangle -D PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark - sudo iptables -t nat -D POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip - sudo iptables -t mangle -A PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark - # set up hairpin - sudo iptables -t nat -A POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip - create_acl_chain - setup_dnsmasq - setup_apache2 - setup_passwdsvcs - - #enable rps, rfs - enable_rpsrfs $dev -} - -enable_rpsrfs() { - - if [ -f /etc/rpsrfsenable ] - then - enable=$(cat /etc/rpsrfsenable) - if [ $enable -eq 0 ] - then - return 0 - fi - else - return 0 - fi - - proc=$(cat /proc/cpuinfo | grep "processor" | wc -l) - if [ $proc -le 1 ] - then - return 0 - fi - dev=$1 - - num=1 - num=$(($num<<$proc)) - num=$(($num-1)); - echo $num; - hex=$(printf "%x\n" $num) - echo $hex; - #enable rps - echo $hex > /sys/class/net/$dev/queues/rx-0/rps_cpus - - #enble rfs - rps_flow_entries=$(cat /proc/sys/net/core/rps_sock_flow_entries) - - if [ $rps_flow_entries -eq 0 ] - then - echo 256 > /proc/sys/net/core/rps_sock_flow_entries - fi - - echo 256 > /sys/class/net/$dev/queues/rx-0/rps_flow_cnt - -} - -destroy_guest_network() { - logger -t cloud " $(basename $0): Create network on interface $dev, gateway $gw, network $ip/$mask " - - sudo ip addr del dev $dev $ip/$mask - sudo iptables -t mangle -D PREROUTING -i $dev -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark - sudo iptables -t nat -D POSTROUTING -s $subnet/$mask -o $dev -j SNAT --to-source $ip - destroy_acl_chain - desetup_dnsmasq - desetup_apache2 - desetup_passwdsvcs -} - -#set -x -iflag=0 -mflag=0 -nflag=0 -dflag= -gflag= -Cflag= -Dflag= -Mflag= - -op="" - - -while getopts 'CDn:m:M:d:i:g:s:e:' OPTION -do - case $OPTION in - C) Cflag=1 - op="-C" - ;; - D) Dflag=1 - op="-D" - ;; - n) nflag=1 - subnet="$OPTARG" - ;; - m) mflag=1 - mask="$OPTARG" - ;; - M) Mflag=1 - mac="$OPTARG" - ;; - d) dflag=1 - dev="$OPTARG" - ;; - i) iflag=1 - ip="$OPTARG" - ;; - g) gflag=1 - gw="$OPTARG" - ;; - s) sflag=1 - DNS="$OPTARG" - ;; - e) eflag=1 - DOMAIN="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -vpccidr=$(getVPCcidr) - -if [ "$Cflag$Dflag$dflag" != "11" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ "$Cflag" == "1" ] && [ "$iflag$gflag$mflag" != "111" ] -then - usage - unlock_exit 2 $lock $locked -fi - - -if [ "$Cflag" == "1" ] -then - create_guest_network -fi - - -if [ "$Dflag" == "1" ] -then - destroy_guest_network -fi - -unlock_exit 0 $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_ipassoc.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_ipassoc.sh deleted file mode 100755 index 8c5e0e46d73..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_ipassoc.sh +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env bash -# 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. - - - -# ipassoc.sh -- associate/disassociate a public ip with an instance -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage:\n %s -A -l -c [-f] \n" $(basename $0) >&2 - printf " %s -D -l -c [-f] \n" $(basename $0) >&2 -} - -add_routing() { - logger -t cloud "$(basename $0):Add routing $pubIp on interface $ethDev" - - local tableName="Table_$ethDev" - sudo ip route add $subnet/$mask dev $ethDev table $tableName proto static - sudo ip route add default via $defaultGwIP table $tableName proto static - sudo ip route flush cache - sudo ip route | grep default - if [ $? -gt 0 ] - then - sudo ip route add default via $defaultGwIP - fi - return 0 -} - - -remove_routing() { - return 0 -} - -add_an_ip () { - # need to wait for eth device to appear before configuring it - timer=0 - while ! `grep -q $ethDev /proc/net/dev` ; do - logger -t cloud "$(basename $0):Waiting for interface $ethDev to appear, $timer seconds" - sleep 1; - if [ $timer -gt 15 ]; then - logger -t cloud "$(basename $0):interface $ethDev never appeared" - break - fi - timer=$[timer + 1] - done - - logger -t cloud "$(basename $0):Adding ip $pubIp on interface $ethDev" - sudo ip link show $ethDev | grep "state DOWN" > /dev/null - local old_state=$? - - sudo ip addr add dev $ethDev $pubIp/$mask brd + - if [ $old_state -eq 0 ] - then - sudo ip link set $ethDev up - fi - sudo arping -c 1 -I $ethDev -A -U -s $pubIp $pubIp - sudo arping -c 1 -I $ethDev -A -U -s $pubIp $pubIp - local tableNo=${ethDev:3} - sudo iptables-save -t mangle | grep "PREROUTING -i $ethDev -m state --state NEW -j CONNMARK --set-xmark" 2>/dev/null - if [ $? -gt 0 ] - then - sudo iptables -t mangle -A PREROUTING -i $ethDev -m state --state NEW -j CONNMARK --set-mark $tableNo 2>/dev/null - fi - - enable_rpsrfs $ethDev - add_routing - return $? -} - -enable_rpsrfs() { - - if [ -f /etc/rpsrfsenable ] - then - enable=$(cat /etc/rpsrfsenable) - if [ $enable -eq 0 ] - then - return 0 - fi - else - return 0 - fi - - proc=$(cat /proc/cpuinfo | grep "processor" | wc -l) - if [ $proc -le 1 ] - then - return 0 - fi - dev=$1 - - num=1 - num=$(($num<<$proc)) - num=$(($num-1)); - echo $num; - hex=$(printf "%x\n" $num) - echo $hex; - #enable rps - echo $hex > /sys/class/net/$dev/queues/rx-0/rps_cpus - - #enble rfs - rps_flow_entries=$(cat /proc/sys/net/core/rps_sock_flow_entries) - - if [ $rps_flow_entries -eq 0 ] - then - echo 256 > /proc/sys/net/core/rps_sock_flow_entries - fi - - if [ $(cat /sys/class/net/$dev/queues/rx-0/rps_flow_cnt) -eq 0 ] - then - echo 256 > /sys/class/net/$dev/queues/rx-0/rps_flow_cnt - fi -} - -remove_an_ip () { - logger -t cloud "$(basename $0):Removing ip $pubIp on interface $ethDev" - local existingIpMask=$(sudo ip addr show dev $ethDev | grep -v "inet6" | grep "inet " | awk '{print $2}') - - sudo ip addr del dev $ethDev $pubIp/$mask - # reapply IPs in this interface - for ipMask in $existingIpMask - do - if [ "$ipMask" == "$pubIp/$mask" ] - then - continue - fi - sudo ip addr add dev $ethDev $ipMask brd + - done - - remove_routing - return 0 -} - -#set -x -lflag=0 -cflag=0 -gflag=0 -mflag=0 -nflag=0 -op="" - - -while getopts 'ADl:c:g:m:n:' OPTION -do - case $OPTION in - A) Aflag=1 - op="-A" - ;; - D) Dflag=1 - op="-D" - ;; - l) lflag=1 - pubIp="$OPTARG" - ;; - c) cflag=1 - ethDev="$OPTARG" - ;; - g) gflag=1 - defaultGwIP="$OPTARG" - ;; - m) mflag=1 - mask="$OPTARG" - ;; - n) nflag=1 - subnet="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - - -if [ "$Aflag$Dflag" != "1" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ "$lflag$cflag$gflag$mflag$nflag" != "11111" ] -then - usage - unlock_exit 2 $lock $locked -fi - - -if [ "$Aflag" == "1" ] -then - add_an_ip - unlock_exit $? $lock $locked -fi - - -if [ "$Dflag" == "1" ] -then - remove_an_ip - unlock_exit $? $lock $locked -fi - - -unlock_exit 1 $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_loadbalancer.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_loadbalancer.sh deleted file mode 100755 index b9b377ce622..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_loadbalancer.sh +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env bash -# 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. - -# @VERSION@ - -do_ilb_if_ilb () { - local typ="" - local pattern="type=(.*)" - - for keyval in $(cat /var/cache/cloud/cmdline) - do - if [[ $keyval =~ $pattern ]]; then - typ=${BASH_REMATCH[1]}; - fi - done - if [ "$typ" == "ilbvm" ] - then - logger -t cloud "$(basename $0): Detected that we are running in an internal load balancer vm" - $(dirname $0)/ilb.sh "$@" - exit $? - fi - -} - -logger -t cloud "$(basename $0): Entering $(dirname $0)/$(basename $0)" - -do_ilb_if_ilb "$@" - -source /root/func.sh -source /opt/cloud/bin/vpc_func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: -i -a -d -f -s \n" $(basename $0) >&2 -} - -# set -x - -fw_remove_backup() { - sudo iptables -F back_load_balancer 2> /dev/null - sudo iptables -D INPUT -p tcp -j back_load_balancer 2> /dev/null - sudo iptables -X back_load_balancer 2> /dev/null - sudo iptables -F back_lb_stats 2> /dev/null - sudo iptables -D INPUT -p tcp -j back_lb_stats 2> /dev/null - sudo iptables -X back_lb_stats 2> /dev/null -} - -fw_remove() { - sudo iptables -F load_balancer 2> /dev/null - sudo iptables -D INPUT -p tcp -j load_balancer 2> /dev/null - sudo iptables -X load_balancer 2> /dev/null - sudo iptables -F lb_stats 2> /dev/null - sudo iptables -D INPUT -p tcp -j lb_stats 2> /dev/null - sudo iptables -X lb_stats 2> /dev/null -} - -fw_backup() { - fw_remove_backup - sudo iptables -E load_balancer back_load_balancer 2> /dev/null - sudo iptables -E lb_stats back_lb_stats 2> /dev/null -} - -fw_restore() { - fw_remove - sudo iptables -E back_load_balancer load_balancer 2> /dev/null - sudo iptables -E back_lb_stats lb_stats 2> /dev/null -} - -fw_chain_create () { - fw_backup - sudo iptables -N load_balancer 2> /dev/null - sudo iptables -A INPUT -p tcp -j load_balancer 2> /dev/null - sudo iptables -N lb_stats 2> /dev/null - sudo iptables -A INPUT -p tcp -j lb_stats 2> /dev/null -} - -# firewall entry to ensure that haproxy can receive on specified port -fw_entry() { - local added=$1 - local removed=$2 - local stats=$3 - if [ "$added" == "none" ] - then - added="" - fi - if [ "$removed" == "none" ] - then - removed="" - fi - local a=$(echo $added | cut -d, -f1- --output-delimiter=" ") - local r=$(echo $removed | cut -d, -f1- --output-delimiter=" ") - fw_chain_create - success=0 - while [ 1 ] - do - for i in $a - do - local pubIp=$(echo $i | cut -d: -f1) - local dport=$(echo $i | cut -d: -f2) - sudo iptables -A load_balancer -p tcp -d $pubIp --dport $dport -j ACL_INBOUND_$dev 2>/dev/null - success=$? - if [ $success -gt 0 ] - then - break - fi - done - if [ "$stats" != "none" ] - then - local pubIp=$(echo $stats | cut -d: -f1) - local dport=$(echo $stats | cut -d: -f2) - local cidrs=$(echo $stats | cut -d: -f3 | sed 's/-/,/') - sudo iptables -A lb_stats -s $cidrs -p tcp -d $pubIp --dport $dport -j ACCEPT 2>/dev/null - success=$? - fi - break - done - if [ $success -gt 0 ] - then - fw_restore - else - fw_remove_backup - fi - return $success -} - -#Hot reconfigure HA Proxy in the routing domain -reconfig_lb() { - logger -t cloud "Reconfiguring loadbalancer using $1" - /root/reconfigLB.sh $1 - return $? -} - -# Restore the HA Proxy to its previous state, and revert iptables rules on DomR -restore_lb() { - logger -t cloud "Restoring HA Proxy to previous state" - # Copy the old version of haproxy.cfg into the file that reconfigLB.sh uses - cp /etc/haproxy/haproxy.cfg.old /etc/haproxy/haproxy.cfg.new - - if [ $? -eq 0 ] - then - # Run reconfigLB.sh again - /root/reconfigLB.sh /etc/haproxy/haproxy.cfg.new - fi -} - -iflag= -aflag= -dflag= -fflag= -sflag= - -while getopts 'i:a:d:f:s:' OPTION -do - case $OPTION in - i) iflag=1 - ip="$OPTARG" - ;; - a) aflag=1 - addedIps="$OPTARG" - ;; - d) dflag=1 - removedIps="$OPTARG" - ;; - s) sflag=1 - statsIp="$OPTARG" - ;; - f) fflag=1 - cfgfile="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - - -dev=$(getEthByIp $ip) - -if [ "$addedIps" == "" ] -then - addedIps="none" -fi - -if [ "$removedIps" == "" ] -then - removedIps="none" -fi - -# hot reconfigure haproxy -reconfig_lb $cfgfile - -if [ $? -gt 0 ] -then - logger -t cloud "Reconfiguring loadbalancer failed" - unlock_exit 1 $lock $locked -fi - -# iptables entry to ensure that haproxy receives traffic -fw_entry $addedIps $removedIps $statsIp -result=$? -if [ $result -gt 0 ] -then - logger -t cloud "Failed to apply firewall rules for load balancing, reverting HA Proxy config" - # Restore the LB - restore_lb -fi - -unlock_exit $result $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_portforwarding.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_portforwarding.sh deleted file mode 100755 index 5aeaa70357b..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_portforwarding.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env bash -# 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. -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: (-A|-D) -r -P protocol (-p port_range | -t icmp_type_code) -l -d -s [-G] \n" $(basename $0) >&2 -} - -#set -x - -#Port (address translation) forwarding for tcp or udp -tcp_or_udp_nat() { - local op=$1 - local proto=$2 - local publicIp=$3 - local ports=$4 - local instIp=$5 - local dports=$6 - - logger -t cloud "$(basename $0): creating port fwd entry for PAT: public ip=$publicIp \ - instance ip=$instIp proto=$proto port=$port dport=$dport op=$op" - - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && tcp_or_udp_nat "-D" $proto $publicIp $ports $instIp $dports - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - # shortcircuit the process if error and it is an append operation - # continue if it is delete - local PROTO="" - if [ "$proto" != "any" ] - then - PROTO="--proto $proto" - fi - - local DEST_PORT="" - if [ "$ports" != "any" ] - then - DEST_PORT="--destination-port $ports" - fi - - local TO_DEST="--to-destination $instIp" - if [ "$dports" != "any" ] - then - TO_DEST="--to-destination $instIp:$dports" - fi - - sudo iptables -t nat $op PREROUTING $PROTO -d $publicIp $DEST_PORT -j DNAT \ - $TO_DEST &>> $OUTFILE - - local result=$? - logger -t cloud "$(basename $0): done port fwd entry for PAT: public ip=$publicIp op=$op result=$result" - # the rule may not exist - if [ "$op" == "-D" ] - then - return 0 - fi - return $result -} - - -rflag= -Pflag= -pflag= -lflag= -dflag= -op="" -protocal="any" -ports="any" -dports="any" -while getopts 'ADr:P:p:l:d:' OPTION -do - case $OPTION in - A) op="-A" - ;; - D) op="-D" - ;; - r) rflag=1 - instanceIp="$OPTARG" - ;; - P) Pflag=1 - protocol="$OPTARG" - ;; - p) pflag=1 - ports="$OPTARG" - ;; - l) lflag=1 - publicIp="$OPTARG" - ;; - d) dflag=1 - dports="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -OUTFILE=$(mktemp) - -tcp_or_udp_nat $op $protocol $publicIp $ports $instanceIp $dports -result=$? -unlock_exit $result $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_privateGateway.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_privateGateway.sh deleted file mode 100755 index 3635e1cd44c..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_privateGateway.sh +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env bash -# 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. - -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage:\n %s -A -l \n" $(basename $0) >&2 - printf " %s -D -l \n" $(basename $0) >&2 -} - - -add_snat() { - logger -t cloud "$(basename $0):Added SourceNAT $pubIp on interface $ethDev" - sudo iptables -t nat -D POSTROUTING -j SNAT -o $ethDev --to-source $pubIp - sudo iptables -t nat -A POSTROUTING -j SNAT -o $ethDev --to-source $pubIp - return $? -} -remove_snat() { - logger -t cloud "$(basename $0):Removing SourceNAT $pubIp on interface $ethDev" - sudo iptables -t nat -D POSTROUTING -j SNAT -o $ethDev --to-source $pubIp - return $? -} - -#set -x -lflag=0 -cflag=0 -op="" - -while getopts 'ADl:c:' OPTION -do - case $OPTION in - A) Aflag=1 - op="-A" - ;; - D) Dflag=1 - op="-D" - ;; - l) lflag=1 - pubIp="$OPTARG" - ;; - c) cflag=1 - ethDev="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -if [ "$Aflag$Dflag" != "1" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ "$lflag$cflag" != "11" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ "$Aflag" == "1" ] -then - add_snat $publicIp - unlock_exit $? $lock $locked -fi - -if [ "$Dflag" == "1" ] -then - remove_snat $publicIp - unlock_exit $? $lock $locked -fi - -unlock_exit 1 $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_privategw_acl.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_privategw_acl.sh deleted file mode 100755 index b585a364bd8..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_privategw_acl.sh +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env bash -# 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. -# vpc_privategw_acl.sh_rule.sh -- allow/block some ports / protocols to vm instances -# @VERSION@ - -source /root/func.sh - -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: -a \n" $(basename $0) >&2 - printf "sourcecidrs format: cidr1-cidr2-cidr3-...\n" -} -#set -x -#FIXME: eating up the error code during execution of iptables - -acl_switch_to_new() { - sudo iptables -D FORWARD -o $dev -j _ACL_INBOUND_$dev 2>/dev/null - sudo iptables-save | grep "\-j _ACL_INBOUND_$dev" | grep "\-A" | while read rule; - do - rule1=$(echo $rule | sed 's/\_ACL_INBOUND/ACL_INBOUND/') - sudo iptables $rule1 - rule2=$(echo $rule | sed 's/\-A/\-D/') - sudo iptables $rule2 - done - sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_remove_backup() { - sudo iptables -F _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -D FORWARD -o $dev -j _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j _ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_remove() { - sudo iptables -F ACL_INBOUND_$dev 2>/dev/null - sudo iptables -D FORWARD -o $dev -j ACL_INBOUND_$dev 2>/dev/null - sudo iptables -X ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -F ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -D PREROUTING -m state --state NEW -i $dev -j ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -X ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_restore() { - acl_remove - sudo iptables -E _ACL_INBOUND_$dev ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -E _ACL_OUTBOUND_$dev ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_save() { - acl_remove_backup - sudo iptables -E ACL_INBOUND_$dev _ACL_INBOUND_$dev 2>/dev/null - sudo iptables -t mangle -E ACL_OUTBOUND_$dev _ACL_OUTBOUND_$dev 2>/dev/null -} - -acl_chain_for_guest_network () { - acl_save - # inbound - sudo iptables -N ACL_INBOUND_$dev 2>/dev/null - # drop if no rules match (this will be the last rule in the chain) - sudo iptables -A ACL_INBOUND_$dev -j DROP 2>/dev/null - sudo iptables -A FORWARD -o $dev -j ACL_INBOUND_$dev 2>/dev/null - # outbound - sudo iptables -t mangle -N ACL_OUTBOUND_$dev 2>/dev/null - sudo iptables -t mangle -A PREROUTING -m state --state NEW -i $dev -j ACL_OUTBOUND_$dev 2>/dev/null -} - - - -acl_entry_for_guest_network() { - local rule=$1 - - local ttype=$(echo $rule | cut -d: -f1) - local prot=$(echo $rule | cut -d: -f2) - local sport=$(echo $rule | cut -d: -f3) - local eport=$(echo $rule | cut -d: -f4) - local cidrs=$(echo $rule | cut -d: -f5 | sed 's/-/ /g') - local action=$(echo $rule | cut -d: -f6) - if [ "$sport" == "0" -a "$eport" == "0" ] - then - DPORT="" - else - DPORT="--dport $sport:$eport" - fi - logger -t cloud "$(basename $0): enter apply acl rules on private gateway interface : $dev, inbound:$inbound:$prot:$sport:$eport:$cidrs" - - # note that rules are inserted after the RELATED,ESTABLISHED rule - # but before the DROP rule - for lcidr in $cidrs - do - [ "$prot" == "reverted" ] && continue; - if [ "$prot" == "icmp" ] - then - typecode="$sport/$eport" - [ "$eport" == "-1" ] && typecode="$sport" - [ "$sport" == "-1" ] && typecode="any" - if [ "$ttype" == "Ingress" ] - then - sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \ - --icmp-type $typecode -j $action - else - let egress++ - sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \ - --icmp-type $typecode -j $action - fi - else - if [ "$ttype" == "Ingress" ] - then - sudo iptables -I ACL_INBOUND_$dev -p $prot -s $lcidr \ - $DPORT -j $action - else - let egress++ - sudo iptables -t mangle -I ACL_OUTBOUND_$dev -p $prot -d $lcidr \ - $DPORT -j $action - fi - fi - result=$? - [ $result -gt 0 ] && - logger -t cloud "Error adding iptables entry for private gateway interface : $dev,inbound:$inbound:$prot:$sport:$eport:$cidrs" && - break - done - - logger -t cloud "$(basename $0): exit apply acl rules for private gw interface : $dev" - return $result -} - - -dflag=0 -gflag=0 -aflag=0 -mflag=0 -rules="" -rules_list="" -dev="" -mac="" -while getopts 'd:a:M:' OPTION -do - case $OPTION in - d) dflag=1 - dev="$OPTARG" - ;; - a) aflag=1 - rules="$OPTARG" - ;; - M) mflag=1 - mac="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -if [ "$dflag$aflag" != "11" ] -then - usage - unlock_exit 2 $lock $locked -fi - -if [ -n "$rules" ] -then - rules_list=$(echo $rules | cut -d, -f1- --output-delimiter=" ") -fi - -# rule format -# protocal:sport:eport:cidr -#-a tcp:80:80:0.0.0.0/0::tcp:220:220:0.0.0.0/0:,172.16.92.44:tcp:222:222:192.168.10.0/24-75.57.23.0/22-88.100.33.1/32 -# if any entry is reverted , entry will be in the format :reverted:0:0:0 -# example : 172.16.92.44:tcp:80:80:0.0.0.0/0:ACCEPT:,172.16.92.44:tcp:220:220:0.0.0.0/0:DROP,200.1.1.2:reverted:0:0:0 - -success=0 - -acl_chain_for_guest_network -egress=0 -for r in $rules_list -do - acl_entry_for_guest_network $r - success=$? - if [ $success -gt 0 ] - then - logger -t cloud "$(basename $0): failure to apply acl rules on private gateway interface : $dev" - break - else - logger -t cloud "$(basename $0): successful in applying acl rules on private gateway interface : $dev" - fi -done - -if [ $success -gt 0 ] -then - logger -t cloud "$(basename $0): restoring from backup on private gateway interface : $dev" - acl_restore -else - logger -t cloud "$(basename $0): deleting backup on private gateway interface : $dev" - if [ $egress -eq 0 ] - then - sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j ACCEPT 2>/dev/null - else - sudo iptables -t mangle -A ACL_OUTBOUND_$dev -j DROP 2>/dev/null - fi - acl_switch_to_new -fi -unlock_exit $success $lock $locked diff --git a/systemvm/patches/debian/config/opt/cloud/bin/vpc_staticnat.sh b/systemvm/patches/debian/config/opt/cloud/bin/vpc_staticnat.sh deleted file mode 100755 index a98a26225b6..00000000000 --- a/systemvm/patches/debian/config/opt/cloud/bin/vpc_staticnat.sh +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env bash -# 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. -# @VERSION@ - -source /root/func.sh -source /opt/cloud/bin/vpc_func.sh -lock="biglock" -locked=$(getLockFile $lock) -if [ "$locked" != "1" ] -then - exit 1 -fi - -usage() { - printf "Usage: %s: (-A|-D) -r -l -d < eth device> \n" $(basename $0) >&2 -} - -#set -x - -vpnoutmark="0x525" - -static_nat() { - local op=$1 - local publicIp=$2 - local instIp=$3 - local op2="-D" - local tableNo=${ethDev:3} - - logger -t cloud "$(basename $0): static nat: public ip=$publicIp \ - instance ip=$instIp op=$op" - #if adding, this might be a duplicate, so delete the old one first - [ "$op" == "-A" ] && static_nat "-D" $publicIp $instIp - # the delete operation may have errored out but the only possible reason is - # that the rules didn't exist in the first place - [ "$op" == "-A" ] && op2="-I" - if [ "$op" == "-A" ] - then - # put static nat rule one rule after VPN no-NAT rule - # rule chain can be used to improve it later - iptables-save -t nat|grep "POSTROUTING" | grep $vpnoutmark > /dev/null - if [ $? -eq 0 ] - then - rulenum=2 - else - rulenum=1 - fi - fi - - # shortcircuit the process if error and it is an append operation - # continue if it is delete - (sudo iptables -t nat $op PREROUTING -d $publicIp -j DNAT \ - --to-destination $instIp &>> $OUTFILE || [ "$op" == "-D" ]) && - # add mark to force the package go out through the eth the public IP is on - #(sudo iptables -t mangle $op PREROUTING -s $instIp -j MARK \ - # --set-mark $tableNo &> $OUTFILE || [ "$op" == "-D" ]) && - (sudo iptables -t nat $op2 POSTROUTING $rulenum -o $ethDev -s $instIp -j SNAT \ - --to-source $publicIp &>> $OUTFILE ) - result=$? - logger -t cloud "$(basename $0): done static nat entry public ip=$publicIp op=$op result=$result" - if [ "$op" == "-D" ] - then - return 0 - fi - return $result -} - - - -rflag= -lflag= -dflag= -op="" -while getopts 'ADr:l:' OPTION - -do - case $OPTION in - A) op="-A" - ;; - D) op="-D" - ;; - r) rflag=1 - instanceIp="$OPTARG" - ;; - l) lflag=1 - publicIp="$OPTARG" - ;; - ?) usage - unlock_exit 2 $lock $locked - ;; - esac -done - -ethDev=$(getEthByIp $publicIp) -result=$? -if [ $result -gt 0 ] -then - if [ "$op" == "-D" ] - then - removeRulesForIp $publicIp - unlock_exit 0 $lock $locked - else - unlock_exit $result $lock $locked - fi -fi -OUTFILE=$(mktemp) - -static_nat $op $publicIp $instanceIp -result=$? -unlock_exit $result $lock $locked