Bump priority stragety is no longer used for redundant virtual routers

- With the changes added by the rVPC work, the bump priority became deprecated.
     This commit includes a refactor to get it removed from the following resources:
     * Java classes
     * domain_router table - removing the is_priority_bumpup column
     * Fixing unit tests

All changes were tested with:

XenServer 6.2 running under our VMWare zone
CloudStack Management Server running on MacBook Pro
MySql running on MackBook Pro
Storage Type: Local
This commit is contained in:
wilderrodrigues 2015-04-02 18:20:29 +02:00
parent 3e28747881
commit 3d22a16c4f
21 changed files with 678 additions and 985 deletions

View File

@ -22,63 +22,49 @@ package com.cloud.agent.api;
import com.cloud.network.router.VirtualRouter.RedundantState;
public class CheckRouterAnswer extends Answer {
public static final String ROUTER_NAME = "router.name";
public static final String ROUTER_IP = "router.ip";
RedundantState state;
boolean isBumped;
protected CheckRouterAnswer() {
}
public CheckRouterAnswer(CheckRouterCommand cmd, String details, boolean parse) {
public CheckRouterAnswer(final CheckRouterCommand cmd, final String details, final boolean parse) {
super(cmd, true, details);
if (parse) {
if (!parseDetails(details)) {
this.result = false;
result = false;
}
}
}
public CheckRouterAnswer(CheckRouterCommand cmd, String details) {
public CheckRouterAnswer(final CheckRouterCommand cmd, final String details) {
super(cmd, false, details);
}
protected boolean parseDetails(String details) {
String[] lines = details.split("&");
if (lines.length != 2) {
protected boolean parseDetails(final String details) {
if (details == null || "".equals(details.trim())) {
state = RedundantState.UNKNOWN;
return false;
}
if (lines[0].startsWith("Status: MASTER")) {
if (details.startsWith("Status: MASTER")) {
state = RedundantState.MASTER;
} else if (lines[0].startsWith("Status: BACKUP")) {
} else if (details.startsWith("Status: BACKUP")) {
state = RedundantState.BACKUP;
} else if (lines[0].startsWith("Status: FAULT")) {
} else if (details.startsWith("Status: FAULT")) {
state = RedundantState.FAULT;
} else {
state = RedundantState.UNKNOWN;
}
if (lines[1].startsWith("Bumped: YES")) {
isBumped = true;
} else {
isBumped = false;
}
return true;
}
public void setState(RedundantState state) {
public void setState(final RedundantState state) {
this.state = state;
}
public RedundantState getState() {
return state;
}
public boolean isBumped() {
return isBumped;
}
public void setIsBumped(boolean isBumped) {
this.isBumped = isBumped;
}
}

View File

@ -28,7 +28,6 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand {
String defaultDns1 = null;
String defaultDns2 = null;
boolean isRedundant = false;
Integer priority;
boolean add = true;
NicTO nic;
@ -60,14 +59,13 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand {
protected SetupGuestNetworkCommand() {
}
public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority, String defaultDns1, String defaultDns2, boolean add,
NicTO nic) {
public SetupGuestNetworkCommand(final String dhcpRange, final String networkDomain, final boolean isRedundant, final String defaultDns1, final String defaultDns2, final boolean add,
final NicTO nic) {
this.dhcpRange = dhcpRange;
this.networkDomain = networkDomain;
this.defaultDns1 = defaultDns1;
this.defaultDns2 = defaultDns2;
this.isRedundant = isRedundant;
this.priority = priority;
this.add = add;
this.nic = nic;
}

View File

@ -101,26 +101,26 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
String ROUTERNAME = "r-4-VM";
@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, 60);
}
@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) {
assertEquals(routerIp, ROUTERIP);
verifyCommand(_currentCmd, script, args);
return new ExecutionResult(true, null);
}
@Override
public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) {
public ExecutionResult createFileInVR(final String routerIp, final String path, final String filename, final String content) {
assertEquals(routerIp, ROUTERIP);
verifyFile(_currentCmd, path, filename, content);
return new ExecutionResult(true, null);
}
@Override
public ExecutionResult prepareCommand(NetworkElementCommand cmd) {
public ExecutionResult prepareCommand(final NetworkElementCommand cmd) {
cmd.setRouterAccessIp(ROUTERIP);
_currentCmd = cmd;
if (cmd instanceof IpAssocVpcCommand) {
@ -138,7 +138,7 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
@Override
public ExecutionResult cleanupCommand(NetworkElementCommand cmd) {
public ExecutionResult cleanupCommand(final NetworkElementCommand cmd) {
return new ExecutionResult(true, null);
}
@ -147,12 +147,12 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
_resource = new VirtualRoutingResource(this);
try {
_resource.configure("VRResource", new HashMap<String, Object>());
} catch (ConfigurationException e) {
} catch (final ConfigurationException e) {
e.printStackTrace();
}
}
private void verifyFile(NetworkElementCommand cmd, String path, String filename, String content) {
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);
} else if (cmd instanceof LoadBalancerConfigCommand) {
@ -160,7 +160,7 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
}
protected void verifyCommand(NetworkElementCommand cmd, String script, String args) {
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) {
@ -210,54 +210,54 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
}
private void verifyArgs(VpnUsersCfgCommand cmd, String script, String args) {
private void verifyArgs(final VpnUsersCfgCommand cmd, final String script, final String args) {
//To change body of created methods use File | Settings | File Templates.
}
private void verifyArgs(SetStaticRouteCommand cmd, String script, String args) {
private void verifyArgs(final SetStaticRouteCommand cmd, final String script, final String args) {
//To change body of created methods use File | Settings | File Templates.
}
private void verifyArgs(SetStaticNatRulesCommand cmd, String script, String args) {
private void verifyArgs(final SetStaticNatRulesCommand cmd, final String script, final String args) {
//To change body of created methods use File | Settings | File Templates.
}
@Test
public void testBumpUpCommand() {
BumpUpPriorityCommand cmd = new BumpUpPriorityCommand();
Answer answer = _resource.executeRequest(cmd);
final BumpUpPriorityCommand cmd = new BumpUpPriorityCommand();
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
private void verifyArgs(BumpUpPriorityCommand cmd, String script, String args) {
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() {
SetPortForwardingRulesVpcCommand cmd = generateSetPortForwardingRulesVpcCommand();
final SetPortForwardingRulesVpcCommand cmd = generateSetPortForwardingRulesVpcCommand();
// Reset rule check count
_count = 0;
Answer answer = _resource.executeRequest(cmd);
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer instanceof GroupAnswer);
assertEquals(((GroupAnswer) answer).getResults().length, 2);
assertTrue(answer.getResult());
}
protected SetPortForwardingRulesVpcCommand generateSetPortForwardingRulesVpcCommand() {
List<PortForwardingRuleTO> pfRules = new ArrayList<>();
final List<PortForwardingRuleTO> pfRules = new ArrayList<>();
pfRules.add(new PortForwardingRuleTO(1, "64.1.1.10", 22, 80, "10.10.1.10", 22, 80, "TCP", false, false));
pfRules.add(new PortForwardingRuleTO(2, "64.1.1.11", 8080, 8080, "10.10.1.11", 8080, 8080, "UDP", true, false));
SetPortForwardingRulesVpcCommand cmd = new SetPortForwardingRulesVpcCommand(pfRules);
final SetPortForwardingRulesVpcCommand cmd = new SetPortForwardingRulesVpcCommand(pfRules);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
assertEquals(cmd.getAnswersCount(), 2);
return cmd;
}
private void verifyArgs(SetPortForwardingRulesVpcCommand cmd, String script, String args) {
private void verifyArgs(final SetPortForwardingRulesVpcCommand cmd, final String script, final String args) {
assertTrue(script.equals(VRScripts.VPC_PORTFORWARDING));
_count ++;
switch (_count) {
@ -274,27 +274,27 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testSetPortForwardingRulesCommand() {
SetPortForwardingRulesCommand cmd = generateSetPortForwardingRulesCommand();
final SetPortForwardingRulesCommand cmd = generateSetPortForwardingRulesCommand();
// Reset rule check count
_count = 0;
Answer answer = _resource.executeRequest(cmd);
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer instanceof GroupAnswer);
assertEquals(((GroupAnswer) answer).getResults().length, 2);
assertTrue(answer.getResult());
}
protected SetPortForwardingRulesCommand generateSetPortForwardingRulesCommand() {
List<PortForwardingRuleTO> pfRules = new ArrayList<>();
final List<PortForwardingRuleTO> pfRules = new ArrayList<>();
pfRules.add(new PortForwardingRuleTO(1, "64.1.1.10", 22, 80, "10.10.1.10", 22, 80, "TCP", false, false));
pfRules.add(new PortForwardingRuleTO(2, "64.1.1.11", 8080, 8080, "10.10.1.11", 8080, 8080, "UDP", true, false));
SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(pfRules);
final SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(pfRules);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
assertEquals(cmd.getAnswersCount(), 2);
return cmd;
}
private void verifyArgs(SetPortForwardingRulesCommand cmd, String script, String args) {
private void verifyArgs(final SetPortForwardingRulesCommand cmd, final String script, final String args) {
assertTrue(script.equals(VRScripts.FIREWALL_NAT));
_count ++;
switch (_count) {
@ -311,31 +311,31 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testIpAssocCommand() {
IpAssocCommand cmd = generateIpAssocCommand();
final IpAssocCommand cmd = generateIpAssocCommand();
_count = 0;
Answer answer = _resource.executeRequest(cmd);
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer instanceof GroupAnswer);
assertEquals(2, ((GroupAnswer)answer).getResults().length);
assertTrue(answer.getResult());
}
private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) {
private ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) {
final IpAddressTO[] ips = cmd.getIpAddresses();
for (final IpAddressTO ip : ips) {
ip.setNicDevId(2);
}
return new ExecutionResult(true, null);
}
protected IpAssocCommand generateIpAssocCommand() {
List<IpAddressTO> ips = new ArrayList<>();
final List<IpAddressTO> ips = new ArrayList<>();
ips.add(new IpAddressTO(1, "64.1.1.10", true, true, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false));
ips.add(new IpAddressTO(2, "64.1.1.11", false, false, false, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false));
ips.add(new IpAddressTO(3, "65.1.1.11", true, false, false, "vlan://65", "65.1.1.1", "255.255.255.0", "11:23:45:67:89:AB", 1000, false));
IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]);
IpAssocCommand cmd = new IpAssocCommand(ipArray);
final IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]);
final IpAssocCommand cmd = new IpAssocCommand(ipArray);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
assertEquals(cmd.getAnswersCount(), 3);
@ -344,38 +344,38 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testIpAssocVpcCommand() {
IpAssocVpcCommand cmd = generateIpAssocVpcCommand();
final IpAssocVpcCommand cmd = generateIpAssocVpcCommand();
_count = 0;
Answer answer = _resource.executeRequest(cmd);
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer instanceof GroupAnswer);
assertEquals(2, ((GroupAnswer)answer).getResults().length);
assertTrue(answer.getResult());
}
private ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) {
IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) {
private ExecutionResult prepareNetworkElementCommand(final IpAssocVpcCommand cmd) {
final IpAddressTO[] ips = cmd.getIpAddresses();
for (final IpAddressTO ip : ips) {
ip.setNicDevId(2);
}
return new ExecutionResult(true, null);
}
protected IpAssocVpcCommand generateIpAssocVpcCommand() {
List<IpAddressTO> ips = new ArrayList<IpAddressTO>();
final List<IpAddressTO> ips = new ArrayList<IpAddressTO>();
ips.add(new IpAddressTO(1, "64.1.1.10", true, true, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false));
ips.add(new IpAddressTO(2, "64.1.1.11", false, false, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false));
ips.add(new IpAddressTO(3, "65.1.1.11", true, false, false, "vlan://65", "65.1.1.1", "255.255.255.0", "11:23:45:67:89:AB", 1000, false));
IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]);
IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipArray);
final IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]);
final IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipArray);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
assertEquals(6, cmd.getAnswersCount()); // AnswersCount is clearly wrong as it doesn't know enough to tell
return cmd;
}
private void verifyArgs(IpAssocCommand cmd, String script, String args) {
private void verifyArgs(final IpAssocCommand cmd, final String script, final String args) {
if (cmd instanceof IpAssocVpcCommand) {
_count ++;
switch (_count) {
@ -423,32 +423,32 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testSourceNatCommand() {
SetSourceNatCommand cmd = generateSetSourceNatCommand();
Answer answer = _resource.executeRequest(cmd);
final SetSourceNatCommand cmd = generateSetSourceNatCommand();
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
private ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) {
IpAddressTO ip = cmd.getIpAddress();
private ExecutionResult prepareNetworkElementCommand(final SetSourceNatCommand cmd) {
final IpAddressTO ip = cmd.getIpAddress();
ip.setNicDevId(1);
return new ExecutionResult(true, null);
}
protected SetSourceNatCommand generateSetSourceNatCommand() {
IpAddressTO ip = new IpAddressTO(1, "64.1.1.10", true, true, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false);
SetSourceNatCommand cmd = new SetSourceNatCommand(ip, true);
final IpAddressTO ip = new IpAddressTO(1, "64.1.1.10", true, true, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false);
final SetSourceNatCommand cmd = new SetSourceNatCommand(ip, true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(SetSourceNatCommand cmd, String script, String args) {
private void verifyArgs(final SetSourceNatCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.VPC_SOURCE_NAT);
assertEquals(args, "-A -l 64.1.1.10 -c eth1");
}
@Test
public void testNetworkACLCommand() {
SetNetworkACLCommand cmd = generateSetNetworkACLCommand();
final SetNetworkACLCommand cmd = generateSetNetworkACLCommand();
_count = 0;
Answer answer = _resource.executeRequest(cmd);
@ -460,24 +460,24 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
protected SetNetworkACLCommand generateSetNetworkACLCommand() {
List<NetworkACLTO> acls = new ArrayList<>();
List<String> cidrs = new ArrayList<>();
final List<NetworkACLTO> acls = new ArrayList<>();
final List<String> cidrs = new ArrayList<>();
cidrs.add("192.168.0.1/24");
cidrs.add("192.168.0.2/24");
acls.add(new NetworkACLTO(1, "64", "TCP", 20, 80, false, false, cidrs, 0, 0, TrafficType.Ingress, true, 1));
acls.add(new NetworkACLTO(2, "64", "ICMP", 0, 0, false, false, cidrs, -1, -1, TrafficType.Ingress, false, 2));
acls.add(new NetworkACLTO(3, "65", "ALL", 0, 0, false, false, cidrs, -1, -1, TrafficType.Egress, true, 3));
NicTO nic = new NicTO();
final NicTO nic = new NicTO();
nic.setMac("01:23:45:67:89:AB");
nic.setIp("192.168.1.1");
nic.setNetmask("255.255.255.0");
SetNetworkACLCommand cmd = new SetNetworkACLCommand(acls, nic);
final SetNetworkACLCommand cmd = new SetNetworkACLCommand(acls, nic);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(SetNetworkACLCommand cmd, String script, String args) {
private void verifyArgs(final SetNetworkACLCommand cmd, final String script, final String args) {
_count ++;
switch (_count) {
case 1:
@ -496,32 +496,32 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
}
private ExecutionResult prepareNetworkElementCommand(SetNetworkACLCommand cmd) {
NicTO nic = cmd.getNic();
private ExecutionResult prepareNetworkElementCommand(final SetNetworkACLCommand cmd) {
final NicTO nic = cmd.getNic();
nic.setDeviceId(3);
return new ExecutionResult(true, null);
}
@Test
public void testSetupGuestNetworkCommand() {
SetupGuestNetworkCommand cmd = generateSetupGuestNetworkCommand();
Answer answer = _resource.executeRequest(cmd);
final SetupGuestNetworkCommand cmd = generateSetupGuestNetworkCommand();
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) {
NicTO nic = cmd.getNic();
private ExecutionResult prepareNetworkElementCommand(final SetupGuestNetworkCommand cmd) {
final NicTO nic = cmd.getNic();
nic.setDeviceId(4);
return new ExecutionResult(true, null);
}
protected SetupGuestNetworkCommand generateSetupGuestNetworkCommand() {
NicTO nic = new NicTO();
final NicTO nic = new NicTO();
nic.setMac("01:23:45:67:89:AB");
nic.setIp("10.1.1.1");
nic.setNetmask("255.255.255.0");
SetupGuestNetworkCommand cmd = new SetupGuestNetworkCommand("10.1.1.10-10.1.1.20", "cloud.test", false, 0, "8.8.8.8", "8.8.4.4", true, nic);
final SetupGuestNetworkCommand cmd = new SetupGuestNetworkCommand("10.1.1.10-10.1.1.20", "cloud.test", false, "8.8.8.8", "8.8.4.4", true, nic);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, "10.1.1.2");
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, "10.1.1.1");
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
@ -529,7 +529,7 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(SetupGuestNetworkCommand cmd, String script, String args) {
private void verifyArgs(final SetupGuestNetworkCommand cmd, final String script, final String args) {
// TODO Check the contents of the json file
//assertEquals(script, VRScripts.VPC_GUEST_NETWORK);
//assertEquals(args, " -C -M 01:23:45:67:89:AB -d eth4 -i 10.1.1.2 -g 10.1.1.1 -m 24 -n 10.1.1.0 -s 8.8.8.8,8.8.4.4 -e cloud.test");
@ -537,23 +537,23 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testSetMonitorServiceCommand() {
SetMonitorServiceCommand cmd = generateSetMonitorServiceCommand();
Answer answer = _resource.executeRequest(cmd);
final SetMonitorServiceCommand cmd = generateSetMonitorServiceCommand();
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
protected SetMonitorServiceCommand generateSetMonitorServiceCommand() {
List<MonitorServiceTO> services = new ArrayList<>();
final List<MonitorServiceTO> services = new ArrayList<>();
services.add(new MonitorServiceTO("service", "process", "name", "path", "file", true));
services.add(new MonitorServiceTO("service_2", "process_2", "name_2", "path_2", "file_2", false));
SetMonitorServiceCommand cmd = new SetMonitorServiceCommand(services);
final SetMonitorServiceCommand cmd = new SetMonitorServiceCommand(services);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(SetMonitorServiceCommand cmd, String script, String args) {
private void verifyArgs(final SetMonitorServiceCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.MONITOR_SERVICE);
assertEquals(args, " -c [service]:processname=process:servicename=name:pidfile=file:,[service_2]:processname=process_2:servicename=name_2:pidfile=file_2:,");
}
@ -578,7 +578,7 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
assertTrue(answer.getResult());
}
private void verifyArgs(Site2SiteVpnCfgCommand cmd, String script, String args) {
private void verifyArgs(final Site2SiteVpnCfgCommand cmd, final String script, final String args) {
_count ++;
assertEquals(script, VRScripts.S2SVPN_IPSEC);
@ -612,27 +612,27 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
protected RemoteAccessVpnCfgCommand generateRemoteAccessVpnCfgCommand1() {
RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(true, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", false);
final RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(true, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", false);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
cmd.setLocalCidr("10.1.1.1/24");
return cmd;
}
protected RemoteAccessVpnCfgCommand generateRemoteAccessVpnCfgCommand2() {
RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(false, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", false);
final RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(false, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", false);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
cmd.setLocalCidr("10.1.1.1/24");
return cmd;
}
protected RemoteAccessVpnCfgCommand generateRemoteAccessVpnCfgCommand3() {
RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(true, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", true);
final RemoteAccessVpnCfgCommand cmd = new RemoteAccessVpnCfgCommand(true, "124.10.10.10", "10.10.1.1", "10.10.1.10-10.10.1.20", "sharedkey", true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
cmd.setLocalCidr("10.1.1.1/24");
return cmd;
}
private void verifyArgs(RemoteAccessVpnCfgCommand cmd, String script, String args) {
private void verifyArgs(final RemoteAccessVpnCfgCommand cmd, final String script, final String args) {
_count ++;
assertEquals(script, VRScripts.VPN_L2TP);
@ -656,27 +656,27 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
public void testFirewallRulesCommand() {
_count = 0;
Answer answer = _resource.executeRequest(generateSetFirewallRulesCommand());
final Answer answer = _resource.executeRequest(generateSetFirewallRulesCommand());
assertTrue(answer.getResult());
//TODO Didn't test egress rule because not able to generate FirewallRuleVO object
}
protected SetFirewallRulesCommand generateSetFirewallRulesCommand() {
List<FirewallRuleTO> rules = new ArrayList<>();
List<String> sourceCidrs = new ArrayList<>();
final List<FirewallRuleTO> rules = new ArrayList<>();
final List<String> sourceCidrs = new ArrayList<>();
sourceCidrs.add("10.10.1.1/24");
sourceCidrs.add("10.10.1.2/24");
rules.add(new FirewallRuleTO(1, "64.10.10.10", "TCP", 22, 80, false, false, Purpose.Firewall, sourceCidrs, 0, 0));
rules.add(new FirewallRuleTO(2, "64.10.10.10", "ICMP", 0, 0, false, false, Purpose.Firewall, sourceCidrs, -1, -1));
rules.add(new FirewallRuleTO(3, "64.10.10.10", "ICMP", 0, 0, true, true, Purpose.Firewall, sourceCidrs, -1, -1));
SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rules);
final SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rules);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(SetFirewallRulesCommand cmd, String script, String args) {
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
@ -689,12 +689,12 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testVmDataCommand() {
Answer answer = _resource.executeRequest(generateVmDataCommand());
final Answer answer = _resource.executeRequest(generateVmDataCommand());
assertTrue(answer.getResult());
}
protected VmDataCommand generateVmDataCommand() {
VmDataCommand cmd = new VmDataCommand("10.1.10.4", "i-4-VM", true);
final VmDataCommand cmd = new VmDataCommand("10.1.10.4", "i-4-VM", true);
// if you add new metadata files, also edit systemvm/patches/debian/config/var/www/html/latest/.htaccess
cmd.addVmData("userdata", "user-data", "user-data");
cmd.addVmData("metadata", "service-offering", "serviceOffering");
@ -713,24 +713,24 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
return cmd;
}
private void verifyArgs(VmDataCommand cmd, String script, String args) {
private void verifyArgs(final VmDataCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.UPDATE_CONFIG);
assertEquals(args, VRScripts.VM_METADATA_CONFIG);
}
@Test
public void testSavePasswordCommand() {
Answer answer = _resource.executeRequest(generateSavePasswordCommand());
final Answer answer = _resource.executeRequest(generateSavePasswordCommand());
assertTrue(answer.getResult());
}
protected SavePasswordCommand generateSavePasswordCommand() {
SavePasswordCommand cmd = new SavePasswordCommand("123pass", "10.1.10.4", "i-4-VM", true);
final SavePasswordCommand cmd = new SavePasswordCommand("123pass", "10.1.10.4", "i-4-VM", true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(SavePasswordCommand cmd, String script, String args) {
private void verifyArgs(final SavePasswordCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.PASSWORD);
assertEquals(args, "-v 10.1.10.4 -p 123pass");
}
@ -750,26 +750,26 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
protected DhcpEntryCommand generateDhcpEntryCommand1() {
DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", "10.1.10.2", "vm1", null, true);
final DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", "10.1.10.2", "vm1", null, true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
protected DhcpEntryCommand generateDhcpEntryCommand2() {
DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", null, "vm1", "2001:db8:0:0:0:ff00:42:8329", true);
final DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", null, "vm1", "2001:db8:0:0:0:ff00:42:8329", true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
cmd.setDuid(NetUtils.getDuidLL(cmd.getVmMac()));
return cmd;
}
protected DhcpEntryCommand generateDhcpEntryCommand3() {
DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", "10.1.10.2", "vm1", "2001:db8:0:0:0:ff00:42:8329", true);
final DhcpEntryCommand cmd = new DhcpEntryCommand("12:34:56:78:90:AB", "10.1.10.2", "vm1", "2001:db8:0:0:0:ff00:42:8329", true);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
cmd.setDuid(NetUtils.getDuidLL(cmd.getVmMac()));
return cmd;
}
private void verifyArgs(DhcpEntryCommand cmd, String script, String args) {
private void verifyArgs(final DhcpEntryCommand cmd, final String script, final String args) {
_count ++;
assertEquals(script, VRScripts.DHCP);
switch (_count) {
@ -789,63 +789,63 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
public void testCreateIpAliasCommand() {
Answer answer = _resource.executeRequest(generateCreateIpAliasCommand());
final Answer answer = _resource.executeRequest(generateCreateIpAliasCommand());
assertTrue(answer.getResult());
}
protected CreateIpAliasCommand generateCreateIpAliasCommand() {
List<IpAliasTO> aliases = new ArrayList<>();
final List<IpAliasTO> aliases = new ArrayList<>();
aliases.add(new IpAliasTO("169.254.3.10", "255.255.255.0", "1"));
aliases.add(new IpAliasTO("169.254.3.11", "255.255.255.0", "2"));
aliases.add(new IpAliasTO("169.254.3.12", "255.255.255.0", "3"));
CreateIpAliasCommand cmd = new CreateIpAliasCommand("169.254.3.10", aliases);
final CreateIpAliasCommand cmd = new CreateIpAliasCommand("169.254.3.10", aliases);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(CreateIpAliasCommand cmd, String script, String args) {
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() {
Answer answer = _resource.executeRequest(generateDeleteIpAliasCommand());
final Answer answer = _resource.executeRequest(generateDeleteIpAliasCommand());
assertTrue(answer.getResult());
}
protected DeleteIpAliasCommand generateDeleteIpAliasCommand() {
List<IpAliasTO> aliases = new ArrayList<>();
final List<IpAliasTO> aliases = new ArrayList<>();
aliases.add(new IpAliasTO("169.254.3.10", "255.255.255.0", "1"));
aliases.add(new IpAliasTO("169.254.3.11", "255.255.255.0", "2"));
aliases.add(new IpAliasTO("169.254.3.12", "255.255.255.0", "3"));
DeleteIpAliasCommand cmd = new DeleteIpAliasCommand("169.254.10.1", aliases, aliases);
final DeleteIpAliasCommand cmd = new DeleteIpAliasCommand("169.254.10.1", aliases, aliases);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(DeleteIpAliasCommand cmd, String script, String args) {
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() {
Answer answer = _resource.executeRequest(generateDnsMasqConfigCommand());
final Answer answer = _resource.executeRequest(generateDnsMasqConfigCommand());
assertTrue(answer.getResult());
}
protected DnsMasqConfigCommand generateDnsMasqConfigCommand() {
List<DhcpTO> dhcps = new ArrayList<>();
final List<DhcpTO> dhcps = new ArrayList<>();
dhcps.add(new DhcpTO("10.1.20.2", "10.1.20.1", "255.255.255.0", "10.1.20.5"));
dhcps.add(new DhcpTO("10.1.21.2", "10.1.21.1", "255.255.255.0", "10.1.21.5"));
DnsMasqConfigCommand cmd = new DnsMasqConfigCommand(dhcps);
final DnsMasqConfigCommand cmd = new DnsMasqConfigCommand(dhcps);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
private void verifyArgs(DnsMasqConfigCommand cmd, String script, String args) {
private void verifyArgs(final DnsMasqConfigCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.DNSMASQ_CONFIG);
assertEquals(args, "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-");
}
@ -863,37 +863,37 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
protected LoadBalancerConfigCommand generateLoadBalancerConfigCommand1() {
List<LoadBalancerTO> lbs = new ArrayList<>();
List<LbDestination> dests = new ArrayList<>();
final List<LoadBalancerTO> lbs = new ArrayList<>();
final List<LbDestination> dests = new ArrayList<>();
dests.add(new LbDestination(80, 8080, "10.1.10.2", false));
dests.add(new LbDestination(80, 8080, "10.1.10.2", true));
lbs.add(new LoadBalancerTO(UUID.randomUUID().toString(), "64.10.1.10", 80, "tcp", "algo", false, false, false, dests));
LoadBalancerTO[] arrayLbs = new LoadBalancerTO[lbs.size()];
final LoadBalancerTO[] arrayLbs = new LoadBalancerTO[lbs.size()];
lbs.toArray(arrayLbs);
NicTO nic = new NicTO();
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(arrayLbs, "64.10.2.10", "10.1.10.2", "192.168.1.2", nic, null, "1000", false);
final NicTO nic = new NicTO();
final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(arrayLbs, "64.10.2.10", "10.1.10.2", "192.168.1.2", nic, null, "1000", false);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, "10.1.10.2");
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
protected LoadBalancerConfigCommand generateLoadBalancerConfigCommand2() {
List<LoadBalancerTO> lbs = new ArrayList<>();
List<LbDestination> dests = new ArrayList<>();
final List<LoadBalancerTO> lbs = new ArrayList<>();
final List<LbDestination> dests = new ArrayList<>();
dests.add(new LbDestination(80, 8080, "10.1.10.2", false));
dests.add(new LbDestination(80, 8080, "10.1.10.2", true));
lbs.add(new LoadBalancerTO(UUID.randomUUID().toString(), "64.10.1.10", 80, "tcp", "algo", false, false, false, dests));
LoadBalancerTO[] arrayLbs = new LoadBalancerTO[lbs.size()];
final LoadBalancerTO[] arrayLbs = new LoadBalancerTO[lbs.size()];
lbs.toArray(arrayLbs);
NicTO nic = new NicTO();
final NicTO nic = new NicTO();
nic.setIp("10.1.10.2");
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(arrayLbs, "64.10.2.10", "10.1.10.2", "192.168.1.2", nic, Long.valueOf(1), "1000", false);
final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(arrayLbs, "64.10.2.10", "10.1.10.2", "192.168.1.2", nic, Long.valueOf(1), "1000", false);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, "10.1.10.2");
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
return cmd;
}
protected void verifyFile(LoadBalancerConfigCommand cmd, String path, String filename, String content) {
protected void verifyFile(final LoadBalancerConfigCommand cmd, final String path, final String filename, final String content) {
_count ++;
switch (_count) {
case 1:
@ -944,7 +944,7 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
}
}
private void verifyArgs(LoadBalancerConfigCommand cmd, String script, String args) {
private void verifyArgs(final LoadBalancerConfigCommand cmd, final String script, final String args) {
_count ++;
switch (_count) {
case 2:
@ -963,8 +963,8 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
@Test
@Ignore("Ignore this test while we are experimenting with the commands.")
public void testAggregationCommands() {
List<NetworkElementCommand> cmds = new LinkedList<>();
AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, ROUTERNAME, ROUTERIP, ROUTERGUESTIP);
final List<NetworkElementCommand> cmds = new LinkedList<>();
final AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, ROUTERNAME, ROUTERIP, ROUTERGUESTIP);
cmds.add(startCmd);
cmds.add(generateIpAssocCommand());
cmds.add(generateIpAssocVpcCommand());
@ -995,40 +995,40 @@ public class VirtualRoutingResourceTest implements VirtualRouterDeployer {
cmds.add(generateSavePasswordCommand());
cmds.add(generateVmDataCommand());
AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, ROUTERNAME, ROUTERIP, ROUTERGUESTIP);
final AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, ROUTERNAME, ROUTERIP, ROUTERGUESTIP);
cmds.add(finishCmd);
for (NetworkElementCommand cmd : cmds) {
Answer answer = _resource.executeRequest(cmd);
for (final NetworkElementCommand cmd : cmds) {
final Answer answer = _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
}
private void verifyArgs(AggregationControlCommand cmd, String script, String args) {
private void verifyArgs(final AggregationControlCommand cmd, final String script, final String args) {
assertEquals(script, VRScripts.VR_CFG);
assertTrue(args.startsWith("-c /var/cache/cloud/VR-"));
assertTrue(args.endsWith(".cfg"));
}
protected void verifyFile(AggregationControlCommand cmd, String path, String filename, String content) {
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"));
Collection<String> filteredScripts = Collections2.transform(Collections2.filter (
final Collection<String> filteredScripts = Collections2.transform(Collections2.filter (
Arrays.asList(content.split("</?script>")), new Predicate<String>() {
@Override
public boolean apply(String str) {
public boolean apply(final String str) {
return str.trim().startsWith("/opt/cloud");
}
}), new Function<String, String>() {
@Override
public String apply(String str) {
public String apply(final String str) {
return str.trim();
}
});
String[] scripts = filteredScripts.toArray(new String[filteredScripts
final String[] scripts = filteredScripts.toArray(new String[filteredScripts
.size()]);
assertEquals(

View File

@ -62,7 +62,8 @@ public class Upgrade451to460 implements DbUpgrade {
}
public void updateVMInstanceUserId(final Connection conn) {
// For schemas before this, copy first user from an account_id which deployed already running VMs
// For schemas before this, copy first user from an account_id which
// deployed already running VMs
s_logger.debug("Updating vm_instance column user_id using first user in vm_instance's account_id");
final String vmInstanceSql = "SELECT id, account_id FROM `cloud`.`vm_instance`";
final String userSql = "SELECT id FROM `cloud`.`user` where account_id=?";
@ -95,24 +96,21 @@ public class Upgrade451to460 implements DbUpgrade {
}
s_logger.debug("Done updating user Ids for previously deployed VMs");
addRedundancyForNwAndVpc(conn);
removeBumPriorityColumn(conn);
}
private void addRedundancyForNwAndVpc(final Connection conn) {
ResultSet rs = null;
try (PreparedStatement addRedundantColToVpcOfferingPstmt = conn.prepareStatement(
"ALTER TABLE `cloud`.`vpc_offerings` ADD COLUMN `redundant_router_service` tinyint(1) DEFAULT 0");
PreparedStatement addRedundantColToVpcPstmt = conn.prepareStatement(
"ALTER TABLE `cloud`.`vpc` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
PreparedStatement addRedundantColToNwPstmt = conn.prepareStatement(
"ALTER TABLE `cloud`.`networks` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
try (PreparedStatement addRedundantColToVpcOfferingPstmt = conn
.prepareStatement("ALTER TABLE `cloud`.`vpc_offerings` ADD COLUMN `redundant_router_service` tinyint(1) DEFAULT 0");
PreparedStatement addRedundantColToVpcPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vpc` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
PreparedStatement addRedundantColToNwPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`networks` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
// The redundancy of the networks must be based on the redundancy of their network offerings
PreparedStatement redundancyPerNwPstmt = conn.prepareStatement(
"select distinct nw.network_offering_id from networks nw join network_offerings off " +
"on nw.network_offering_id = off.id where off.redundant_router_service = 1");
PreparedStatement updateNwRedundancyPstmt = conn.prepareStatement(
"update networks set redundant = 1 where network_offering_id = ?");
) {
// The redundancy of the networks must be based on the
// redundancy of their network offerings
PreparedStatement redundancyPerNwPstmt = conn.prepareStatement("select distinct nw.network_offering_id from networks nw join network_offerings off "
+ "on nw.network_offering_id = off.id where off.redundant_router_service = 1");
PreparedStatement updateNwRedundancyPstmt = conn.prepareStatement("update networks set redundant = 1 where network_offering_id = ?");) {
addRedundantColToVpcPstmt.executeUpdate();
addRedundantColToVpcOfferingPstmt.executeUpdate();
addRedundantColToNwPstmt.executeUpdate();
@ -129,6 +127,15 @@ public class Upgrade451to460 implements DbUpgrade {
}
}
private void removeBumPriorityColumn(final Connection conn) {
try (PreparedStatement removeBumPriorityColumnPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`domain_router` DROP COLUMN `is_priority_bumpup`");) {
removeBumPriorityColumnPstmt.executeUpdate();
} catch (final SQLException e) {
e.printStackTrace();
throw new CloudRuntimeException("Adding redundancy to vpc, networks and vpc_offerings failed", e);
}
}
@Override
public File[] getCleanupScripts() {
final String script = Script.findScript("", "db/schema-451to460-cleanup.sql");

View File

@ -49,12 +49,6 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
@Column(name = "is_redundant_router")
boolean isRedundantRouter;
@Column(name = "priority")
int priority;
@Column(name = "is_priority_bumpup")
boolean isPriorityBumpUp;
@Column(name = "redundant_state")
@Enumerated(EnumType.STRING)
private RedundantState redundantState;
@ -75,28 +69,24 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
@Column(name = "vpc_id")
private Long vpcId;
public DomainRouterVO(long id, long serviceOfferingId, long elementId, String name, long templateId, HypervisorType hypervisorType, long guestOSId, long domainId,
long accountId, long userId, boolean isRedundantRouter, int priority, boolean isPriorityBumpUp, RedundantState redundantState, boolean haEnabled, boolean stopPending,
Long vpcId) {
public DomainRouterVO(final long id, final long serviceOfferingId, final long elementId, final String name, final long templateId, final HypervisorType hypervisorType, final long guestOSId, final long domainId,
final long accountId, final long userId, final boolean isRedundantRouter, final RedundantState redundantState, final boolean haEnabled, final boolean stopPending,
final Long vpcId) {
super(id, serviceOfferingId, name, name, Type.DomainRouter, templateId, hypervisorType, guestOSId, domainId, accountId, userId, haEnabled);
this.elementId = elementId;
this.isRedundantRouter = isRedundantRouter;
this.priority = priority;
this.redundantState = redundantState;
this.isPriorityBumpUp = isPriorityBumpUp;
this.stopPending = stopPending;
this.vpcId = vpcId;
}
public DomainRouterVO(long id, long serviceOfferingId, long elementId, String name, long templateId, HypervisorType hypervisorType, long guestOSId, long domainId,
long accountId, long userId, boolean isRedundantRouter, int priority, boolean isPriorityBumpUp, RedundantState redundantState, boolean haEnabled, boolean stopPending,
Type vmType, Long vpcId) {
public DomainRouterVO(final long id, final long serviceOfferingId, final long elementId, final String name, final long templateId, final HypervisorType hypervisorType, final long guestOSId, final long domainId,
final long accountId, final long userId, final boolean isRedundantRouter, final RedundantState redundantState, final boolean haEnabled, final boolean stopPending,
final Type vmType, final Long vpcId) {
super(id, serviceOfferingId, name, name, vmType, templateId, hypervisorType, guestOSId, domainId, accountId, userId, haEnabled);
this.elementId = elementId;
this.isRedundantRouter = isRedundantRouter;
this.priority = priority;
this.redundantState = redundantState;
this.isPriorityBumpUp = isPriorityBumpUp;
this.stopPending = stopPending;
this.vpcId = vpcId;
}
@ -105,15 +95,15 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
return elementId;
}
public void setPublicIpAddress(String publicIpAddress) {
public void setPublicIpAddress(final String publicIpAddress) {
this.publicIpAddress = publicIpAddress;
}
public void setPublicMacAddress(String publicMacAddress) {
public void setPublicMacAddress(final String publicMacAddress) {
this.publicMacAddress = publicMacAddress;
}
public void setPublicNetmask(String publicNetmask) {
public void setPublicNetmask(final String publicNetmask) {
this.publicNetmask = publicNetmask;
}
@ -144,16 +134,16 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
return role;
}
public void setRole(Role role) {
public void setRole(final Role role) {
this.role = role;
}
@Override
public boolean getIsRedundantRouter() {
return this.isRedundantRouter;
return isRedundantRouter;
}
public void setIsRedundantRouter(boolean isRedundantRouter) {
public void setIsRedundantRouter(final boolean isRedundantRouter) {
this.isRedundantRouter = isRedundantRouter;
}
@ -162,55 +152,39 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
return serviceOfferingId;
}
public int getPriority() {
return this.priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
@Override
public RedundantState getRedundantState() {
return this.redundantState;
return redundantState;
}
public void setRedundantState(RedundantState redundantState) {
public void setRedundantState(final RedundantState redundantState) {
this.redundantState = redundantState;
}
public boolean getIsPriorityBumpUp() {
return this.isPriorityBumpUp;
}
public void setIsPriorityBumpUp(boolean isPriorityBumpUp) {
this.isPriorityBumpUp = isPriorityBumpUp;
}
@Override
public boolean isStopPending() {
return this.stopPending;
return stopPending;
}
@Override
public void setStopPending(boolean stopPending) {
public void setStopPending(final boolean stopPending) {
this.stopPending = stopPending;
}
@Override
public String getTemplateVersion() {
return this.templateVersion;
return templateVersion;
}
public void setTemplateVersion(String templateVersion) {
public void setTemplateVersion(final String templateVersion) {
this.templateVersion = templateVersion;
}
public String getScriptsVersion() {
return this.scriptsVersion;
return scriptsVersion;
}
public void setScriptsVersion(String scriptsVersion) {
public void setScriptsVersion(final String scriptsVersion) {
this.scriptsVersion = scriptsVersion;
}

View File

@ -20,7 +20,6 @@ import java.util.HashMap;
import java.util.Map;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckVirtualMachineCommand;
@ -98,8 +97,6 @@ public interface MockVmManager extends Manager {
CheckRouterAnswer checkRouter(CheckRouterCommand cmd);
Answer bumpPriority(BumpUpPriorityCommand cmd);
Answer CleanupNetworkRules(CleanupNetworkRulesCmd cmd, SimulatorInfo info);
Answer scaleVm(ScaleVmCommand cmd);

View File

@ -31,7 +31,6 @@ import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
@ -110,12 +109,12 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
return true;
}
public String startVM(String vmName, NicTO[] nics, int cpuHz, long ramSize, String bootArgs, String hostGuid) {
public String startVM(final String vmName, final NicTO[] nics, final int cpuHz, final long ramSize, final String bootArgs, final String hostGuid) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
MockHost host = null;
@ -129,7 +128,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
vm = _mockVmDao.findByVmName(vmName);
txn.commit();
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to start VM " + vmName, ex);
} finally {
@ -139,9 +138,10 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
if (vm == null) {
int vncPort = 0;
if (vncPort < 0)
final int vncPort = 0;
if (vncPort < 0) {
return "Unable to allocate VNC port";
}
vm = new MockVMVO();
vm.setCpu(cpuHz);
vm.setMemory(ramSize);
@ -164,7 +164,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
txn.start();
vm = _mockVmDao.persist((MockVMVO)vm);
txn.commit();
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to save vm to db " + vm.getName(), ex);
} finally {
@ -180,7 +180,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
txn.start();
_mockVmDao.update(vm.getId(), (MockVMVO)vm);
txn.commit();
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to update vm " + vm.getName(), ex);
} finally {
@ -196,7 +196,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
String prvMac = null;
String prvNetMask = null;
for (NicTO nic : nics) {
for (final NicTO nic : nics) {
if (nic.getType() == TrafficType.Management) {
prvIp = nic.getIp();
prvMac = nic.getMac();
@ -208,9 +208,9 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
String name = null;
String vmType = null;
String url = null;
String[] args = bootArgs.trim().split(" ");
for (String arg : args) {
String[] params = arg.split("=");
final String[] args = bootArgs.trim().split(" ");
for (final String arg : args) {
final String[] params = arg.split("=");
if (params.length < 1) {
continue;
}
@ -235,18 +235,18 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Map<String, MockVMVO> getVms(String hostGuid) {
public Map<String, MockVMVO> getVms(final String hostGuid) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
List<MockVMVO> vms = _mockVmDao.findByHostGuid(hostGuid);
Map<String, MockVMVO> vmMap = new HashMap<String, MockVMVO>();
for (MockVMVO vm : vms) {
final List<MockVMVO> vms = _mockVmDao.findByHostGuid(hostGuid);
final Map<String, MockVMVO> vmMap = new HashMap<String, MockVMVO>();
for (final MockVMVO vm : vms) {
vmMap.put(vm.getName(), vm);
}
txn.commit();
return vmMap;
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to fetch vms from host " + hostGuid, ex);
} finally {
@ -257,52 +257,40 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public CheckRouterAnswer checkRouter(CheckRouterCommand cmd) {
String router_name = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
MockVm vm = _mockVmDao.findByVmName(router_name);
String args = vm.getBootargs();
public CheckRouterAnswer checkRouter(final CheckRouterCommand cmd) {
final String router_name = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
final MockVm vm = _mockVmDao.findByVmName(router_name);
final String args = vm.getBootargs();
if (args.indexOf("router_pr=100") > 0) {
s_logger.debug("Router priority is for MASTER");
CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: MASTER & Bumped: NO", true);
final CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: MASTER", true);
ans.setState(VirtualRouter.RedundantState.MASTER);
return ans;
} else {
s_logger.debug("Router priority is for BACKUP");
CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: BACKUP & Bumped: NO", true);
final CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: BACKUP", true);
ans.setState(VirtualRouter.RedundantState.BACKUP);
return ans;
}
}
@Override
public Answer bumpPriority(BumpUpPriorityCommand cmd) {
String router_name = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
MockVm vm = _mockVmDao.findByVmName(router_name);
String args = vm.getBootargs();
if (args.indexOf("router_pr=100") > 0) {
return new Answer(cmd, true, "Status: BACKUP & Bumped: YES");
} else {
return new Answer(cmd, true, "Status: MASTER & Bumped: YES");
}
}
@Override
public Map<String, PowerState> getVmStates(String hostGuid) {
public Map<String, PowerState> getVmStates(final String hostGuid) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
Map<String, PowerState> states = new HashMap<String, PowerState>();
List<MockVMVO> vms = _mockVmDao.findByHostGuid(hostGuid);
final Map<String, PowerState> states = new HashMap<String, PowerState>();
final List<MockVMVO> vms = _mockVmDao.findByHostGuid(hostGuid);
if (vms.isEmpty()) {
txn.commit();
return states;
}
for (MockVm vm : vms) {
for (final MockVm vm : vms) {
states.put(vm.getName(), vm.getPowerState());
}
txn.commit();
return states;
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to fetch vms from host " + hostGuid, ex);
} finally {
@ -328,11 +316,11 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Answer getVmStats(GetVmStatsCommand cmd) {
HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
List<String> vmNames = cmd.getVmNames();
for (String vmName : vmNames) {
VmStatsEntry entry = new VmStatsEntry(0, 0, 0, 0, "vm");
public Answer getVmStats(final GetVmStatsCommand cmd) {
final HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
final List<String> vmNames = cmd.getVmNames();
for (final String vmName : vmNames) {
final VmStatsEntry entry = new VmStatsEntry(0, 0, 0, 0, "vm");
entry.setNetworkReadKBs(32768); // default values 256 KBps
entry.setNetworkWriteKBs(16384);
entry.setCPUUtilization(10);
@ -343,18 +331,18 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public CheckVirtualMachineAnswer checkVmState(CheckVirtualMachineCommand cmd) {
public CheckVirtualMachineAnswer checkVmState(final CheckVirtualMachineCommand cmd) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
MockVMVO vm = _mockVmDao.findByVmName(cmd.getVmName());
final MockVMVO vm = _mockVmDao.findByVmName(cmd.getVmName());
if (vm == null) {
return new CheckVirtualMachineAnswer(cmd, "can't find vm:" + cmd.getVmName());
}
txn.commit();
return new CheckVirtualMachineAnswer(cmd, vm.getPowerState(), vm.getVncPort());
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to fetch vm state " + cmd.getVmName(), ex);
} finally {
@ -365,9 +353,9 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public StartAnswer startVM(StartCommand cmd, SimulatorInfo info) {
VirtualMachineTO vm = cmd.getVirtualMachine();
String result = startVM(vm.getName(), vm.getNics(), vm.getCpus() * vm.getMaxSpeed(), vm.getMaxRam(), vm.getBootArgs(), info.getHostUuid());
public StartAnswer startVM(final StartCommand cmd, final SimulatorInfo info) {
final VirtualMachineTO vm = cmd.getVirtualMachine();
final String result = startVM(vm.getName(), vm.getNics(), vm.getCpus() * vm.getMaxSpeed(), vm.getMaxRam(), vm.getBootArgs(), info.getHostUuid());
if (result != null) {
return new StartAnswer(cmd, result);
} else {
@ -376,23 +364,23 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public CheckSshAnswer checkSshCommand(CheckSshCommand cmd) {
public CheckSshAnswer checkSshCommand(final CheckSshCommand cmd) {
return new CheckSshAnswer(cmd);
}
@Override
public MigrateAnswer Migrate(MigrateCommand cmd, SimulatorInfo info) {
public MigrateAnswer Migrate(final MigrateCommand cmd, final SimulatorInfo info) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
String vmName = cmd.getVmName();
String destGuid = cmd.getHostGuid();
MockVMVO vm = _mockVmDao.findByVmNameAndHost(vmName, info.getHostUuid());
final String vmName = cmd.getVmName();
final String destGuid = cmd.getHostGuid();
final MockVMVO vm = _mockVmDao.findByVmNameAndHost(vmName, info.getHostUuid());
if (vm == null) {
return new MigrateAnswer(cmd, false, "can't find vm:" + vmName + " on host:" + info.getHostUuid(), null);
}
MockHost destHost = _mockHostDao.findByGuid(destGuid);
final MockHost destHost = _mockHostDao.findByGuid(destGuid);
if (destHost == null) {
return new MigrateAnswer(cmd, false, "can;t find host:" + info.getHostUuid(), null);
}
@ -400,7 +388,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
_mockVmDao.update(vm.getId(), vm);
txn.commit();
return new MigrateAnswer(cmd, true, null, 0);
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to migrate vm " + cmd.getVmName(), ex);
} finally {
@ -411,15 +399,15 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public PrepareForMigrationAnswer prepareForMigrate(PrepareForMigrationCommand cmd) {
public PrepareForMigrationAnswer prepareForMigrate(final PrepareForMigrationCommand cmd) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
VirtualMachineTO vmTo = cmd.getVirtualMachine();
final VirtualMachineTO vmTo = cmd.getVirtualMachine();
try {
txn.start();
MockVMVO vm = _mockVmDao.findById(vmTo.getId());
final MockVMVO vm = _mockVmDao.findById(vmTo.getId());
_mockVmDao.update(vm.getId(), vm);
txn.commit();
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to find vm " + vmTo.getName(), ex);
} finally {
@ -431,25 +419,25 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Answer setVmData(VmDataCommand cmd) {
public Answer setVmData(final VmDataCommand cmd) {
return new Answer(cmd);
}
@Override
public Answer CleanupNetworkRules(CleanupNetworkRulesCmd cmd, SimulatorInfo info) {
public Answer CleanupNetworkRules(final CleanupNetworkRulesCmd cmd, final SimulatorInfo info) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
List<MockSecurityRulesVO> rules = _mockSecurityDao.findByHost(info.getHostUuid());
for (MockSecurityRulesVO rule : rules) {
MockVMVO vm = _mockVmDao.findByVmNameAndHost(rule.getVmName(), info.getHostUuid());
final List<MockSecurityRulesVO> rules = _mockSecurityDao.findByHost(info.getHostUuid());
for (final MockSecurityRulesVO rule : rules) {
final MockVMVO vm = _mockVmDao.findByVmNameAndHost(rule.getVmName(), info.getHostUuid());
if (vm == null) {
_mockSecurityDao.remove(rule.getId());
}
}
txn.commit();
return new Answer(cmd);
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to clean up rules", ex);
} finally {
@ -460,28 +448,28 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Answer scaleVm(ScaleVmCommand cmd) {
public Answer scaleVm(final ScaleVmCommand cmd) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Answer plugSecondaryIp(NetworkRulesVmSecondaryIpCommand cmd) {
public Answer plugSecondaryIp(final NetworkRulesVmSecondaryIpCommand cmd) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Answer createVmSnapshot(CreateVMSnapshotCommand cmd) {
String vmName = cmd.getVmName();
String vmSnapshotName = cmd.getTarget().getSnapshotName();
public Answer createVmSnapshot(final CreateVMSnapshotCommand cmd) {
final String vmName = cmd.getVmName();
final String vmSnapshotName = cmd.getTarget().getSnapshotName();
s_logger.debug("Created snapshot " + vmSnapshotName + " for vm " + vmName);
return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
}
@Override
public Answer deleteVmSnapshot(DeleteVMSnapshotCommand cmd) {
String vm = cmd.getVmName();
String snapshotName = cmd.getTarget().getSnapshotName();
public Answer deleteVmSnapshot(final DeleteVMSnapshotCommand cmd) {
final String vm = cmd.getVmName();
final String snapshotName = cmd.getTarget().getSnapshotName();
if (_mockVmDao.findByVmName(cmd.getVmName()) == null) {
return new DeleteVMSnapshotAnswer(cmd, false, "No VM by name " + cmd.getVmName());
}
@ -490,10 +478,10 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Answer revertVmSnapshot(RevertToVMSnapshotCommand cmd) {
String vm = cmd.getVmName();
String snapshot = cmd.getTarget().getSnapshotName();
MockVMVO vmVo = _mockVmDao.findByVmName(cmd.getVmName());
public Answer revertVmSnapshot(final RevertToVMSnapshotCommand cmd) {
final String vm = cmd.getVmName();
final String snapshot = cmd.getTarget().getSnapshotName();
final MockVMVO vmVo = _mockVmDao.findByVmName(cmd.getVmName());
if (vmVo == null) {
return new RevertToVMSnapshotAnswer(cmd, false, "No VM by name " + cmd.getVmName());
}
@ -502,12 +490,12 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public StopAnswer stopVM(StopCommand cmd) {
public StopAnswer stopVM(final StopCommand cmd) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
String vmName = cmd.getVmName();
MockVm vm = _mockVmDao.findByVmName(vmName);
final String vmName = cmd.getVmName();
final MockVm vm = _mockVmDao.findByVmName(vmName);
if (vm != null) {
vm.setPowerState(PowerState.PowerOff);
_mockVmDao.update(vm.getId(), (MockVMVO)vm);
@ -518,7 +506,7 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
txn.commit();
return new StopAnswer(cmd, null, true);
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("unable to stop vm " + cmd.getVmName(), ex);
} finally {
@ -529,33 +517,33 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public RebootAnswer rebootVM(RebootCommand cmd) {
public RebootAnswer rebootVM(final RebootCommand cmd) {
return new RebootAnswer(cmd, "Rebooted " + cmd.getVmName(), true);
}
@Override
public Answer getVncPort(GetVncPortCommand cmd) {
public Answer getVncPort(final GetVncPortCommand cmd) {
return new GetVncPortAnswer(cmd, 0);
}
@Override
public Answer CheckConsoleProxyLoad(CheckConsoleProxyLoadCommand cmd) {
public Answer CheckConsoleProxyLoad(final CheckConsoleProxyLoadCommand cmd) {
return Answer.createUnsupportedCommandAnswer(cmd);
}
@Override
public Answer WatchConsoleProxyLoad(WatchConsoleProxyLoadCommand cmd) {
public Answer WatchConsoleProxyLoad(final WatchConsoleProxyLoadCommand cmd) {
return Answer.createUnsupportedCommandAnswer(cmd);
}
@Override
public GetDomRVersionAnswer getDomRVersion(GetDomRVersionCmd cmd) {
String template_version = "CloudStack Release "+ NetworkOrchestrationService.MinVRVersion.defaultValue();
public GetDomRVersionAnswer getDomRVersion(final GetDomRVersionCmd cmd) {
final String template_version = "CloudStack Release "+ NetworkOrchestrationService.MinVRVersion.defaultValue();
return new GetDomRVersionAnswer(cmd, null, template_version, UUID.randomUUID().toString());
}
@Override
public SecurityGroupRuleAnswer AddSecurityGroupRules(SecurityGroupRulesCmd cmd, SimulatorInfo info) {
public SecurityGroupRuleAnswer AddSecurityGroupRules(final SecurityGroupRulesCmd cmd, final SimulatorInfo info) {
if (!info.isEnabled()) {
return new SecurityGroupRuleAnswer(cmd, false, "Disabled", SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL);
}
@ -575,11 +563,11 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
return new SecurityGroupRuleAnswer(cmd);
}
private boolean logSecurityGroupAction(SecurityGroupRulesCmd cmd, Ternary<String, Long, Long> rule) {
private boolean logSecurityGroupAction(final SecurityGroupRulesCmd cmd, final Ternary<String, Long, Long> rule) {
String action = ", do nothing";
String reason = ", reason=";
Long currSeqnum = rule == null ? null : rule.third();
String currSig = rule == null ? null : rule.first();
final Long currSeqnum = rule == null ? null : rule.third();
final String currSig = rule == null ? null : rule.first();
boolean updateSeqnoAndSig = false;
if (currSeqnum != null) {
if (cmd.getSeqNum() > currSeqnum) {
@ -623,26 +611,26 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
}
@Override
public Answer SavePassword(SavePasswordCommand cmd) {
public Answer SavePassword(final SavePasswordCommand cmd) {
return new Answer(cmd);
}
@Override
public HashMap<String, Pair<Long, Long>> syncNetworkGroups(SimulatorInfo info) {
HashMap<String, Pair<Long, Long>> maps = new HashMap<String, Pair<Long, Long>>();
public HashMap<String, Pair<Long, Long>> syncNetworkGroups(final SimulatorInfo info) {
final HashMap<String, Pair<Long, Long>> maps = new HashMap<String, Pair<Long, Long>>();
Map<String, Ternary<String, Long, Long>> rules = _securityRules.get(info.getHostUuid());
final Map<String, Ternary<String, Long, Long>> rules = _securityRules.get(info.getHostUuid());
if (rules == null) {
return maps;
}
for (Map.Entry<String, Ternary<String, Long, Long>> rule : rules.entrySet()) {
for (final Map.Entry<String, Ternary<String, Long, Long>> rule : rules.entrySet()) {
maps.put(rule.getKey(), new Pair<Long, Long>(rule.getValue().second(), rule.getValue().third()));
}
return maps;
}
@Override
public Answer fence(FenceCommand cmd) {
public Answer fence(final FenceCommand cmd) {
return new FenceAnswer(cmd);
}
}

View File

@ -27,20 +27,17 @@ import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.agent.api.routing.SetMonitorServiceCommand;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.storage.command.DeleteCommand;
import org.apache.cloudstack.storage.command.DownloadCommand;
import org.apache.cloudstack.storage.command.DownloadProgressCommand;
import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.CheckRouterCommand;
@ -75,6 +72,7 @@ import com.cloud.agent.api.PvlanSetupCommand;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RevertToVMSnapshotCommand;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.agent.api.SecStorageSetupCommand;
import com.cloud.agent.api.SecStorageVMSetupCommand;
import com.cloud.agent.api.SecurityGroupRulesCmd;
@ -95,6 +93,7 @@ import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetFirewallRulesCommand;
import com.cloud.agent.api.routing.SetMonitorServiceCommand;
import com.cloud.agent.api.routing.SetNetworkACLCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
@ -113,7 +112,6 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.api.commands.CleanupSimulatorMockCmd;
import com.cloud.api.commands.ConfigureSimulatorCmd;
import com.cloud.api.commands.QuerySimulatorMockCmd;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.resource.SimulatorStorageProcessor;
import com.cloud.serializer.GsonHelper;
import com.cloud.simulator.MockConfigurationVO;
@ -153,9 +151,9 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
protected StorageSubsystemCommandHandler storageHandler;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
SimulatorStorageProcessor processor = new SimulatorStorageProcessor(this);
this.storageHandler = new StorageSubsystemCommandHandlerBase(processor);
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
final SimulatorStorageProcessor processor = new SimulatorStorageProcessor(this);
storageHandler = new StorageSubsystemCommandHandlerBase(processor);
return true;
}
@ -191,7 +189,7 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
@Override
public List<Class<?>> getCommands() {
List<Class<?>> cmdList = new ArrayList<Class<?>>();
final List<Class<?>> cmdList = new ArrayList<Class<?>>();
cmdList.add(ConfigureSimulatorCmd.class);
cmdList.add(QuerySimulatorMockCmd.class);
cmdList.add(CleanupSimulatorMockCmd.class);
@ -200,48 +198,48 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
@DB
@Override
public Answer simulate(Command cmd, String hostGuid) {
public Answer simulate(final Command cmd, final String hostGuid) {
Answer answer = null;
Exception exception = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
MockHost host = _mockHost.findByGuid(hostGuid);
final MockHost host = _mockHost.findByGuid(hostGuid);
String cmdName = cmd.toString();
int index = cmdName.lastIndexOf(".");
final int index = cmdName.lastIndexOf(".");
if (index != -1) {
cmdName = cmdName.substring(index + 1);
}
SimulatorInfo info = new SimulatorInfo();
final SimulatorInfo info = new SimulatorInfo();
info.setHostUuid(hostGuid);
MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName);
final MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName);
if (config != null && (config.getCount() == null || config.getCount().intValue() > 0)) {
Map<String, String> configParameters = config.getParameters();
for (Map.Entry<String, String> entry : configParameters.entrySet()) {
final Map<String, String> configParameters = config.getParameters();
for (final Map.Entry<String, String> entry : configParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase("enabled")) {
info.setEnabled(Boolean.parseBoolean(entry.getValue()));
} else if (entry.getKey().equalsIgnoreCase("timeout")) {
try {
info.setTimeout(Integer.valueOf(entry.getValue()));
} catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
s_logger.debug("invalid timeout parameter: " + e.toString());
}
}
if (entry.getKey().equalsIgnoreCase("wait")) {
try {
int wait = Integer.valueOf(entry.getValue());
final int wait = Integer.valueOf(entry.getValue());
Thread.sleep(wait);
} catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
s_logger.debug("invalid wait parameter: " + e.toString());
} catch (InterruptedException e) {
} catch (final InterruptedException e) {
s_logger.debug("thread is interrupted: " + e.toString());
}
}
if (entry.getKey().equalsIgnoreCase("result")) {
String value = entry.getValue();
final String value = entry.getValue();
if (value.equalsIgnoreCase("fail")) {
answer = new Answer(cmd, false, "Simulated failure");
} else if (value.equalsIgnoreCase("fault")) {
@ -255,20 +253,20 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
if (answer == null) {
String message = config.getJsonResponse();
final String message = config.getJsonResponse();
if (message != null) {
// json response looks like {"<Type>":....}
String objectType = message.split(":")[0].substring(2).replace("\"", "");
String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
final String objectType = message.split(":")[0].substring(2).replace("\"", "");
final String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
if (objectType != null) {
Class<?> clz = null;
try {
clz = Class.forName(objectType);
} catch (ClassNotFoundException e) {
} catch (final ClassNotFoundException e) {
}
if (clz != null) {
StringReader reader = new StringReader(objectData);
JsonReader jsonReader = new JsonReader(reader);
final StringReader reader = new StringReader(objectData);
final JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
answer = (Answer)s_gson.fromJson(jsonReader, clz);
}
@ -378,8 +376,6 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
answer = _mockVmMgr.getVmStats((GetVmStatsCommand)cmd);
} else if (cmd instanceof CheckRouterCommand) {
answer = _mockVmMgr.checkRouter((CheckRouterCommand)cmd);
} else if (cmd instanceof BumpUpPriorityCommand) {
answer = _mockVmMgr.bumpPriority((BumpUpPriorityCommand)cmd);
} else if (cmd instanceof GetDomRVersionCmd) {
answer = _mockVmMgr.getDomRVersion((GetDomRVersionCmd)cmd);
} else if (cmd instanceof CopyVolumeCommand) {
@ -419,7 +415,7 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
} else if (cmd instanceof PvlanSetupCommand) {
answer = _mockNetworkMgr.setupPVLAN((PvlanSetupCommand)cmd);
} else if (cmd instanceof StorageSubSystemCommand) {
answer = this.storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
answer = storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
} else if (cmd instanceof FenceCommand) {
answer = _mockVmMgr.fence((FenceCommand)cmd);
} else if (cmd instanceof GetRouterAlertsCommand || cmd instanceof VpnUsersCfgCommand || cmd instanceof RemoteAccessVpnCfgCommand || cmd instanceof SetMonitorServiceCommand || cmd instanceof AggregationControlCommand ||
@ -431,7 +427,7 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
}
if (config != null && (config.getCount() != null && config.getCount().intValue() > 0)) {
if (config != null && config.getCount() != null && config.getCount().intValue() > 0) {
if (answer != null) {
config.setCount(config.getCount().intValue() - 1);
_mockConfigDao.update(config.getId(), config);
@ -439,7 +435,7 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
return answer;
} catch (Exception e) {
} catch (final Exception e) {
s_logger.error("Failed execute cmd: ", e);
txn.rollback();
return new Answer(cmd, false, e.toString());
@ -451,29 +447,29 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
@Override
public StoragePoolInfo getLocalStorage(String hostGuid) {
public StoragePoolInfo getLocalStorage(final String hostGuid) {
return _mockStorageMgr.getLocalStorage(hostGuid);
}
@Override
public Map<String, PowerState> getVmStates(String hostGuid) {
public Map<String, PowerState> getVmStates(final String hostGuid) {
return _mockVmMgr.getVmStates(hostGuid);
}
@Override
public Map<String, MockVMVO> getVms(String hostGuid) {
public Map<String, MockVMVO> getVms(final String hostGuid) {
return _mockVmMgr.getVms(hostGuid);
}
@Override
public HashMap<String, Pair<Long, Long>> syncNetworkGroups(String hostGuid) {
SimulatorInfo info = new SimulatorInfo();
public HashMap<String, Pair<Long, Long>> syncNetworkGroups(final String hostGuid) {
final SimulatorInfo info = new SimulatorInfo();
info.setHostUuid(hostGuid);
return _mockVmMgr.syncNetworkGroups(info);
}
@Override
public Long configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values, Integer count, String jsonResponse) {
public Long configureSimulator(final Long zoneId, final Long podId, final Long clusterId, final Long hostId, final String command, final String values, final Integer count, final String jsonResponse) {
Long id = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
@ -499,7 +495,7 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
txn.commit();
}
id = config.getId();
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to configure simulator mock because of " + ex.getMessage(), ex);
} finally {
@ -511,12 +507,12 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
@Override
public MockConfigurationVO querySimulatorMock(Long id) {
public MockConfigurationVO querySimulatorMock(final Long id) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
return _mockConfigDao.findById(id);
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to query simulator mock because of " + ex.getMessage(), ex);
} finally {
@ -527,19 +523,19 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
@Override
public boolean clearSimulatorMock(Long id) {
public boolean clearSimulatorMock(final Long id) {
boolean status = false;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
MockConfigurationVO config = _mockConfigDao.findById(id);
final MockConfigurationVO config = _mockConfigDao.findById(id);
if (config != null) {
config.setRemoved(new Date());
_mockConfigDao.update(config.getId(), config);
status = true;
txn.commit();
}
} catch (Exception ex) {
} catch (final Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to cleanup simulator mock because of " + ex.getMessage(), ex);
} finally {

View File

@ -27,7 +27,6 @@ import java.util.Random;
import javax.inject.Inject;
import com.cloud.user.dao.UserDao;
import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
@ -78,6 +77,7 @@ import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@ -87,7 +87,6 @@ import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineName;
@ -150,28 +149,28 @@ public class LoadBalanceRuleHandler {
private final String _instance;
private final Account _systemAcct;
public LoadBalanceRuleHandler(ServiceOfferingVO elasticLbVmOffering, String instance, Account systemAcct) {
this._elasticLbVmOffering = elasticLbVmOffering;
this._instance = instance;
this._systemAcct = systemAcct;
public LoadBalanceRuleHandler(final ServiceOfferingVO elasticLbVmOffering, final String instance, final Account systemAcct) {
_elasticLbVmOffering = elasticLbVmOffering;
_instance = instance;
_systemAcct = systemAcct;
}
public void handleDeleteLoadBalancerRule(LoadBalancer lb, long userId, Account caller) {
List<LoadBalancerVO> remainingLbs = _loadBalancerDao.listByIpAddress(lb.getSourceIpAddressId());
public void handleDeleteLoadBalancerRule(final LoadBalancer lb, final long userId, final Account caller) {
final List<LoadBalancerVO> remainingLbs = _loadBalancerDao.listByIpAddress(lb.getSourceIpAddressId());
if (remainingLbs.size() == 0) {
s_logger.debug("ELB mgr: releasing ip " + lb.getSourceIpAddressId() + " since no LB rules remain for this ip address");
releaseIp(lb.getSourceIpAddressId(), userId, caller);
}
}
public LoadBalancer handleCreateLoadBalancerRule(CreateLoadBalancerRuleCmd lb, Account account, long networkId) throws InsufficientAddressCapacityException,
public LoadBalancer handleCreateLoadBalancerRule(final CreateLoadBalancerRuleCmd lb, Account account, final long networkId) throws InsufficientAddressCapacityException,
NetworkRuleConflictException {
//this part of code is executed when the LB provider is Elastic Load Balancer vm
if (!_networkModel.isProviderSupportServiceInNetwork(lb.getNetworkId(), Service.Lb, Provider.ElasticLoadBalancerVm)) {
return null;
}
Long ipId = lb.getSourceIpAddressId();
final Long ipId = lb.getSourceIpAddressId();
if (ipId != null) {
return null;
}
@ -190,19 +189,19 @@ public class LoadBalanceRuleHandler {
}
}
private DomainRouterVO deployLoadBalancerVM(Long networkId, IPAddressVO ipAddr) {
NetworkVO network = _networkDao.findById(networkId);
DataCenter dc = _dcDao.findById(network.getDataCenterId());
Long podId = getPodIdForDirectIp(ipAddr);
Pod pod = podId == null ? null : _podDao.findById(podId);
Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(1);
private DomainRouterVO deployLoadBalancerVM(final Long networkId, final IPAddressVO ipAddr) {
final NetworkVO network = _networkDao.findById(networkId);
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
final Long podId = getPodIdForDirectIp(ipAddr);
final Pod pod = podId == null ? null : _podDao.findById(podId);
final Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(1);
params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true);
Account owner = _accountService.getActiveAccountByName("system", new Long(1));
DeployDestination dest = new DeployDestination(dc, pod, null, null);
final Account owner = _accountService.getActiveAccountByName("system", new Long(1));
final DeployDestination dest = new DeployDestination(dc, pod, null, null);
s_logger.debug("About to deploy ELB vm ");
try {
DomainRouterVO elbVm = deployELBVm(network, dest, owner, params);
final DomainRouterVO elbVm = deployELBVm(network, dest, owner, params);
if (elbVm == null) {
throw new InvalidParameterValueException("Could not deploy or find existing ELB VM");
}
@ -210,19 +209,19 @@ public class LoadBalanceRuleHandler {
return elbVm;
} catch (Throwable t) {
} catch (final Throwable t) {
s_logger.warn("Error while deploying ELB VM: ", t);
return null;
}
}
private DomainRouterVO deployELBVm(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws ConcurrentOperationException,
private DomainRouterVO deployELBVm(Network guestNetwork, final DeployDestination dest, Account owner, final Map<Param, Object> params) throws ConcurrentOperationException,
InsufficientCapacityException {
long dcId = dest.getDataCenter().getId();
final long dcId = dest.getDataCenter().getId();
// lock guest network
Long guestNetworkId = guestNetwork.getId();
final Long guestNetworkId = guestNetwork.getId();
guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
if (guestNetwork == null) {
@ -247,30 +246,30 @@ public class LoadBalanceRuleHandler {
plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null);
if (elbVm == null) {
long id = _routerDao.getNextInSequence(Long.class, "id");
final long id = _routerDao.getNextInSequence(Long.class, "id");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating the ELB vm " + id);
}
List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
NetworkOffering controlOffering = offerings.get(0);
Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
final List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
final NetworkOffering controlOffering = offerings.get(0);
final Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(2);
NicProfile guestNic = new NicProfile();
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(2);
final NicProfile guestNic = new NicProfile();
guestNic.setDefaultNic(true);
networks.put(controlConfig, new ArrayList<NicProfile>());
networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
final VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
String typeString = "ElasticLoadBalancerVm";
Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork);
PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString);
final String typeString = "ElasticLoadBalancerVm";
final Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork);
final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString);
if (provider == null) {
throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId);
}
VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm);
final VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm);
if (vrProvider == null) {
throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId());
}
@ -281,8 +280,8 @@ public class LoadBalanceRuleHandler {
}
elbVm = new DomainRouterVO(id, _elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX),
template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, 0, false, RedundantState.UNKNOWN,
_elasticLbVmOffering.getOfferHA(), false, VirtualMachine.Type.ElasticLoadBalancerVm, null);
template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN,
_elasticLbVmOffering.getOfferHA(), false, null);
elbVm.setRole(Role.LB);
elbVm = _routerDao.persist(elbVm);
_itMgr.allocate(elbVm.getInstanceName(), template, _elasticLbVmOffering, networks, plan, null);
@ -290,9 +289,9 @@ public class LoadBalanceRuleHandler {
//TODO: create usage stats
}
State state = elbVm.getState();
final State state = elbVm.getState();
if (state != State.Running) {
elbVm = this.start(elbVm, params);
elbVm = start(elbVm, params);
}
return elbVm;
@ -301,17 +300,17 @@ public class LoadBalanceRuleHandler {
}
}
private void releaseIp(long ipId, long userId, Account caller) {
private void releaseIp(final long ipId, final long userId, final Account caller) {
s_logger.info("ELB: Release public IP for loadbalancing " + ipId);
IPAddressVO ipvo = _ipAddressDao.findById(ipId);
final IPAddressVO ipvo = _ipAddressDao.findById(ipId);
ipvo.setAssociatedWithNetworkId(null);
_ipAddressDao.update(ipvo.getId(), ipvo);
_ipAddrMgr.disassociatePublicIpAddress(ipId, userId, caller);
_ipAddressDao.unassignIpAddress(ipId);
}
protected Long getPodIdForDirectIp(IPAddressVO ipAddr) {
PodVlanMapVO podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ipAddr.getVlanId());
protected Long getPodIdForDirectIp(final IPAddressVO ipAddr) {
final PodVlanMapVO podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ipAddr.getVlanId());
if (podVlanMaps == null) {
return null;
} else {
@ -319,7 +318,7 @@ public class LoadBalanceRuleHandler {
}
}
private LoadBalancer handleCreateLoadBalancerRuleWithLock(CreateLoadBalancerRuleCmd lb, Account account, long networkId) throws InsufficientAddressCapacityException,
private LoadBalancer handleCreateLoadBalancerRuleWithLock(final CreateLoadBalancerRuleCmd lb, final Account account, final long networkId) throws InsufficientAddressCapacityException,
NetworkRuleConflictException {
Long ipId = null;
boolean newIp = false;
@ -331,7 +330,7 @@ public class LoadBalanceRuleHandler {
throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(lb);
} else {
s_logger.debug("Could not find any existing frontend ips for this account for this LB rule, acquiring a new frontent IP for ELB");
PublicIp ip = allocDirectIp(account, networkId);
final PublicIp ip = allocDirectIp(account, networkId);
ipId = ip.getId();
newIp = true;
}
@ -344,7 +343,7 @@ public class LoadBalanceRuleHandler {
throw new NetworkRuleConflictException("ELB: Found existing load balancers matching requested new LB");
}
IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
final IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
LoadBalancer result = null;
try {
@ -352,7 +351,7 @@ public class LoadBalanceRuleHandler {
result = _lbMgr.createPublicLoadBalancer(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourcePortStart(), lb.getDefaultPortStart(), ipId.longValue(),
lb.getProtocol(), lb.getAlgorithm(), false, CallContext.current(), lb.getLbProtocol(), true);
} catch (NetworkRuleConflictException e) {
} catch (final NetworkRuleConflictException e) {
s_logger.warn("Failed to create LB rule, not continuing with ELB deployment");
if (newIp) {
releaseIp(ipId, CallContext.current().getCallingUserId(), account);
@ -367,15 +366,16 @@ public class LoadBalanceRuleHandler {
if (elbVm == null) {
elbVm = deployLoadBalancerVM(networkId, ipAddr);
if (elbVm == null) {
Network network = _networkModel.getNetwork(networkId);
final Network network = _networkModel.getNetwork(networkId);
s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName());
if (newIp)
if (newIp) {
releaseIp(ipId, CallContext.current().getCallingUserId(), account);
}
}
}
} else {
ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId);
final ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId);
if (elbVmMap != null) {
elbVm = _routerDao.findById(elbVmMap.getElbVmId());
}
@ -388,20 +388,20 @@ public class LoadBalanceRuleHandler {
return null;
}
ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId());
final ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId());
_elbVmMapDao.persist(mapping);
return result;
}
private void throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(CreateLoadBalancerRuleCmd lb) {
List<LoadBalancerVO> existingLbs = findExistingLoadBalancers(lb.getName(), null, lb.getAccountId(), lb.getDomainId(), null);
private void throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(final CreateLoadBalancerRuleCmd lb) {
final List<LoadBalancerVO> existingLbs = findExistingLoadBalancers(lb.getName(), null, lb.getAccountId(), lb.getDomainId(), null);
if (existingLbs != null) {
throw new InvalidParameterValueException("Supplied LB name " + lb.getName() + " is not associated with IP " + lb.getSourceIpAddressId());
}
}
protected List<LoadBalancerVO> findExistingLoadBalancers(String lbName, Long ipId, Long accountId, Long domainId, Integer publicPort) {
SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
protected List<LoadBalancerVO> findExistingLoadBalancers(final String lbName, final Long ipId, final Long accountId, final Long domainId, final Integer publicPort) {
final SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
@ -414,7 +414,7 @@ public class LoadBalanceRuleHandler {
if (publicPort != null) {
sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
}
SearchCriteria<LoadBalancerVO> sc = sb.create();
final SearchCriteria<LoadBalancerVO> sc = sb.create();
sc.setParameters("name", lbName);
sc.setParameters("accountId", accountId);
if (ipId != null) {
@ -426,7 +426,7 @@ public class LoadBalanceRuleHandler {
if (publicPort != null) {
sc.setParameters("publicPort", publicPort);
}
List<LoadBalancerVO> lbs = _lbDao.search(sc, null);
final List<LoadBalancerVO> lbs = _lbDao.search(sc, null);
return lbs == null || lbs.size() == 0 ? null : lbs;
}
@ -435,11 +435,11 @@ public class LoadBalanceRuleHandler {
private PublicIp allocDirectIp(final Account account, final long guestNetworkId) throws InsufficientAddressCapacityException {
return Transaction.execute(new TransactionCallbackWithException<PublicIp, InsufficientAddressCapacityException>() {
@Override
public PublicIp doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
Network frontEndNetwork = _networkModel.getNetwork(guestNetworkId);
public PublicIp doInTransaction(final TransactionStatus status) throws InsufficientAddressCapacityException {
final Network frontEndNetwork = _networkModel.getNetwork(guestNetworkId);
PublicIp ip = _ipAddrMgr.assignPublicIpAddress(frontEndNetwork.getDataCenterId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null, true);
IPAddressVO ipvo = _ipAddressDao.findById(ip.getId());
final PublicIp ip = _ipAddrMgr.assignPublicIpAddress(frontEndNetwork.getDataCenterId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null, true);
final IPAddressVO ipvo = _ipAddressDao.findById(ip.getId());
ipvo.setAssociatedWithNetworkId(frontEndNetwork.getId());
_ipAddressDao.update(ipvo.getId(), ipvo);
s_logger.info("Acquired frontend IP for ELB " + ip);
@ -449,11 +449,11 @@ public class LoadBalanceRuleHandler {
});
}
protected DomainRouterVO findElbVmWithCapacity(IPAddressVO ipAddr) {
List<DomainRouterVO> unusedElbVms = _elbVmMapDao.listUnusedElbVms();
protected DomainRouterVO findElbVmWithCapacity(final IPAddressVO ipAddr) {
final List<DomainRouterVO> unusedElbVms = _elbVmMapDao.listUnusedElbVms();
if (unusedElbVms.size() > 0) {
List<DomainRouterVO> candidateVms = new ArrayList<DomainRouterVO>();
for (DomainRouterVO candidateVm : unusedElbVms) {
final List<DomainRouterVO> candidateVms = new ArrayList<DomainRouterVO>();
for (final DomainRouterVO candidateVm : unusedElbVms) {
addCandidateVmIsPodIpMatches(candidateVm, getPodIdForDirectIp(ipAddr), candidateVms);
}
return candidateVms.size() == 0 ? null : candidateVms.get(new Random().nextInt(candidateVms.size()));
@ -461,13 +461,13 @@ public class LoadBalanceRuleHandler {
return null;
}
protected static void addCandidateVmIsPodIpMatches(DomainRouterVO candidateVm, Long podIdForDirectIp, List<DomainRouterVO> candidateVms) {
protected static void addCandidateVmIsPodIpMatches(final DomainRouterVO candidateVm, final Long podIdForDirectIp, final List<DomainRouterVO> candidateVms) {
if (candidateVm.getPodIdToDeployIn().equals(podIdForDirectIp)) {
candidateVms.add(candidateVm);
}
}
protected DomainRouterVO start(DomainRouterVO elbVm, Map<Param, Object> params) throws ConcurrentOperationException {
protected DomainRouterVO start(final DomainRouterVO elbVm, final Map<Param, Object> params) throws ConcurrentOperationException {
s_logger.debug("Starting ELB VM " + elbVm);
_itMgr.start(elbVm.getUuid(), params);
return _routerDao.findById(elbVm.getId());

View File

@ -27,7 +27,6 @@ import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.user.dao.UserDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
@ -91,12 +90,13 @@ import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.resource.ResourceManager;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.Storage;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
@ -170,13 +170,13 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
UserDao _userDao;
@Override
public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) {
public boolean finalizeVirtualMachineProfile(final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context) {
//Internal LB vm starts up with 2 Nics
//Nic #1 - Guest Nic with IP address that would act as the LB entry point
//Nic #2 - Control/Management Nic
StringBuilder buf = profile.getBootArgsBuilder();
final StringBuilder buf = profile.getBootArgsBuilder();
buf.append(" template=domP");
buf.append(" name=").append(profile.getHostName());
@ -187,8 +187,8 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
NicProfile controlNic = null;
Network guestNetwork = null;
for (NicProfile nic : profile.getNics()) {
int deviceId = nic.getDeviceId();
for (final NicProfile nic : profile.getNics()) {
final int deviceId = nic.getDeviceId();
buf.append(" eth").append(deviceId).append("ip=").append(nic.getIp4Address());
buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
@ -225,13 +225,13 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
if (guestNetwork != null) {
String domain = guestNetwork.getNetworkDomain();
final String domain = guestNetwork.getNetworkDomain();
if (domain != null) {
buf.append(" domain=" + domain);
}
}
String type = "ilbvm";
final String type = "ilbvm";
buf.append(" type=" + type);
if (s_logger.isDebugEnabled()) {
@ -242,13 +242,13 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context)
public boolean finalizeDeployment(final Commands cmds, final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context)
throws ResourceUnavailableException {
DomainRouterVO internalLbVm = _internalLbVmDao.findById(profile.getId());
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(profile.getId());
List<NicProfile> nics = profile.getNics();
for (NicProfile nic : nics) {
final List<NicProfile> nics = profile.getNics();
for (final NicProfile nic : nics) {
if (nic.getTrafficType() == TrafficType.Control) {
internalLbVm.setPrivateIpAddress(nic.getIp4Address());
internalLbVm.setPrivateMacAddress(nic.getMacAddress());
@ -261,14 +261,14 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Commands cmds, ReservationContext context) {
public boolean finalizeStart(final VirtualMachineProfile profile, final long hostId, final Commands cmds, final ReservationContext context) {
DomainRouterVO internalLbVm = _internalLbVmDao.findById(profile.getId());
boolean result = true;
Answer answer = cmds.getAnswer("checkSsh");
if (answer != null && answer instanceof CheckSshAnswer) {
CheckSshAnswer sshAnswer = (CheckSshAnswer)answer;
final CheckSshAnswer sshAnswer = (CheckSshAnswer)answer;
if (sshAnswer == null || !sshAnswer.getResult()) {
s_logger.warn("Unable to ssh to the internal LB VM: " + sshAnswer.getDetails());
result = false;
@ -281,10 +281,10 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
//Get guest network info
List<Network> guestNetworks = new ArrayList<Network>();
List<? extends Nic> internalLbVmNics = _nicDao.listByVmId(profile.getId());
for (Nic internalLbVmNic : internalLbVmNics) {
Network network = _ntwkModel.getNetwork(internalLbVmNic.getNetworkId());
final List<Network> guestNetworks = new ArrayList<Network>();
final List<? extends Nic> internalLbVmNics = _nicDao.listByVmId(profile.getId());
for (final Nic internalLbVmNic : internalLbVmNics) {
final Network network = _ntwkModel.getNetwork(internalLbVmNic.getNetworkId());
if (network.getTrafficType() == TrafficType.Guest) {
guestNetworks.add(network);
}
@ -292,7 +292,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
answer = cmds.getAnswer("getDomRVersion");
if (answer != null && answer instanceof GetDomRVersionAnswer) {
GetDomRVersionAnswer versionAnswer = (GetDomRVersionAnswer)answer;
final GetDomRVersionAnswer versionAnswer = (GetDomRVersionAnswer)answer;
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to get the template/scripts version of internal LB VM " + internalLbVm.getInstanceName() + " due to: " + versionAnswer.getDetails());
result = false;
@ -309,9 +309,9 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) {
DomainRouterVO internalLbVm = _internalLbVmDao.findById(profile.getId());
NicProfile controlNic = getNicProfileByTrafficType(profile, TrafficType.Control);
public boolean finalizeCommandsOnStart(final Commands cmds, final VirtualMachineProfile profile) {
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(profile.getId());
final NicProfile controlNic = getNicProfileByTrafficType(profile, TrafficType.Control);
if (controlNic == null) {
s_logger.error("Control network doesn't exist for the internal LB vm " + internalLbVm);
@ -326,18 +326,18 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
reprogramGuestNtwk = false;
}
VirtualRouterProvider lbProvider = _vrProviderDao.findById(internalLbVm.getElementId());
final VirtualRouterProvider lbProvider = _vrProviderDao.findById(internalLbVm.getElementId());
if (lbProvider == null) {
throw new CloudRuntimeException("Cannot find related element " + Type.InternalLbVm + " of vm: " + internalLbVm.getHostName());
}
Provider provider = Network.Provider.getProvider(lbProvider.getType().toString());
final Provider provider = Network.Provider.getProvider(lbProvider.getType().toString());
if (provider == null) {
throw new CloudRuntimeException("Cannot find related provider of provider: " + lbProvider.getType().toString());
}
if (reprogramGuestNtwk) {
NicProfile guestNic = getNicProfileByTrafficType(profile, TrafficType.Guest);
final NicProfile guestNic = getNicProfileByTrafficType(profile, TrafficType.Guest);
finalizeLbRulesForIp(cmds, internalLbVm, provider, new Ip(guestNic.getIp4Address()), guestNic.getNetworkId());
}
@ -345,19 +345,19 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public void finalizeStop(VirtualMachineProfile profile, Answer answer) {
public void finalizeStop(final VirtualMachineProfile profile, final Answer answer) {
}
@Override
public void finalizeExpunge(VirtualMachine vm) {
public void finalizeExpunge(final VirtualMachine vm) {
}
@Override
public void prepareStop(VirtualMachineProfile profile) {
public void prepareStop(final VirtualMachineProfile profile) {
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
_instance = configs.get("instance.name");
if (_instance == null) {
@ -367,10 +367,10 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
_mgmtHost = configs.get("host");
_mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
String offUUID = configs.get(Config.InternalLbVmServiceOfferingId.key());
final String offUUID = configs.get(Config.InternalLbVmServiceOfferingId.key());
if (offUUID != null && !offUUID.isEmpty()) {
//get the id by offering UUID
ServiceOfferingVO off = _serviceOfferingDao.findByUuid(offUUID);
final ServiceOfferingVO off = _serviceOfferingDao.findByUuid(offUUID);
if (off != null) {
_internalLbVmOfferingId = off.getId();
} else {
@ -380,7 +380,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
//if offering wasn't set, try to get the default one
if (_internalLbVmOfferingId == 0L) {
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
final boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
ServiceOfferingVO newOff =
new ServiceOfferingVO("System Offering For Internal LB VM", 1, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_RAMSIZE,
InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_CPU_MHZ, null, null, true, null,
@ -405,8 +405,8 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return _name;
}
protected NicProfile getNicProfileByTrafficType(VirtualMachineProfile profile, TrafficType trafficType) {
for (NicProfile nic : profile.getNics()) {
protected NicProfile getNicProfileByTrafficType(final VirtualMachineProfile profile, final TrafficType trafficType) {
for (final NicProfile nic : profile.getNics()) {
if (nic.getTrafficType() == trafficType && nic.getIp4Address() != null) {
return nic;
}
@ -414,7 +414,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return null;
}
protected void finalizeSshAndVersionOnStart(Commands cmds, VirtualMachineProfile profile, DomainRouterVO router, NicProfile controlNic) {
protected void finalizeSshAndVersionOnStart(final Commands cmds, final VirtualMachineProfile profile, final DomainRouterVO router, final NicProfile controlNic) {
cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922));
// Update internal lb vm template/scripts version
@ -424,17 +424,17 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
cmds.addCommand("getDomRVersion", command);
}
protected void finalizeLbRulesForIp(Commands cmds, DomainRouterVO internalLbVm, Provider provider, Ip sourceIp, long guestNtwkId) {
protected void finalizeLbRulesForIp(final Commands cmds, final DomainRouterVO internalLbVm, final Provider provider, final Ip sourceIp, final long guestNtwkId) {
s_logger.debug("Resending load balancing rules as a part of start for " + internalLbVm);
List<ApplicationLoadBalancerRuleVO> lbs = _lbDao.listBySrcIpSrcNtwkId(sourceIp, guestNtwkId);
List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
final List<ApplicationLoadBalancerRuleVO> lbs = _lbDao.listBySrcIpSrcNtwkId(sourceIp, guestNtwkId);
final List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
if (_ntwkModel.isProviderSupportServiceInNetwork(guestNtwkId, Service.Lb, provider)) {
// Re-apply load balancing rules
for (ApplicationLoadBalancerRuleVO lb : lbs) {
List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp);
for (final ApplicationLoadBalancerRuleVO lb : lbs) {
final List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
final List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
final List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp);
lbRules.add(loadBalancing);
}
}
@ -445,40 +445,40 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
}
private void createApplyLoadBalancingRulesCommands(List<LoadBalancingRule> rules, VirtualRouter internalLbVm, Commands cmds, long guestNetworkId) {
private void createApplyLoadBalancingRulesCommands(final List<LoadBalancingRule> rules, final VirtualRouter internalLbVm, final Commands cmds, final long guestNetworkId) {
LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
final LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
int i = 0;
boolean inline = false;
for (LoadBalancingRule rule : rules) {
boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke));
String protocol = rule.getProtocol();
String algorithm = rule.getAlgorithm();
String uuid = rule.getUuid();
final boolean inline = false;
for (final LoadBalancingRule rule : rules) {
final boolean revoked = rule.getState().equals(FirewallRule.State.Revoke);
final String protocol = rule.getProtocol();
final String algorithm = rule.getAlgorithm();
final String uuid = rule.getUuid();
String srcIp = rule.getSourceIp().addr();
int srcPort = rule.getSourcePortStart();
List<LbDestination> destinations = rule.getDestinations();
List<LbStickinessPolicy> stickinessPolicies = rule.getStickinessPolicies();
LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, stickinessPolicies);
final String srcIp = rule.getSourceIp().addr();
final int srcPort = rule.getSourcePortStart();
final List<LbDestination> destinations = rule.getDestinations();
final List<LbStickinessPolicy> stickinessPolicies = rule.getStickinessPolicies();
final LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, stickinessPolicies);
lbs[i++] = lb;
}
Network guestNetwork = _ntwkModel.getNetwork(guestNetworkId);
Nic guestNic = _nicDao.findByNtwkIdAndInstanceId(guestNetwork.getId(), internalLbVm.getId());
NicProfile guestNicProfile =
final Network guestNetwork = _ntwkModel.getNetwork(guestNetworkId);
final Nic guestNic = _nicDao.findByNtwkIdAndInstanceId(guestNetwork.getId(), internalLbVm.getId());
final NicProfile guestNicProfile =
new NicProfile(guestNic, guestNetwork, guestNic.getBroadcastUri(), guestNic.getIsolationUri(), _ntwkModel.getNetworkRate(guestNetwork.getId(),
internalLbVm.getId()), _ntwkModel.isSecurityGroupSupportedInNetwork(guestNetwork), _ntwkModel.getNetworkTag(internalLbVm.getHypervisorType(),
guestNetwork));
NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
String maxconn = null;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
} else {
maxconn = offering.getConcurrentConnections().toString();
}
LoadBalancerConfigCommand cmd =
final LoadBalancerConfigCommand cmd =
new LoadBalancerConfigCommand(lbs, guestNic.getIp4Address(), guestNic.getIp4Address(), internalLbVm.getPrivateIpAddress(), _itMgr.toNicTO(guestNicProfile,
internalLbVm.getHypervisorType()), internalLbVm.getVpcId(), maxconn, offering.isKeepAliveEnabled());
@ -490,16 +490,16 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getInternalLbControlIp(internalLbVm.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, guestNic.getIp4Address());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, internalLbVm.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(internalLbVm.getDataCenterId());
final DataCenterVO dcVo = _dcDao.findById(internalLbVm.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
protected String getInternalLbControlIp(long internalLbVmId) {
protected String getInternalLbControlIp(final long internalLbVmId) {
String controlIpAddress = null;
List<NicVO> nics = _nicDao.listByVmId(internalLbVmId);
for (NicVO nic : nics) {
Network ntwk = _ntwkModel.getNetwork(nic.getNetworkId());
final List<NicVO> nics = _nicDao.listByVmId(internalLbVmId);
for (final NicVO nic : nics) {
final Network ntwk = _ntwkModel.getNetwork(nic.getNetworkId());
if (ntwk.getTrafficType() == TrafficType.Control) {
controlIpAddress = nic.getIp4Address();
}
@ -507,7 +507,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
if (controlIpAddress == null) {
s_logger.warn("Unable to find Internal LB control ip in its attached NICs!. Internal LB vm: " + internalLbVmId);
DomainRouterVO internalLbVm = _internalLbVmDao.findById(internalLbVmId);
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(internalLbVmId);
return internalLbVm.getPrivateIpAddress();
}
@ -515,12 +515,12 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public boolean destroyInternalLbVm(long vmId, Account caller, Long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException {
public boolean destroyInternalLbVm(final long vmId, final Account caller, final Long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Attempting to destroy Internal LB vm " + vmId);
}
DomainRouterVO internalLbVm = _internalLbVmDao.findById(vmId);
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(vmId);
if (internalLbVm == null) {
return true;
}
@ -533,8 +533,8 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public VirtualRouter stopInternalLbVm(long vmId, boolean forced, Account caller, long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException {
DomainRouterVO internalLbVm = _internalLbVmDao.findById(vmId);
public VirtualRouter stopInternalLbVm(final long vmId, final boolean forced, final Account caller, final long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException {
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(vmId);
if (internalLbVm == null || internalLbVm.getRole() != Role.INTERNAL_LB_VM) {
throw new InvalidParameterValueException("Can't find internal lb vm by id specified");
}
@ -545,27 +545,27 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return stopInternalLbVm(internalLbVm, forced, caller, callerUserId);
}
protected VirtualRouter stopInternalLbVm(DomainRouterVO internalLbVm, boolean forced, Account caller, long callerUserId) throws ResourceUnavailableException,
protected VirtualRouter stopInternalLbVm(final DomainRouterVO internalLbVm, final boolean forced, final Account caller, final long callerUserId) throws ResourceUnavailableException,
ConcurrentOperationException {
s_logger.debug("Stopping internal lb vm " + internalLbVm);
try {
_itMgr.advanceStop(internalLbVm.getUuid(), forced);
return _internalLbVmDao.findById(internalLbVm.getId());
} catch (OperationTimedoutException e) {
} catch (final OperationTimedoutException e) {
throw new CloudRuntimeException("Unable to stop " + internalLbVm, e);
}
}
@Override
public List<DomainRouterVO> deployInternalLbVm(Network guestNetwork, Ip requestedGuestIp, DeployDestination dest, Account owner, Map<Param, Object> params)
public List<DomainRouterVO> deployInternalLbVm(final Network guestNetwork, final Ip requestedGuestIp, final DeployDestination dest, final Account owner, final Map<Param, Object> params)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
List<DomainRouterVO> internalLbVms = findOrDeployInternalLbVm(guestNetwork, requestedGuestIp, dest, owner, params);
final List<DomainRouterVO> internalLbVms = findOrDeployInternalLbVm(guestNetwork, requestedGuestIp, dest, owner, params);
return startInternalLbVms(params, internalLbVms);
}
protected List<DomainRouterVO> startInternalLbVms(Map<Param, Object> params, List<DomainRouterVO> internalLbVms) throws StorageUnavailableException,
protected List<DomainRouterVO> startInternalLbVms(final Map<Param, Object> params, final List<DomainRouterVO> internalLbVms) throws StorageUnavailableException,
InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
List<DomainRouterVO> runningInternalLbVms = null;
@ -589,11 +589,11 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@DB
protected List<DomainRouterVO> findOrDeployInternalLbVm(Network guestNetwork, Ip requestedGuestIp, DeployDestination dest, Account owner, Map<Param, Object> params)
protected List<DomainRouterVO> findOrDeployInternalLbVm(final Network guestNetwork, final Ip requestedGuestIp, final DeployDestination dest, final Account owner, final Map<Param, Object> params)
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
List<DomainRouterVO> internalLbVms = new ArrayList<DomainRouterVO>();
Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), NetworkOrchestrationService.NetworkLockTimeout.value());
final Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), NetworkOrchestrationService.NetworkLockTimeout.value());
if (lock == null) {
throw new ConcurrentOperationException("Unable to lock network " + guestNetwork.getId());
}
@ -602,7 +602,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
s_logger.debug("Lock is acquired for network id " + lock.getId() + " as a part of internal lb startup in " + dest);
}
long internalLbProviderId = getInternalLbProviderId(guestNetwork);
final long internalLbProviderId = getInternalLbProviderId(guestNetwork);
try {
assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup ||
@ -610,18 +610,18 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
assert guestNetwork.getTrafficType() == TrafficType.Guest;
//deploy internal lb vm
Pair<DeploymentPlan, List<DomainRouterVO>> planAndInternalLbVms = getDeploymentPlanAndInternalLbVms(dest, guestNetwork.getId(), requestedGuestIp);
final Pair<DeploymentPlan, List<DomainRouterVO>> planAndInternalLbVms = getDeploymentPlanAndInternalLbVms(dest, guestNetwork.getId(), requestedGuestIp);
internalLbVms = planAndInternalLbVms.second();
DeploymentPlan plan = planAndInternalLbVms.first();
final DeploymentPlan plan = planAndInternalLbVms.first();
if (internalLbVms.size() > 0) {
s_logger.debug("Found " + internalLbVms.size() + " internal lb vms for the requested IP " + requestedGuestIp.addr());
return internalLbVms;
}
LinkedHashMap<Network, List<? extends NicProfile>> networks = createInternalLbVmNetworks(guestNetwork, plan, requestedGuestIp);
final LinkedHashMap<Network, List<? extends NicProfile>> networks = createInternalLbVmNetworks(guestNetwork, plan, requestedGuestIp);
//Pass startVm=false as we are holding the network lock that needs to be released at the end of vm allocation
DomainRouterVO internalLbVm =
final DomainRouterVO internalLbVm =
deployInternalLbVm(owner, dest, plan, params, internalLbProviderId, _internalLbVmOfferingId, guestNetwork.getVpcId(), networks, false);
if (internalLbVm != null) {
_internalLbVmDao.addRouterToGuestNetwork(internalLbVm, guestNetwork);
@ -638,16 +638,16 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return internalLbVms;
}
protected long getInternalLbProviderId(Network guestNetwork) {
Type type = Type.InternalLbVm;
long physicalNetworkId = _ntwkModel.getPhysicalNetworkId(guestNetwork);
protected long getInternalLbProviderId(final Network guestNetwork) {
final Type type = Type.InternalLbVm;
final long physicalNetworkId = _ntwkModel.getPhysicalNetworkId(guestNetwork);
PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, type.toString());
final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, type.toString());
if (provider == null) {
throw new CloudRuntimeException("Cannot find service provider " + type.toString() + " in physical network " + physicalNetworkId);
}
VirtualRouterProvider internalLbProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), type);
final VirtualRouterProvider internalLbProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), type);
if (internalLbProvider == null) {
throw new CloudRuntimeException("Cannot find provider " + type.toString() + " as service provider " + provider.getId());
}
@ -655,16 +655,16 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return internalLbProvider.getId();
}
protected LinkedHashMap<Network, List<? extends NicProfile>> createInternalLbVmNetworks(Network guestNetwork, DeploymentPlan plan, Ip guestIp) throws ConcurrentOperationException,
protected LinkedHashMap<Network, List<? extends NicProfile>> createInternalLbVmNetworks(final Network guestNetwork, final DeploymentPlan plan, final Ip guestIp) throws ConcurrentOperationException,
InsufficientAddressCapacityException {
//Form networks
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(3);
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(3);
//1) Guest network - default
if (guestNetwork != null) {
s_logger.debug("Adding nic for Internal LB in Guest network " + guestNetwork);
NicProfile guestNic = new NicProfile();
final NicProfile guestNic = new NicProfile();
if (guestIp != null) {
guestNic.setIp4Address(guestIp.addr());
} else {
@ -675,7 +675,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
guestNic.setBroadcastType(guestNetwork.getBroadcastDomainType());
guestNic.setIsolationUri(guestNetwork.getBroadcastUri());
guestNic.setMode(guestNetwork.getMode());
String gatewayCidr = guestNetwork.getCidr();
final String gatewayCidr = guestNetwork.getCidr();
guestNic.setNetmask(NetUtils.getCidrNetmask(gatewayCidr));
guestNic.setDefaultNic(true);
networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
@ -683,31 +683,31 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
//2) Control network
s_logger.debug("Adding nic for Internal LB vm in Control network ");
List<? extends NetworkOffering> offerings = _ntwkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
NetworkOffering controlOffering = offerings.get(0);
Network controlConfig = _ntwkMgr.setupNetwork(_accountMgr.getSystemAccount(), controlOffering, plan, null, null, false).get(0);
final List<? extends NetworkOffering> offerings = _ntwkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
final NetworkOffering controlOffering = offerings.get(0);
final Network controlConfig = _ntwkMgr.setupNetwork(_accountMgr.getSystemAccount(), controlOffering, plan, null, null, false).get(0);
networks.put(controlConfig, new ArrayList<NicProfile>());
return networks;
}
protected Pair<DeploymentPlan, List<DomainRouterVO>> getDeploymentPlanAndInternalLbVms(DeployDestination dest, long guestNetworkId, Ip requestedGuestIp) {
long dcId = dest.getDataCenter().getId();
DeploymentPlan plan = new DataCenterDeployment(dcId);
List<DomainRouterVO> internalLbVms = findInternalLbVms(guestNetworkId, requestedGuestIp);
protected Pair<DeploymentPlan, List<DomainRouterVO>> getDeploymentPlanAndInternalLbVms(final DeployDestination dest, final long guestNetworkId, final Ip requestedGuestIp) {
final long dcId = dest.getDataCenter().getId();
final DeploymentPlan plan = new DataCenterDeployment(dcId);
final List<DomainRouterVO> internalLbVms = findInternalLbVms(guestNetworkId, requestedGuestIp);
return new Pair<DeploymentPlan, List<DomainRouterVO>>(plan, internalLbVms);
}
@Override
public List<DomainRouterVO> findInternalLbVms(long guestNetworkId, Ip requestedGuestIp) {
List<DomainRouterVO> internalLbVms = _internalLbVmDao.listByNetworkAndRole(guestNetworkId, Role.INTERNAL_LB_VM);
public List<DomainRouterVO> findInternalLbVms(final long guestNetworkId, final Ip requestedGuestIp) {
final List<DomainRouterVO> internalLbVms = _internalLbVmDao.listByNetworkAndRole(guestNetworkId, Role.INTERNAL_LB_VM);
if (requestedGuestIp != null && !internalLbVms.isEmpty()) {
Iterator<DomainRouterVO> it = internalLbVms.iterator();
final Iterator<DomainRouterVO> it = internalLbVms.iterator();
while (it.hasNext()) {
DomainRouterVO vm = it.next();
Nic nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
final DomainRouterVO vm = it.next();
final Nic nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
if (!nic.getIp4Address().equalsIgnoreCase(requestedGuestIp.addr())) {
it.remove();
}
@ -716,24 +716,24 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return internalLbVms;
}
protected DomainRouterVO deployInternalLbVm(Account owner, DeployDestination dest, DeploymentPlan plan, Map<Param, Object> params, long internalLbProviderId,
long svcOffId, Long vpcId, LinkedHashMap<Network, List<? extends NicProfile>> networks, boolean startVm) throws ConcurrentOperationException,
protected DomainRouterVO deployInternalLbVm(final Account owner, final DeployDestination dest, final DeploymentPlan plan, final Map<Param, Object> params, final long internalLbProviderId,
final long svcOffId, final Long vpcId, final LinkedHashMap<Network, List<? extends NicProfile>> networks, final boolean startVm) throws ConcurrentOperationException,
InsufficientAddressCapacityException, InsufficientServerCapacityException, InsufficientCapacityException, StorageUnavailableException,
ResourceUnavailableException {
ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(svcOffId);
final ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(svcOffId);
// Internal lb is the network element, we don't know the hypervisor type yet.
// Try to allocate the internal lb twice using diff hypervisors, and when failed both times, throw the exception up
List<HypervisorType> hypervisors = getHypervisors(dest, plan, null);
final List<HypervisorType> hypervisors = getHypervisors(dest, plan, null);
int allocateRetry = 0;
int startRetry = 0;
DomainRouterVO internalLbVm = null;
for (Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext();) {
HypervisorType hType = iter.next();
for (final Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext();) {
final HypervisorType hType = iter.next();
try {
long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
final long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating the internal lb vm " + id + " in datacenter " + dest.getDataCenter() + " with hypervisor type " + hType);
}
@ -757,7 +757,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
default:
break;
}
VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
final VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
if (template == null) {
s_logger.debug(hType + " won't support system vm, skip it");
@ -771,13 +771,12 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
internalLbVm =
new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, VirtualMachineName.getSystemVmName(id, _instance, InternalLbVmNamePrefix),
template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, 0, false,
RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
internalLbVm.setRole(Role.INTERNAL_LB_VM);
internalLbVm = _internalLbVmDao.persist(internalLbVm);
_itMgr.allocate(internalLbVm.getInstanceName(), template, routerOffering, networks, plan, null);
internalLbVm = _internalLbVmDao.findById(internalLbVm.getId());
} catch (InsufficientCapacityException ex) {
} catch (final InsufficientCapacityException ex) {
if (allocateRetry < 2 && iter.hasNext()) {
s_logger.debug("Failed to allocate the Internal lb vm with hypervisor type " + hType + ", retrying one more time");
continue;
@ -792,7 +791,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
try {
internalLbVm = startInternalLbVm(internalLbVm, _accountMgr.getSystemAccount(), User.UID_SYSTEM, params);
break;
} catch (InsufficientCapacityException ex) {
} catch (final InsufficientCapacityException ex) {
if (startRetry < 2 && iter.hasNext()) {
s_logger.debug("Failed to start the Internal lb vm " + internalLbVm + " with hypervisor type " + hType + ", " +
"destroying it and recreating one more time");
@ -813,7 +812,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return internalLbVm;
}
protected DomainRouterVO startInternalLbVm(DomainRouterVO internalLbVm, Account caller, long callerUserId, Map<Param, Object> params)
protected DomainRouterVO startInternalLbVm(DomainRouterVO internalLbVm, final Account caller, final long callerUserId, final Map<Param, Object> params)
throws StorageUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("Starting Internal LB VM " + internalLbVm);
_itMgr.start(internalLbVm.getUuid(), params, null, null);
@ -825,11 +824,11 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
return _internalLbVmDao.findById(internalLbVm.getId());
}
protected List<HypervisorType> getHypervisors(DeployDestination dest, DeploymentPlan plan, List<HypervisorType> supportedHypervisors)
protected List<HypervisorType> getHypervisors(final DeployDestination dest, final DeploymentPlan plan, final List<HypervisorType> supportedHypervisors)
throws InsufficientServerCapacityException {
List<HypervisorType> hypervisors = new ArrayList<HypervisorType>();
HypervisorType defaults = _resourceMgr.getDefaultHypervisor(dest.getDataCenter().getId());
final HypervisorType defaults = _resourceMgr.getDefaultHypervisor(dest.getDataCenter().getId());
if (defaults != HypervisorType.None) {
hypervisors.add(defaults);
} else {
@ -838,10 +837,10 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
//keep only elements defined in supported hypervisors
StringBuilder hTypesStr = new StringBuilder();
final StringBuilder hTypesStr = new StringBuilder();
if (supportedHypervisors != null && !supportedHypervisors.isEmpty()) {
hypervisors.retainAll(supportedHypervisors);
for (HypervisorType hType : supportedHypervisors) {
for (final HypervisorType hType : supportedHypervisors) {
hTypesStr.append(hType).append(" ");
}
}
@ -854,7 +853,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public boolean applyLoadBalancingRules(Network network, final List<LoadBalancingRule> rules, List<? extends VirtualRouter> internalLbVms)
public boolean applyLoadBalancingRules(final Network network, final List<LoadBalancingRule> rules, final List<? extends VirtualRouter> internalLbVms)
throws ResourceUnavailableException {
if (rules == null || rules.isEmpty()) {
s_logger.debug("No lb rules to be applied for network " + network);
@ -866,7 +865,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
throw new CloudRuntimeException("Can't apply the lb rules on network " + network + " as the list of internal lb vms is empty");
}
VirtualRouter lbVm = internalLbVms.get(0);
final VirtualRouter lbVm = internalLbVms.get(0);
if (lbVm.getState() == State.Running) {
return sendLBRules(lbVm, rules, network.getId());
} else if (lbVm.getState() == State.Stopped || lbVm.getState() == State.Stopping) {
@ -878,17 +877,17 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
}
protected boolean sendLBRules(VirtualRouter internalLbVm, List<LoadBalancingRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(Command.OnError.Continue);
protected boolean sendLBRules(final VirtualRouter internalLbVm, final List<LoadBalancingRule> rules, final long guestNetworkId) throws ResourceUnavailableException {
final Commands cmds = new Commands(Command.OnError.Continue);
createApplyLoadBalancingRulesCommands(rules, internalLbVm, cmds, guestNetworkId);
return sendCommandsToInternalLbVm(internalLbVm, cmds);
}
protected boolean sendCommandsToInternalLbVm(final VirtualRouter internalLbVm, Commands cmds) throws AgentUnavailableException {
protected boolean sendCommandsToInternalLbVm(final VirtualRouter internalLbVm, final Commands cmds) throws AgentUnavailableException {
Answer[] answers = null;
try {
answers = _agentMgr.send(internalLbVm.getHostId(), cmds);
} catch (OperationTimedoutException e) {
} catch (final OperationTimedoutException e) {
s_logger.warn("Timed Out", e);
throw new AgentUnavailableException("Unable to send commands to virtual router ", internalLbVm.getHostId(), e);
}
@ -903,7 +902,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
boolean result = true;
if (answers.length > 0) {
for (Answer answer : answers) {
for (final Answer answer : answers) {
if (!answer.getResult()) {
result = false;
break;
@ -914,10 +913,10 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
}
@Override
public VirtualRouter startInternalLbVm(long internalLbVmId, Account caller, long callerUserId) throws StorageUnavailableException, InsufficientCapacityException,
public VirtualRouter startInternalLbVm(final long internalLbVmId, final Account caller, final long callerUserId) throws StorageUnavailableException, InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
DomainRouterVO internalLbVm = _internalLbVmDao.findById(internalLbVmId);
final DomainRouterVO internalLbVm = _internalLbVmDao.findById(internalLbVmId);
if (internalLbVm == null || internalLbVm.getRole() != Role.INTERNAL_LB_VM) {
throw new InvalidParameterValueException("Can't find internal lb vm by id specified");
}

View File

@ -24,9 +24,10 @@ import java.util.List;
import javax.inject.Inject;
import com.cloud.storage.Storage;
import junit.framework.TestCase;
import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -35,9 +36,6 @@ import org.mockito.Mockito;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.manager.Commands;
@ -60,6 +58,7 @@ import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.Storage;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.utils.component.ComponentContext;
@ -126,16 +125,16 @@ public class InternalLBVMManagerTest extends TestCase {
ComponentContext.initComponentsLifeCycle();
vm =
new DomainRouterVO(1L, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, 0, false, null, false, false,
new DomainRouterVO(1L, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false,
VirtualMachine.Type.InternalLoadBalancerVm, null);
vm.setRole(Role.INTERNAL_LB_VM);
vm = setId(vm, 1);
vm.setPrivateIpAddress("10.2.2.2");
NicVO nic = new NicVO("somereserver", 1L, 1L, VirtualMachine.Type.InternalLoadBalancerVm);
final NicVO nic = new NicVO("somereserver", 1L, 1L, VirtualMachine.Type.InternalLoadBalancerVm);
nic.setIp4Address(requestedIp);
List<DomainRouterVO> emptyList = new ArrayList<DomainRouterVO>();
List<DomainRouterVO> nonEmptyList = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> emptyList = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> nonEmptyList = new ArrayList<DomainRouterVO>();
nonEmptyList.add(vm);
Mockito.when(_domainRouterDao.listByNetworkAndRole(invalidNtwkId, Role.INTERNAL_LB_VM)).thenReturn(emptyList);
@ -144,16 +143,16 @@ public class InternalLBVMManagerTest extends TestCase {
Mockito.when(_nicDao.findByNtwkIdAndInstanceId(validNtwkId, 1)).thenReturn(nic);
Mockito.when(_nicDao.findByNtwkIdAndInstanceId(invalidNtwkId, 1)).thenReturn(nic);
Answer answer = new Answer(null, true, null);
Answer[] answers = new Answer[1];
final Answer answer = new Answer(null, true, null);
final Answer[] answers = new Answer[1];
answers[0] = answer;
try {
Mockito.when(_agentMgr.send(Matchers.anyLong(), Matchers.any(Commands.class))).thenReturn(answers);
} catch (AgentUnavailableException e) {
} catch (final AgentUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationTimedoutException e) {
} catch (final OperationTimedoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -163,9 +162,9 @@ public class InternalLBVMManagerTest extends TestCase {
Mockito.when(_itMgr.toNicTO(Matchers.any(NicProfile.class), Matchers.any(HypervisorType.class))).thenReturn(null);
Mockito.when(_domainRouterDao.findById(Matchers.anyLong())).thenReturn(vm);
DataCenterVO dc = new DataCenterVO(1L, null, null, null, null, null, null, null, null, null, NetworkType.Advanced, null, null);
final DataCenterVO dc = new DataCenterVO(1L, null, null, null, null, null, null, null, null, null, NetworkType.Advanced, null, null);
Mockito.when(_dcDao.findById(Matchers.anyLong())).thenReturn(dc);
NetworkOfferingVO networkOfferingVO = new NetworkOfferingVO();
final NetworkOfferingVO networkOfferingVO = new NetworkOfferingVO();
networkOfferingVO.setConcurrentConnections(500);
Mockito.when(_offeringDao.findById(Matchers.anyLong())).thenReturn(networkOfferingVO);
@ -178,7 +177,7 @@ public class InternalLBVMManagerTest extends TestCase {
ntwk = new NetworkVO();
try {
ntwk.setBroadcastUri(new URI("somevlan"));
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -190,13 +189,13 @@ public class InternalLBVMManagerTest extends TestCase {
@Test
public void findInternalLbVmsForInvalidNetwork() {
List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(invalidNtwkId, new Ip(requestedIp));
final List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(invalidNtwkId, new Ip(requestedIp));
assertTrue("Non empty vm list was returned for invalid network id", vms.isEmpty());
}
@Test
public void findInternalLbVmsForValidNetwork() {
List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(validNtwkId, new Ip(requestedIp));
final List<? extends VirtualRouter> vms = _lbVmMgr.findInternalLbVms(validNtwkId, new Ip(requestedIp));
assertTrue("Empty vm list was returned for valid network id", !vms.isEmpty());
}
@ -204,10 +203,10 @@ public class InternalLBVMManagerTest extends TestCase {
@Test
public void applyEmptyRulesSet() {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
try {
result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), new ArrayList<LoadBalancingRule>(), vms);
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
} finally {
assertTrue("Got failure when tried to apply empty list of rules", result);
@ -217,14 +216,14 @@ public class InternalLBVMManagerTest extends TestCase {
@Test(expected = CloudRuntimeException.class)
public void applyWithEmptyVmsSet() {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
final LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
rules.add(rule);
try {
result = _lbVmMgr.applyLoadBalancingRules(new NetworkVO(), rules, vms);
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
} finally {
assertFalse("Got success when tried to apply with the empty internal lb vm list", result);
}
@ -233,12 +232,12 @@ public class InternalLBVMManagerTest extends TestCase {
@Test(expected = ResourceUnavailableException.class)
public void applyToVmInStartingState() throws ResourceUnavailableException {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
vm.setState(State.Starting);
vms.add(vm);
List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
final List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
final LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
rules.add(rule);
try {
@ -251,12 +250,12 @@ public class InternalLBVMManagerTest extends TestCase {
@Test
public void applyToVmInStoppedState() throws ResourceUnavailableException {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
vm.setState(State.Stopped);
vms.add(vm);
List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
final List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
final LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
rules.add(rule);
try {
@ -269,12 +268,12 @@ public class InternalLBVMManagerTest extends TestCase {
@Test
public void applyToVmInStoppingState() throws ResourceUnavailableException {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
vm.setState(State.Stopping);
vms.add(vm);
List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
final List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
final LoadBalancingRule rule = new LoadBalancingRule(null, null, null, null, null, null, null);
rules.add(rule);
try {
@ -287,15 +286,15 @@ public class InternalLBVMManagerTest extends TestCase {
@Test
public void applyToVmInRunningState() throws ResourceUnavailableException {
boolean result = false;
List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
final List<DomainRouterVO> vms = new ArrayList<DomainRouterVO>();
vm.setState(State.Running);
vms.add(vm);
List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
ApplicationLoadBalancerRuleVO lb = new ApplicationLoadBalancerRuleVO(null, null, 22, 22, "roundrobin", 1L, 1L, 1L, new Ip(requestedIp), 1L, Scheme.Internal);
final List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
final ApplicationLoadBalancerRuleVO lb = new ApplicationLoadBalancerRuleVO(null, null, 22, 22, "roundrobin", 1L, 1L, 1L, new Ip(requestedIp), 1L, Scheme.Internal);
lb.setState(FirewallRule.State.Add);
LoadBalancingRule rule = new LoadBalancingRule(lb, null, null, null, new Ip(requestedIp));
final LoadBalancingRule rule = new LoadBalancingRule(lb, null, null, null, new Ip(requestedIp));
rules.add(rule);
@ -331,48 +330,48 @@ public class InternalLBVMManagerTest extends TestCase {
}
}
private static ServiceOfferingVO setId(ServiceOfferingVO vo, long id) {
ServiceOfferingVO voToReturn = vo;
Class<?> c = voToReturn.getClass();
private static ServiceOfferingVO setId(final ServiceOfferingVO vo, final long id) {
final ServiceOfferingVO voToReturn = vo;
final Class<?> c = voToReturn.getClass();
try {
Field f = c.getSuperclass().getDeclaredField("id");
final Field f = c.getSuperclass().getDeclaredField("id");
f.setAccessible(true);
f.setLong(voToReturn, id);
} catch (NoSuchFieldException ex) {
} catch (final NoSuchFieldException ex) {
return null;
} catch (IllegalAccessException ex) {
} catch (final IllegalAccessException ex) {
return null;
}
return voToReturn;
}
private static NetworkVO setId(NetworkVO vo, long id) {
NetworkVO voToReturn = vo;
Class<?> c = voToReturn.getClass();
private static NetworkVO setId(final NetworkVO vo, final long id) {
final NetworkVO voToReturn = vo;
final Class<?> c = voToReturn.getClass();
try {
Field f = c.getDeclaredField("id");
final Field f = c.getDeclaredField("id");
f.setAccessible(true);
f.setLong(voToReturn, id);
} catch (NoSuchFieldException ex) {
} catch (final NoSuchFieldException ex) {
return null;
} catch (IllegalAccessException ex) {
} catch (final IllegalAccessException ex) {
return null;
}
return voToReturn;
}
private static DomainRouterVO setId(DomainRouterVO vo, long id) {
DomainRouterVO voToReturn = vo;
Class<?> c = voToReturn.getClass();
private static DomainRouterVO setId(final DomainRouterVO vo, final long id) {
final DomainRouterVO voToReturn = vo;
final Class<?> c = voToReturn.getClass();
try {
Field f = c.getSuperclass().getDeclaredField("id");
final Field f = c.getSuperclass().getDeclaredField("id");
f.setAccessible(true);
f.setLong(voToReturn, id);
} catch (NoSuchFieldException ex) {
} catch (final NoSuchFieldException ex) {
return null;
} catch (IllegalAccessException ex) {
} catch (final IllegalAccessException ex) {
return null;
}

View File

@ -20,9 +20,10 @@ import java.lang.reflect.Field;
import javax.inject.Inject;
import com.cloud.storage.Storage;
import junit.framework.TestCase;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -32,9 +33,6 @@ import org.mockito.Mockito;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
@ -45,6 +43,7 @@ import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.Storage;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.UserVO;
@ -100,12 +99,12 @@ public class InternalLBVMServiceTest extends TestCase {
Mockito.when(_accountDao.findByIdIncludingRemoved(Matchers.anyLong())).thenReturn(new AccountVO(2));
CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
DomainRouterVO validVm =
new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, 0, false, null, false, false,
final DomainRouterVO validVm =
new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false,
VirtualMachine.Type.InternalLoadBalancerVm, null);
validVm.setRole(Role.INTERNAL_LB_VM);
DomainRouterVO nonInternalLbVm =
new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, 0, false, null, false, false,
final DomainRouterVO nonInternalLbVm =
new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false,
VirtualMachine.Type.DomainRouter, null);
nonInternalLbVm.setRole(Role.VIRTUAL_ROUTER);
@ -124,19 +123,19 @@ public class InternalLBVMServiceTest extends TestCase {
@Test(expected = InvalidParameterValueException.class)
public void startNonExistingVm() {
String expectedExcText = null;
final String expectedExcText = null;
try {
_lbVmSvc.startInternalLbVm(nonExistingVmId, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InsufficientCapacityException e) {
} catch (final InsufficientCapacityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -144,19 +143,19 @@ public class InternalLBVMServiceTest extends TestCase {
@Test(expected = InvalidParameterValueException.class)
public void startNonInternalLbVmVm() {
String expectedExcText = null;
final String expectedExcText = null;
try {
_lbVmSvc.startInternalLbVm(nonInternalLbVmId, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InsufficientCapacityException e) {
} catch (final InsufficientCapacityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -167,16 +166,16 @@ public class InternalLBVMServiceTest extends TestCase {
VirtualRouter vr = null;
try {
vr = _lbVmSvc.startInternalLbVm(validVmId, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InsufficientCapacityException e) {
} catch (final InsufficientCapacityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
@ -187,16 +186,16 @@ public class InternalLBVMServiceTest extends TestCase {
//TEST FOR STOP COMMAND
@Test(expected = InvalidParameterValueException.class)
public void stopNonExistingVm() {
String expectedExcText = null;
final String expectedExcText = null;
try {
_lbVmSvc.stopInternalLbVm(nonExistingVmId, false, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -204,16 +203,16 @@ public class InternalLBVMServiceTest extends TestCase {
@Test(expected = InvalidParameterValueException.class)
public void stopNonInternalLbVmVm() {
String expectedExcText = null;
final String expectedExcText = null;
try {
_lbVmSvc.stopInternalLbVm(nonInternalLbVmId, false, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -224,13 +223,13 @@ public class InternalLBVMServiceTest extends TestCase {
VirtualRouter vr = null;
try {
vr = _lbVmSvc.stopInternalLbVm(validVmId, false, _accountMgr.getAccount(1L), 1L);
} catch (StorageUnavailableException e) {
} catch (final StorageUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ConcurrentOperationException e) {
} catch (final ConcurrentOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceUnavailableException e) {
} catch (final ResourceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
@ -238,16 +237,16 @@ public class InternalLBVMServiceTest extends TestCase {
}
}
private static ServiceOfferingVO setId(ServiceOfferingVO vo, long id) {
ServiceOfferingVO voToReturn = vo;
Class<?> c = voToReturn.getClass();
private static ServiceOfferingVO setId(final ServiceOfferingVO vo, final long id) {
final ServiceOfferingVO voToReturn = vo;
final Class<?> c = voToReturn.getClass();
try {
Field f = c.getSuperclass().getDeclaredField("id");
final Field f = c.getSuperclass().getDeclaredField("id");
f.setAccessible(true);
f.setLong(voToReturn, id);
} catch (NoSuchFieldException ex) {
} catch (final NoSuchFieldException ex) {
return null;
} catch (IllegalAccessException ex) {
} catch (final IllegalAccessException ex) {
return null;
}

View File

@ -930,9 +930,8 @@ public class CommandSetupHelper {
final String dhcpRange = getGuestDhcpRange(guestNic, network, _entityMgr.findById(DataCenter.class, network.getDataCenterId()));
final NicProfile nicProfile = _networkModel.getNicProfile(router, nic.getNetworkId(), null);
final int priority = _networkHelper.getRealPriority(router);
final SetupGuestNetworkCommand setupCmd = new SetupGuestNetworkCommand(dhcpRange, networkDomain, router.getIsRedundantRouter(), priority, defaultDns1, defaultDns2, add, _itMgr.toNicTO(nicProfile,
final SetupGuestNetworkCommand setupCmd = new SetupGuestNetworkCommand(dhcpRange, networkDomain, router.getIsRedundantRouter(), defaultDns1, defaultDns2, add, _itMgr.toNicTO(nicProfile,
router.getHypervisorType()));
final String brd = NetUtils.long2Ip(NetUtils.ip2Long(guestNic.getIp4Address()) | ~NetUtils.ip2Long(guestNic.getNetmask()));

View File

@ -50,8 +50,6 @@ public interface NetworkHelper {
List<? extends VirtualRouter> disconnectedRouters, String reason)
throws ResourceUnavailableException;
public abstract int getRealPriority(DomainRouterVO router);
public abstract NicTO getNicTO(VirtualRouter router, Long networkId,
String broadcastUri);

View File

@ -36,8 +36,6 @@ import org.cloud.network.router.deployment.RouterDeploymentDefinition;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
@ -224,33 +222,6 @@ public class NetworkHelperImpl implements NetworkHelper {
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, disconnectedRouter.getDataCenterId(), disconnectedRouter.getPodIdToDeployIn(), title, context);
disconnectedRouter.setStopPending(true);
disconnectedRouter = _routerDao.persist(disconnectedRouter);
final int connRouterPR = getRealPriority(connectedRouter);
final int disconnRouterPR = getRealPriority(disconnectedRouter);
if (connRouterPR < disconnRouterPR) {
// connRouterPR < disconnRouterPR, they won't equal at any time
if (!connectedRouter.getIsPriorityBumpUp()) {
final BumpUpPriorityCommand command = new BumpUpPriorityCommand();
command.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(connectedRouter.getId()));
command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, connectedRouter.getInstanceName());
final Answer answer = _agentMgr.easySend(connectedRouter.getHostId(), command);
if (!answer.getResult()) {
s_logger.error("Failed to bump up " + connectedRouter.getInstanceName() + "'s priority! " + answer.getDetails());
}
} else {
final String t = "Can't bump up virtual router " + connectedRouter.getInstanceName() + "'s priority due to it's already bumped up!";
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, connectedRouter.getDataCenterId(), connectedRouter.getPodIdToDeployIn(), t, t);
}
}
}
@Override
public int getRealPriority(final DomainRouterVO router) {
int priority = router.getPriority();
if (router.getIsPriorityBumpUp()) {
priority += VirtualNetworkApplianceManager.DEFAULT_DELTA;
}
return priority;
}
@Override
@ -522,7 +493,7 @@ public class NetworkHelperImpl implements NetworkHelper {
router = new DomainRouterVO(id, routerOffering.getId(), routerDeploymentDefinition.getVirtualProvider().getId(), VirtualMachineName.getRouterName(id,
s_vmInstanceName), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(),
userId, routerDeploymentDefinition.isRedundant(), 0, false, RedundantState.UNKNOWN, offerHA, false, vpcId);
userId, routerDeploymentDefinition.isRedundant(), RedundantState.UNKNOWN, offerHA, false, vpcId);
router.setDynamicallyScalable(template.isDynamicallyScalable());
router.setRole(Role.VIRTUAL_ROUTER);

View File

@ -115,7 +115,6 @@ import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
@ -1067,7 +1066,6 @@ Configurable, StateListener<State, VirtualMachine.Event, VirtualMachine> {
/*
* In order to make fail-over works well at any time, we have to ensure:
* 1. Backup router's priority = Master's priority - DELTA + 1
* 2. Backup router's priority hasn't been bumped up.
*/
private void checkSanity(final List<DomainRouterVO> routers) {
final Set<Long> checkedNetwork = new HashSet<Long>();
@ -1342,41 +1340,6 @@ Configurable, StateListener<State, VirtualMachine.Event, VirtualMachine> {
}
}
protected int getUpdatedPriority(final Network network, final List<DomainRouterVO> routers, final DomainRouterVO masterRouter)
throws InsufficientVirtualNetworkCapacityException {
int priority;
if (routers.size() == 0) {
priority = DEFAULT_PRIORITY;
} else {
int maxPriority = 0;
final DomainRouterVO router0 = routers.get(0);
if (router0.getId() == masterRouter.getId()) {
if (!router0.getIsRedundantRouter()) {
throw new CloudRuntimeException("Redundant router is mixed with single router in one network!");
}
maxPriority = _nwHelper.getRealPriority(router0);
} else {
maxPriority = DEFAULT_PRIORITY;
}
if (maxPriority == 0) {
return DEFAULT_PRIORITY;
}
if (maxPriority < 20) {
s_logger.error("Current maximum priority is too low!");
throw new InsufficientVirtualNetworkCapacityException("Current maximum priority is too low as " + maxPriority + "!", network.getId());
} else if (maxPriority > 200) {
s_logger.error("Too many times fail-over happened! Current maximum priority is too high as " + maxPriority + "!");
throw new InsufficientVirtualNetworkCapacityException("Too many times fail-over happened! Current maximum priority is too high as " + maxPriority + "!",
network.getId());
}
priority = maxPriority - DEFAULT_DELTA + 1;
}
return priority;
}
@Override
public boolean finalizeVirtualMachineProfile(final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context) {
@ -1621,7 +1584,7 @@ Configurable, StateListener<State, VirtualMachine.Event, VirtualMachine> {
return buf;
}
protected StringBuilder createRedundantRouterArgs(final NicProfile nic, DomainRouterVO router) {
protected StringBuilder createRedundantRouterArgs(final NicProfile nic, final DomainRouterVO router) {
final StringBuilder buf = new StringBuilder();
final long networkId = nic.getNetworkId();
@ -1673,17 +1636,6 @@ Configurable, StateListener<State, VirtualMachine.Event, VirtualMachine> {
}
buf.append(" redundant_state=").append(redundantState);
try {
final int priority = getUpdatedPriority(network, routers, router);
router.setPriority(priority);
router = _routerDao.persist(router);
buf.append(" router_pr=").append(router.getPriority());
} catch (final InsufficientVirtualNetworkCapacityException e) {
s_logger.error("Failed to get update priority!", e);
throw new CloudRuntimeException("Failed to get update priority!");
}
}
return buf;

View File

@ -338,7 +338,6 @@ public class RouterDeploymentDefinition {
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
//Check current redundant routers, if possible(all routers are stopped), reset the priority
planDeploymentRouters();
setupPriorityOfRedundantRouter();
if (getNumberOfRoutersToDeploy() > 0 && prepareDeployment()) {
findVirtualProvider();
@ -442,19 +441,4 @@ public class RouterDeploymentDefinition {
return needReset;
}
/**
* Only for redundant deployment and if any routers needed reset, we shall
* reset all routers priorities
*/
protected void setupPriorityOfRedundantRouter() {
if (isRedundant() && routersNeedReset()) {
for (final DomainRouterVO router : routers) {
// getUpdatedPriority() would update the value later
router.setPriority(0);
router.setIsPriorityBumpUp(false);
routerDao.update(router.getId(), router);
}
}
}
}

View File

@ -201,7 +201,7 @@ public class VirtualRouterElementTest {
mockDAOs(testNetwork, testOffering);
mockMgrs();
boolean done = virtualRouterElement.implement(testNetwork, testOffering, testDestination, testContext);
final boolean done = virtualRouterElement.implement(testNetwork, testOffering, testDestination, testContext);
assertTrue("no cigar for network daddy",done);
}
@ -209,7 +209,7 @@ public class VirtualRouterElementTest {
@Ignore("Ignore it until it's fixed in order not to brake the build")
public void testPrepare() {
virtualRouterElement._routerMgr = _routerMgr;
virtualRouterElement.routerDeploymentDefinitionBuilder = this.routerDeploymentDefinitionBuilder;
virtualRouterElement.routerDeploymentDefinitionBuilder = routerDeploymentDefinitionBuilder;
mockDAOs(testNetwork,testOffering);
mockMgrs();
@ -230,7 +230,7 @@ public class VirtualRouterElementTest {
* @throws ConcurrentOperationException
*/
private void mockMgrs() throws ConcurrentOperationException {
Service service = Service.Connectivity;
final Service service = Service.Connectivity;
testNetwork.setState(Network.State.Implementing);
testNetwork.setTrafficType(TrafficType.Guest);
when(_networkMdl.isProviderEnabledInPhysicalNetwork(0L, "VirtualRouter")).thenReturn(true);
@ -238,9 +238,9 @@ public class VirtualRouterElementTest {
when(_networkMdl.isProviderForNetwork(Network.Provider.VirtualRouter, 0L)).thenReturn(true);
when(testVMProfile.getType()).thenReturn(VirtualMachine.Type.User);
when(testVMProfile.getHypervisorType()).thenReturn(HypervisorType.XenServer);
List<NetworkVO> networks = new ArrayList<NetworkVO>(1);
final List<NetworkVO> networks = new ArrayList<NetworkVO>(1);
networks.add(testNetwork);
List<NetworkOfferingVO> offerings = new ArrayList<NetworkOfferingVO>(1);
final List<NetworkOfferingVO> offerings = new ArrayList<NetworkOfferingVO>(1);
offerings.add(testOffering);
doReturn(offerings).when(_networkModel).getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
doReturn(networks).when(_networkMgr).setupNetwork(any(Account.class), any(NetworkOffering.class), any(DeploymentPlan.class), any(String.class), any(String.class), anyBoolean());
@ -252,7 +252,7 @@ public class VirtualRouterElementTest {
/**
* @param network
*/
private void mockDAOs(NetworkVO network, NetworkOfferingVO offering) {
private void mockDAOs(final NetworkVO network, final NetworkOfferingVO offering) {
when(_networkDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network);
when(_networksDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network);
when(_physicalProviderDao.findByServiceProvider(0L, "VirtualRouter")).thenReturn(new PhysicalNetworkServiceProviderVO());
@ -260,7 +260,7 @@ public class VirtualRouterElementTest {
when(_networkOfferingDao.findById(0L)).thenReturn(offering);
// watchit: (in this test) there can be only one
when(_routerDao.getNextInSequence(Long.class, "id")).thenReturn(0L);
ServiceOfferingVO svcoff = new ServiceOfferingVO("name",
final ServiceOfferingVO svcoff = new ServiceOfferingVO("name",
/* cpu */ 1,
/* ramsize */ 1024*1024,
/* (clock?)speed */ 1024*1024*1024,
@ -276,7 +276,7 @@ public class VirtualRouterElementTest {
VirtualMachine.Type.DomainRouter,
/* defaultUse */ false);
when(_serviceOfferingDao.findById(0L)).thenReturn(svcoff);
DomainRouterVO router = new DomainRouterVO(/* id */ 1L,
final DomainRouterVO router = new DomainRouterVO(/* id */ 1L,
/* serviceOfferingId */ 1L,
/* elementId */ 0L,
"name",
@ -287,8 +287,6 @@ public class VirtualRouterElementTest {
/* accountId */ 1L,
/* userId */ 1L,
/* isRedundantRouter */ false,
/* priority */ 0,
/* isPriorityBumpUp */ false,
RedundantState.UNKNOWN,
/* haEnabled */ false,
/* stopPending */ false,

View File

@ -22,10 +22,7 @@ import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@ -526,117 +523,6 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
fail();
}
/**
* If any router is NOT redundant, then it shouldn't update routers
*/
@Test
public void testSetupPriorityOfRedundantRouterWithNonRedundantRouters() {
// Prepare
deployment.routers = new ArrayList<>();
final DomainRouterVO routerVO1 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO1);
when(routerVO1.getIsRedundantRouter()).thenReturn(true);
when(routerVO1.getState()).thenReturn(VirtualMachine.State.Stopped);
final DomainRouterVO routerVO2 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO2);
when(routerVO2.getIsRedundantRouter()).thenReturn(false);
when(routerVO2.getState()).thenReturn(VirtualMachine.State.Stopped);
// If this deployment is not redundant nothing will be executed
when(mockNw.isRedundant()).thenReturn(true);
// Execute
deployment.setupPriorityOfRedundantRouter();
// Assert
verify(routerVO1, times(0)).setPriority(anyInt());
verify(routerVO1, times(0)).setIsPriorityBumpUp(anyBoolean());
verify(mockRouterDao, times(0)).update(anyLong(), (DomainRouterVO) anyObject());
}
/**
* If any router is NOT Stopped, then it shouldn't update routers
*/
@Test
public void testSetupPriorityOfRedundantRouterWithRunningRouters() {
// Prepare
deployment.routers = new ArrayList<>();
final DomainRouterVO routerVO1 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO1);
when(routerVO1.getIsRedundantRouter()).thenReturn(true);
when(routerVO1.getState()).thenReturn(VirtualMachine.State.Stopped);
final DomainRouterVO routerVO2 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO2);
when(routerVO2.getIsRedundantRouter()).thenReturn(true);
when(routerVO2.getState()).thenReturn(VirtualMachine.State.Running);
// If this deployment is not redundant nothing will be executed
when(mockNw.isRedundant()).thenReturn(true);
// Execute
deployment.setupPriorityOfRedundantRouter();
// Assert
verify(routerVO1, times(0)).setPriority(anyInt());
verify(routerVO1, times(0)).setIsPriorityBumpUp(anyBoolean());
verify(mockRouterDao, times(0)).update(anyLong(), (DomainRouterVO) anyObject());
}
/**
* Given all routers are redundant and Stopped, then it should update ALL routers
*/
@Test
public void testSetupPriorityOfRedundantRouter() {
// Prepare
deployment.routers = new ArrayList<>();
final DomainRouterVO routerVO1 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO1);
when(routerVO1.getId()).thenReturn(ROUTER1_ID);
when(routerVO1.getIsRedundantRouter()).thenReturn(true);
when(routerVO1.getState()).thenReturn(VirtualMachine.State.Stopped);
final DomainRouterVO routerVO2 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO2);
when(routerVO2.getId()).thenReturn(ROUTER2_ID);
when(routerVO2.getIsRedundantRouter()).thenReturn(true);
when(routerVO2.getState()).thenReturn(VirtualMachine.State.Stopped);
// If this deployment is not redundant nothing will be executed
when(mockNw.isRedundant()).thenReturn(true);
// Execute
deployment.setupPriorityOfRedundantRouter();
// Assert
verify(routerVO1, times(1)).setPriority(0);
verify(routerVO1, times(1)).setIsPriorityBumpUp(false);
verify(mockRouterDao, times(1)).update(ROUTER1_ID, routerVO1);
verify(routerVO2, times(1)).setPriority(0);
verify(routerVO2, times(1)).setIsPriorityBumpUp(false);
verify(mockRouterDao, times(1)).update(ROUTER2_ID, routerVO2);
}
/**
* If this is not a redundant deployment, then we shouldn't reset priorities
*/
@Test
public void testSetupPriorityOfRedundantRouterWithNonRedundantDeployment() {
// Prepare
deployment.routers = new ArrayList<>();
final DomainRouterVO routerVO1 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO1);
when(routerVO1.getIsRedundantRouter()).thenReturn(true);
when(routerVO1.getState()).thenReturn(VirtualMachine.State.Stopped);
final DomainRouterVO routerVO2 = mock(DomainRouterVO.class);
deployment.routers.add(routerVO2);
when(routerVO2.getIsRedundantRouter()).thenReturn(true);
when(routerVO2.getState()).thenReturn(VirtualMachine.State.Stopped);
// Execute
deployment.setupPriorityOfRedundantRouter();
// Assert
verify(routerVO1, times(0)).setPriority(anyInt());
verify(routerVO1, times(0)).setIsPriorityBumpUp(anyBoolean());
verify(mockRouterDao, times(0)).update(anyLong(), (DomainRouterVO) anyObject());
}
@Test
public void testGetNumberOfRoutersToDeploy() {
// Prepare
@ -886,7 +772,6 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
// Prepare
final RouterDeploymentDefinition deploymentUT = spy(deployment);
doNothing().when(deploymentUT).setupPriorityOfRedundantRouter();
doReturn(noOfRoutersToDeploy).when(deploymentUT).getNumberOfRoutersToDeploy();
doReturn(passPreparation).when(deploymentUT).prepareDeployment();
doNothing().when(deploymentUT).findVirtualProvider();
@ -898,7 +783,6 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
deploymentUT.executeDeployment();
// Assert
verify(deploymentUT, times(1)).setupPriorityOfRedundantRouter();
verify(deploymentUT, times(1)).getNumberOfRoutersToDeploy();
int proceedToDeployment = 0;
if (noOfRoutersToDeploy > 0) {

View File

@ -21,4 +21,4 @@ if [ "$?" -ne "0" ]
then
STATUS=MASTER
fi
echo "Status: ${STATUS}&Bumped: NO"
echo "Status: ${STATUS}"

View File

@ -1,4 +1,4 @@
#!/bin/bash
#!/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
@ -16,45 +16,9 @@
# specific language governing permissions and limitations
# under the License.
source /root/func.sh
nolock=0
if [ $# -eq 1 ]
STATUS=$(cat /etc/cloudstack/cmdline.json | grep redundant_state | awk '{print $2;}' | sed -e 's/[,\"]//g')
if [ "$?" -ne "0" ]
then
if [ $1 == "--no-lock" ]
then
nolock=1
fi
fi
if [ $nolock -eq 0 ]
then
lock="biglock"
locked=$(getLockFile $lock)
if [ "$locked" != "1" ]
then
exit 1
fi
fi
bumped="Bumped: NO"
if [ -e /tmp/rrouter_bumped ]
then
bumped="Bumped: YES"
fi
state="Status: BACKUP"
isMaster=`grep -Po '(?<="redundant_master": ")[^"]*' /etc/cloudstack/cmdline.json`
if [ $? -eq 0 ]
then
if [ "$isMaster" = true ] ; then
state="Status: MASTER"
fi
echo "$state&$bumped"
fi
if [ $nolock -eq 0 ]
then
unlock_exit $? $lock $locked
STATUS=MASTER
fi
echo "Status: ${STATUS}"