sdn hosted vpc gateways (using lswitch)

This commit is contained in:
Daan Hoogland 2013-08-01 16:25:27 +02:00
parent 62b0ad03c8
commit 2614b00c51
49 changed files with 1958 additions and 1792 deletions

View File

@ -26,7 +26,7 @@ public class IpAddressTO {
private boolean add; private boolean add;
private boolean oneToOneNat; private boolean oneToOneNat;
private boolean firstIP; private boolean firstIP;
private String vlanId; private String broadcastUri;
private String vlanGateway; private String vlanGateway;
private String vlanNetmask; private String vlanNetmask;
private String vifMacAddress; private String vifMacAddress;
@ -34,14 +34,14 @@ public class IpAddressTO {
private TrafficType trafficType; private TrafficType trafficType;
private String networkName; private String networkName;
public IpAddressTO(long accountId, String ipAddress, boolean add, boolean firstIP, boolean sourceNat, String vlanId, public IpAddressTO(long accountId, String ipAddress, boolean add, boolean firstIP, boolean sourceNat, String broadcastUri,
String vlanGateway, String vlanNetmask, String vifMacAddress, Integer networkRate, boolean isOneToOneNat) { String vlanGateway, String vlanNetmask, String vifMacAddress, Integer networkRate, boolean isOneToOneNat) {
this.accountId = accountId; this.accountId = accountId;
this.publicIp = ipAddress; this.publicIp = ipAddress;
this.add = add; this.add = add;
this.firstIP = firstIP; this.firstIP = firstIP;
this.sourceNat = sourceNat; this.sourceNat = sourceNat;
this.vlanId = vlanId; this.broadcastUri = broadcastUri;
this.vlanGateway = vlanGateway; this.vlanGateway = vlanGateway;
this.vlanNetmask = vlanNetmask; this.vlanNetmask = vlanNetmask;
this.vifMacAddress = vifMacAddress; this.vifMacAddress = vifMacAddress;
@ -97,8 +97,8 @@ public class IpAddressTO {
return sourceNat; return sourceNat;
} }
public String getVlanId() { public String getBroadcastUri() {
return vlanId; return broadcastUri;
} }
public String getVlanGateway() { public String getVlanGateway() {

View File

@ -163,6 +163,10 @@ public class NetworkTO {
} }
public void setBroadcastUri(URI broadcastUri) { public void setBroadcastUri(URI broadcastUri) {
// only do this if the scheme needs aligning with the broadcastUri
if(broadcastUri != null && getBroadcastType() == null) {
setBroadcastType(BroadcastDomainType.getSchemeValue(broadcastUri));
}
this.broadcastUri = broadcastUri; this.broadcastUri = broadcastUri;
} }

View File

@ -19,11 +19,12 @@ package com.cloud.network;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.cloud.offering.NetworkOffering;
import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd; import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd;
import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd; import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd;
import org.apache.cloudstack.api.command.user.network.*; import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd;
import org.apache.cloudstack.api.command.user.network.ListNetworksCmd;
import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd;
import org.apache.cloudstack.api.command.user.vm.ListNicsCmd; import org.apache.cloudstack.api.command.user.vm.ListNicsCmd;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
@ -34,6 +35,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.GuestVlan; import com.cloud.network.GuestVlan;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.User; import com.cloud.user.User;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
@ -156,7 +158,7 @@ public interface NetworkService {
* @param networkName * @param networkName
* @param displayText * @param displayText
* @param physicalNetworkId * @param physicalNetworkId
* @param vlan * @param broadcastUri TODO set the guru name based on the broadcastUri?
* @param startIp * @param startIp
* @param endIP TODO * @param endIP TODO
* @param gateway * @param gateway
@ -169,8 +171,8 @@ public interface NetworkService {
* @throws ConcurrentOperationException * @throws ConcurrentOperationException
* @throws ResourceAllocationException * @throws ResourceAllocationException
*/ */
Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String broadcastUri,
String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat) String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat, Long networkOfferingId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
/* Requests an IP address for the guest nic */ /* Requests an IP address for the guest nic */

View File

@ -91,7 +91,7 @@ public class Networks {
@Override @Override
public <T> URI toUri(T value) { public <T> URI toUri(T value) {
try { try {
return new URI("lswitch",value.toString(),null,null); return new URI("lswitch", value.toString(), null, null);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new CloudRuntimeException( throw new CloudRuntimeException(
"Unable to convert to broadcast URI: " + value); "Unable to convert to broadcast URI: " + value);
@ -181,6 +181,7 @@ public class Networks {
* @return the value of this * @return the value of this
*/ */
public static BroadcastDomainType toEnumValue(String scheme) { public static BroadcastDomainType toEnumValue(String scheme) {
// scheme might be null and some of the enumvalue.scheme are as well, so
if (scheme == null) { if (scheme == null) {
return UnDecided; return UnDecided;
} }
@ -242,7 +243,7 @@ public class Networks {
try { try {
URI uri = new URI(candidate); URI uri = new URI(candidate);
BroadcastDomainType tiep = getSchemeValue(uri); BroadcastDomainType tiep = getSchemeValue(uri);
if (tiep.scheme.equals(uri.getScheme())) { if (tiep.scheme != null && tiep.scheme.equals(uri.getScheme())) {
return uri; return uri;
} else { } else {
throw new CloudRuntimeException("string '" + candidate + "' has an unknown BroadcastDomainType."); throw new CloudRuntimeException("string '" + candidate + "' has an unknown BroadcastDomainType.");

View File

@ -26,7 +26,7 @@ public interface PrivateIp {
/** /**
* @return * @return
*/ */
String getVlanTag(); String getBroadcastUri();
/** /**
* @return * @return

View File

@ -41,7 +41,7 @@ public class StaticRouteProfile implements StaticRoute {
this.gatewayId = staticRoute.getVpcGatewayId(); this.gatewayId = staticRoute.getVpcGatewayId();
this.state = staticRoute.getState(); this.state = staticRoute.getState();
this.vpcId = staticRoute.getVpcId(); this.vpcId = staticRoute.getVpcId();
this.vlanTag = gateway.getVlanTag(); this.vlanTag = gateway.getBroadcastUri();
this.gateway = gateway.getGateway(); this.gateway = gateway.getGateway();
this.netmask = gateway.getNetmask(); this.netmask = gateway.getNetmask();
this.ipAddress = gateway.getIp4Address(); this.ipAddress = gateway.getIp4Address();

View File

@ -71,7 +71,7 @@ public interface VpcGateway extends Identity, ControlledEntity, InternalIdentity
/** /**
* @return * @return
*/ */
String getVlanTag(); String getBroadcastUri();
/** /**
* @return * @return

View File

@ -150,6 +150,7 @@ public interface VpcService {
* @param gateway * @param gateway
* @param netmask * @param netmask
* @param gatewayOwnerId * @param gatewayOwnerId
* @param networkOfferingId
* @param isSourceNat * @param isSourceNat
* @param aclId * @param aclId
* @return * @return
@ -157,7 +158,7 @@ public interface VpcService {
* @throws ConcurrentOperationException * @throws ConcurrentOperationException
* @throws ResourceAllocationException * @throws ResourceAllocationException
*/ */
public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, String gateway, String netmask, long gatewayOwnerId, public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, String gateway, String netmask, long gatewayOwnerId, Long networkOfferingId,
Boolean isSoruceNat, Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; Boolean isSoruceNat, Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
/** /**

View File

@ -27,6 +27,7 @@ import org.apache.cloudstack.api.BaseAsyncCreateCmd;
import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.NetworkACLResponse;
import org.apache.cloudstack.api.response.NetworkOfferingResponse;
import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.cloudstack.api.response.PrivateGatewayResponse;
import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.VpcResponse;
@ -64,8 +65,12 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
@Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway") @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway")
private String ipAddress; private String ipAddress;
@Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the Vlan for the private gateway") @Parameter(name = ApiConstants.VLAN, type = CommandType.STRING, required = true, description = "the network implementation uri for the private gateway")
private String vlan; private String broadcastUri;
@Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, required = false, entityType = NetworkOfferingResponse.class,
description = "the uuid of the network offering to use for the private gateways network connection")
private Long networkOfferingId;
@Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class,
required=true, description="the VPC network belongs to") required=true, description="the VPC network belongs to")
@ -89,8 +94,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
return gateway; return gateway;
} }
public String getVlan() { public String getBroadcastUri() {
return vlan; return broadcastUri;
} }
public String getNetmask() { public String getNetmask() {
@ -105,6 +110,10 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
return physicalNetworkId; return physicalNetworkId;
} }
private Long getNetworkOfferingId() {
return networkOfferingId;
}
public Long getVpcId() { public Long getVpcId() {
return vpcId; return vpcId;
} }
@ -135,7 +144,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
PrivateGateway result = null; PrivateGateway result = null;
try { try {
result = _vpcService.createVpcPrivateGateway(getVpcId(), getPhysicalNetworkId(), result = _vpcService.createVpcPrivateGateway(getVpcId(), getPhysicalNetworkId(),
getVlan(), getStartIp(), getGateway(), getNetmask(), getEntityOwnerId(), getIsSourceNat(), getAclId()); getBroadcastUri(), getStartIp(), getGateway(), getNetmask(), getEntityOwnerId(), getNetworkOfferingId(), getIsSourceNat(), getAclId());
} catch (InsufficientCapacityException ex){ } catch (InsufficientCapacityException ex){
s_logger.info(ex); s_logger.info(ex);
s_logger.trace(ex); s_logger.trace(ex);

View File

@ -45,8 +45,8 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn
@SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the private gateway belongs to") @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the private gateway belongs to")
private String zoneName; private String zoneName;
@SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the private gateway") @SerializedName(ApiConstants.VLAN) @Param(description="the network implementation uri for the private gateway")
private String vlan; private String broadcastUri;
@SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the private gateaway belongs to") @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the private gateaway belongs to")
private String vpcId; private String vpcId;
@ -105,8 +105,8 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn
this.zoneId = zoneId; this.zoneId = zoneId;
} }
public void setVlan(String vlan) { public void setBroadcastUri(String broadcastUri) {
this.vlan = vlan; this.broadcastUri = broadcastUri;
} }
public void setZoneName(String zoneName) { public void setZoneName(String zoneName) {

View File

@ -16,6 +16,7 @@
// under the License. // under the License.
package com.cloud.network; package com.cloud.network;
import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import org.junit.Assert; import org.junit.Assert;
@ -24,6 +25,7 @@ import org.junit.Test;
import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.IsolationType;
import com.cloud.utils.exception.CloudRuntimeException;
/** /**
* @author dhoogland * @author dhoogland
@ -49,13 +51,10 @@ public class NetworksTest {
Long value2 = 2L; Long value2 = 2L;
String uri2 = BroadcastDomainType.Vlan.toUri(value2).toString(); String uri2 = BroadcastDomainType.Vlan.toUri(value2).toString();
BroadcastDomainType type1 = BroadcastDomainType.getTypeOf(uri1); BroadcastDomainType type1 = BroadcastDomainType.getTypeOf(uri1);
BroadcastDomainType type2 = BroadcastDomainType.getTypeOf(uri2);
String id1 = BroadcastDomainType.getValue(uri1); String id1 = BroadcastDomainType.getValue(uri1);
String id2 = BroadcastDomainType.getValue(uri2); String id2 = BroadcastDomainType.getValue(uri2);
Assert.assertEquals("uri1 should be of broadcasttype vlan", Assert.assertEquals("uri1 should be of broadcasttype vlan",
BroadcastDomainType.Vlan, type1); BroadcastDomainType.Vlan, type1);
Assert.assertEquals("uri2 should be of broadcasttype vlan",
BroadcastDomainType.Vlan, type2);
Assert.assertEquals("id1 should be \"1\"", "1", id1); Assert.assertEquals("id1 should be \"1\"", "1", id1);
Assert.assertEquals("id2 should be \"2\"", "2", id2); Assert.assertEquals("id2 should be \"2\"", "2", id2);
} }
@ -71,17 +70,44 @@ public class NetworksTest {
@Test @Test
public void otherTypesTest() throws URISyntaxException { public void otherTypesTest() throws URISyntaxException {
String bogeyUri = "lswitch://1"; String bogeyUri = "lswitch://0";
String uri1 = "lswitch:1";
String uri2 = "mido://2"; String uri2 = "mido://2";
BroadcastDomainType type1 = BroadcastDomainType.getTypeOf(bogeyUri); BroadcastDomainType type = BroadcastDomainType.getTypeOf(bogeyUri);
BroadcastDomainType type2 = BroadcastDomainType.getTypeOf(uri2); String id = BroadcastDomainType.getValue(bogeyUri);
String id1 = BroadcastDomainType.getValue(bogeyUri); Assert.assertEquals("uri0 should be of broadcasttype vlan",
String id2 = BroadcastDomainType.getValue(uri2); BroadcastDomainType.Lswitch, type);
Assert.assertEquals("uri1 should be of broadcasttype lswitch", Assert.assertEquals("id0 should be \"//0\"", "//0", id);
BroadcastDomainType.Lswitch, type1); type = BroadcastDomainType.getTypeOf(uri1);
Assert.assertEquals("uri2 should be of broadcasttype mido", id = BroadcastDomainType.getValue(uri1);
BroadcastDomainType.Mido, type2); Assert.assertEquals("uri1 should be of broadcasttype vlan",
Assert.assertEquals("id1 should be \"//1\"", "//1", id1); BroadcastDomainType.Lswitch, type);
Assert.assertEquals("id1 should be \"2\"", "2", id2); Assert.assertEquals("id1 should be \"1\"", "1", id);
type = BroadcastDomainType.getTypeOf(uri2);
id = BroadcastDomainType.getValue(uri2);
Assert.assertEquals("uri2 should be of broadcasttype vlan",
BroadcastDomainType.Mido, type);
Assert.assertEquals("id2 should be \"2\"", "2", id);
}
@Test
public void invalidTypesTest() throws URISyntaxException {
String uri1 = "https://1";
String uri2 = "bla:0";
BroadcastDomainType type = BroadcastDomainType.getTypeOf(uri1);
try {
/* URI result = */ BroadcastDomainType.fromString(uri1);
} catch (CloudRuntimeException e) {
Assert.assertEquals("unexpected parameter exception",
"string 'https://1' has an unknown BroadcastDomainType.",
e.getMessage());
}
try {
/* URI result = */ BroadcastDomainType.fromString(uri2);
} catch (CloudRuntimeException e) {
Assert.assertEquals("unexpected parameter exception",
"string 'bla:0' has an unknown BroadcastDomainType.",
e.getMessage());
}
} }
} }

View File

@ -16,6 +16,28 @@
// under the License. // under the License.
package com.cloud.agent.resource.virtualnetwork; package com.cloud.agent.resource.virtualnetwork;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
@ -69,27 +91,6 @@ import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SshHelper; import com.cloud.utils.ssh.SshHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* VirtualNetworkResource controls and configures virtual networking * VirtualNetworkResource controls and configures virtual networking
@ -99,7 +100,7 @@ import java.util.Map;
* || Param Name | Description | Values | Default || * || Param Name | Description | Values | Default ||
* } * }
**/ **/
@Local(value={VirtualRoutingResource.class}) @Local(value = {VirtualRoutingResource.class})
public class VirtualRoutingResource implements Manager { public class VirtualRoutingResource implements Manager {
private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class); private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class);
private String _savepasswordPath; // This script saves a random password to the DomR file system private String _savepasswordPath; // This script saves a random password to the DomR file system
@ -126,13 +127,13 @@ public class VirtualRoutingResource implements Manager {
public Answer executeRequest(final Command cmd) { public Answer executeRequest(final Command cmd) {
try { try {
if (cmd instanceof SetPortForwardingRulesVpcCommand ) { if (cmd instanceof SetPortForwardingRulesVpcCommand) {
return execute((SetPortForwardingRulesVpcCommand)cmd); return execute((SetPortForwardingRulesVpcCommand)cmd);
} else if (cmd instanceof SetPortForwardingRulesCommand){ } else if (cmd instanceof SetPortForwardingRulesCommand) {
return execute((SetPortForwardingRulesCommand)cmd); return execute((SetPortForwardingRulesCommand)cmd);
} else if (cmd instanceof SetStaticRouteCommand){ } else if (cmd instanceof SetStaticRouteCommand) {
return execute((SetStaticRouteCommand)cmd); return execute((SetStaticRouteCommand)cmd);
} else if (cmd instanceof SetStaticNatRulesCommand){ } else if (cmd instanceof SetStaticNatRulesCommand) {
return execute((SetStaticNatRulesCommand)cmd); return execute((SetStaticNatRulesCommand)cmd);
} else if (cmd instanceof LoadBalancerConfigCommand) { } else if (cmd instanceof LoadBalancerConfigCommand) {
return execute((LoadBalancerConfigCommand)cmd); return execute((LoadBalancerConfigCommand)cmd);
@ -140,22 +141,22 @@ public class VirtualRoutingResource implements Manager {
return execute((IpAssocCommand)cmd); return execute((IpAssocCommand)cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) { } else if (cmd instanceof CheckConsoleProxyLoadCommand) {
return execute((CheckConsoleProxyLoadCommand)cmd); return execute((CheckConsoleProxyLoadCommand)cmd);
} else if(cmd instanceof WatchConsoleProxyLoadCommand) { } else if (cmd instanceof WatchConsoleProxyLoadCommand) {
return execute((WatchConsoleProxyLoadCommand)cmd); return execute((WatchConsoleProxyLoadCommand)cmd);
} else if (cmd instanceof SavePasswordCommand) { } else if (cmd instanceof SavePasswordCommand) {
return execute((SavePasswordCommand)cmd); return execute((SavePasswordCommand)cmd);
} else if (cmd instanceof DhcpEntryCommand) { } else if (cmd instanceof DhcpEntryCommand) {
return execute((DhcpEntryCommand)cmd); return execute((DhcpEntryCommand)cmd);
} else if (cmd instanceof CreateIpAliasCommand) { } else if (cmd instanceof CreateIpAliasCommand) {
return execute((CreateIpAliasCommand) cmd); return execute((CreateIpAliasCommand)cmd);
} else if (cmd instanceof DnsMasqConfigCommand) { } else if (cmd instanceof DnsMasqConfigCommand) {
return execute((DnsMasqConfigCommand) cmd); return execute((DnsMasqConfigCommand)cmd);
} else if (cmd instanceof DeleteIpAliasCommand) { } else if (cmd instanceof DeleteIpAliasCommand) {
return execute((DeleteIpAliasCommand) cmd); return execute((DeleteIpAliasCommand)cmd);
} else if (cmd instanceof VmDataCommand) { } else if (cmd instanceof VmDataCommand) {
return execute ((VmDataCommand)cmd); return execute((VmDataCommand)cmd);
} else if (cmd instanceof CheckRouterCommand) { } else if (cmd instanceof CheckRouterCommand) {
return execute ((CheckRouterCommand)cmd); return execute((CheckRouterCommand)cmd);
} else if (cmd instanceof SetFirewallRulesCommand) { } else if (cmd instanceof SetFirewallRulesCommand) {
return execute((SetFirewallRulesCommand)cmd); return execute((SetFirewallRulesCommand)cmd);
} else if (cmd instanceof BumpUpPriorityCommand) { } else if (cmd instanceof BumpUpPriorityCommand) {
@ -180,13 +181,13 @@ public class VirtualRoutingResource implements Manager {
} }
private Answer execute(VpnUsersCfgCommand cmd) { private Answer execute(VpnUsersCfgCommand cmd) {
for (VpnUsersCfgCommand.UsernamePassword userpwd: cmd.getUserpwds()) { for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) {
String args = ""; String args = "";
if (!userpwd.isAdd()) { if (!userpwd.isAdd()) {
args +="-U "; args += "-U ";
args +=userpwd.getUsername(); args += userpwd.getUsername();
} else { } else {
args +="-u "; args += "-u ";
args += userpwd.getUsernamePassword(); args += userpwd.getUsernamePassword();
} }
String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args); String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args);
@ -210,7 +211,7 @@ public class VirtualRoutingResource implements Manager {
args += cmd.getLocalIp(); args += cmd.getLocalIp();
args += " -c "; args += " -c ";
} else { } else {
args +="-d "; args += "-d ";
args += " -s "; args += " -s ";
args += cmd.getVpnServerIp(); args += cmd.getVpnServerIp();
} }
@ -223,7 +224,7 @@ public class VirtualRoutingResource implements Manager {
private Answer execute(SetFirewallRulesCommand cmd) { private Answer execute(SetFirewallRulesCommand cmd) {
String[] results = new String[cmd.getRules().length]; String[] results = new String[cmd.getRules().length];
for (int i =0; i < cmd.getRules().length; i++) { for (int i = 0; i < cmd.getRules().length; i++) {
results[i] = "Failed"; results[i] = "Failed";
} }
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
@ -241,7 +242,7 @@ public class VirtualRoutingResource implements Manager {
command.add(routerIp); command.add(routerIp);
command.add("-F"); command.add("-F");
if (trafficType == FirewallRule.TrafficType.Egress){ if (trafficType == FirewallRule.TrafficType.Egress) {
command.add("-E"); command.add("-E");
if (egressDefault.equals("true")) { if (egressDefault.equals("true")) {
command.add("-P ", "1"); command.add("-P ", "1");
@ -267,7 +268,6 @@ public class VirtualRoutingResource implements Manager {
} }
return new SetFirewallRulesAnswer(cmd, true, null); return new SetFirewallRulesAnswer(cmd, true, null);
} }
private Answer execute(SetPortForwardingRulesCommand cmd) { private Answer execute(SetPortForwardingRulesCommand cmd) {
@ -311,7 +311,7 @@ public class VirtualRoutingResource implements Manager {
String result = routerProxy("vpc_staticnat.sh", routerIp, args); String result = routerProxy("vpc_staticnat.sh", routerIp, args);
if(result == null) { if (result == null) {
results[i++] = null; results[i++] = null;
} else { } else {
results[i++] = "Failed"; results[i++] = "Failed";
@ -323,7 +323,7 @@ public class VirtualRoutingResource implements Manager {
} }
private Answer execute(SetStaticNatRulesCommand cmd) { private Answer execute(SetStaticNatRulesCommand cmd) {
if ( cmd.getVpcId() != null ) { if (cmd.getVpcId() != null) {
return SetVPCStaticNatRules(cmd); return SetVPCStaticNatRules(cmd);
} }
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
@ -345,7 +345,7 @@ public class VirtualRoutingResource implements Manager {
} }
command.add(" -d ", rule.getStringSrcPortRange()); command.add(" -d ", rule.getStringSrcPortRange());
command.add(" -G ") ; command.add(" -G ");
result = command.execute(); result = command.execute();
if (result == null) { if (result == null) {
@ -376,57 +376,57 @@ public class VirtualRoutingResource implements Manager {
File permKey = new File("/root/.ssh/id_rsa.cloud"); File permKey = new File("/root/.ssh/id_rsa.cloud");
try { try {
SshHelper.scpTo(routerIp, 3922, "root", permKey, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); SshHelper.scpTo(routerIp, 3922, "root", permKey, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null);
String[][] rules = cfgtr.generateFwRules(cmd); String[][] rules = cfgtr.generateFwRules(cmd);
String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] addRules = rules[LoadBalancerConfigurator.ADD];
String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE];
String[] statRules = rules[LoadBalancerConfigurator.STATS]; String[] statRules = rules[LoadBalancerConfigurator.STATS];
String ip = cmd.getNic().getIp(); String ip = cmd.getNic().getIp();
String args = " -i " + ip; String args = " -i " + ip;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (addRules.length > 0) { if (addRules.length > 0) {
for (int i = 0; i < addRules.length; i++) { for (int i = 0; i < addRules.length; i++) {
sb.append(addRules[i]).append(','); sb.append(addRules[i]).append(',');
} }
args += " -a " + sb.toString(); args += " -a " + sb.toString();
} }
sb = new StringBuilder(); sb = new StringBuilder();
if (removeRules.length > 0) { if (removeRules.length > 0) {
for (int i = 0; i < removeRules.length; i++) { for (int i = 0; i < removeRules.length; i++) {
sb.append(removeRules[i]).append(','); sb.append(removeRules[i]).append(',');
} }
args += " -d " + sb.toString(); args += " -d " + sb.toString();
} }
sb = new StringBuilder(); sb = new StringBuilder();
if (statRules.length > 0) { if (statRules.length > 0) {
for (int i = 0; i < statRules.length; i++) { for (int i = 0; i < statRules.length; i++) {
sb.append(statRules[i]).append(','); sb.append(statRules[i]).append(',');
} }
args += " -s " + sb.toString(); args += " -s " + sb.toString();
} }
String result = routerProxy("vpc_loadbalancer.sh", routerIp, args); String result = routerProxy("vpc_loadbalancer.sh", routerIp, args);
if (result != null) { if (result != null) {
return new Answer(cmd, false, "LoadBalancerConfigCommand failed"); return new Answer(cmd, false, "LoadBalancerConfigCommand failed");
} }
return new Answer(cmd); return new Answer(cmd);
} catch (Exception e) { } catch (Exception e) {
return new Answer(cmd, e); return new Answer(cmd, e);
} }
} }
private Answer execute(LoadBalancerConfigCommand cmd) { private Answer execute(LoadBalancerConfigCommand cmd) {
if ( cmd.getVpcId() != null ) { if (cmd.getVpcId() != null) {
return VPCLoadBalancerConfig(cmd); return VPCLoadBalancerConfig(cmd);
} }
@ -439,9 +439,8 @@ public class VirtualRoutingResource implements Manager {
String[][] rules = cfgtr.generateFwRules(cmd); String[][] rules = cfgtr.generateFwRules(cmd);
if (routerIp != null) { if (routerIp != null) {
tmpCfgFile = File.createTempFile(routerIp.replace('.', '_'), "cfg"); tmpCfgFile = File.createTempFile(routerIp.replace('.', '_'), "cfg");
final PrintWriter out final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(tmpCfgFile)));
= new PrintWriter(new BufferedWriter(new FileWriter(tmpCfgFile))); for (int i = 0; i < config.length; i++) {
for (int i=0; i < config.length; i++) {
out.println(config[i]); out.println(config[i]);
} }
out.close(); out.close();
@ -492,19 +491,20 @@ public class VirtualRoutingResource implements Manager {
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
result = assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), result = assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(),
ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), ip.getVlanNetmask(),
ip.getVifMacAddress(), 2, false); ip.getVifMacAddress(), 2, false);
if (result != null) { if (result != null) {
results[i++] = IpAssocAnswer.errorResult; results[i++] = IpAssocAnswer.errorResult;
} else { } else {
results[i++] = ip.getPublicIp() + " - success";; results[i++] = ip.getPublicIp() + " - success";
;
} }
} }
return new IpAssocAnswer(cmd, results); return new IpAssocAnswer(cmd, results);
} }
private String setLoadBalancerConfig(final String cfgFile, private String setLoadBalancerConfig(final String cfgFile,
final String[] addRules, final String[] removeRules, final String[] statsRules,String routerIp) { final String[] addRules, final String[] removeRules, final String[] statsRules, String routerIp) {
if (routerIp == null) { if (routerIp == null) {
routerIp = "none"; routerIp = "none";
@ -517,7 +517,7 @@ public class VirtualRoutingResource implements Manager {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (addRules.length > 0) { if (addRules.length > 0) {
for (int i=0; i< addRules.length; i++) { for (int i = 0; i < addRules.length; i++) {
sb.append(addRules[i]).append(','); sb.append(addRules[i]).append(',');
} }
command.add("-a", sb.toString()); command.add("-a", sb.toString());
@ -525,7 +525,7 @@ public class VirtualRoutingResource implements Manager {
sb = new StringBuilder(); sb = new StringBuilder();
if (removeRules.length > 0) { if (removeRules.length > 0) {
for (int i=0; i< removeRules.length; i++) { for (int i = 0; i < removeRules.length; i++) {
sb.append(removeRules[i]).append(','); sb.append(removeRules[i]).append(',');
} }
command.add("-d", sb.toString()); command.add("-d", sb.toString());
@ -533,7 +533,7 @@ public class VirtualRoutingResource implements Manager {
sb = new StringBuilder(); sb = new StringBuilder();
if (statsRules.length > 0) { if (statsRules.length > 0) {
for (int i=0; i< statsRules.length; i++) { for (int i = 0; i < statsRules.length; i++) {
sb.append(statsRules[i]).append(','); sb.append(statsRules[i]).append(',');
} }
command.add("-s", sb.toString()); command.add("-s", sb.toString());
@ -547,7 +547,7 @@ public class VirtualRoutingResource implements Manager {
final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
final String vmName = cmd.getVmName(); final String vmName = cmd.getVmName();
final String vmIpAddress = cmd.getVmIpAddress(); final String vmIpAddress = cmd.getVmIpAddress();
final String local = vmName; final String local = vmName;
// Run save_password_to_domr.sh // Run save_password_to_domr.sh
final String result = savePassword(routerPrivateIPAddress, vmIpAddress, password, local); final String result = savePassword(routerPrivateIPAddress, vmIpAddress, password, local);
@ -558,11 +558,11 @@ public class VirtualRoutingResource implements Manager {
} }
} }
protected Answer execute (final DhcpEntryCommand cmd) { protected Answer execute(final DhcpEntryCommand cmd) {
final Script command = new Script(_dhcpEntryPath, _timeout, s_logger); final Script command = new Script(_dhcpEntryPath, _timeout, s_logger);
command.add("-r", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); command.add("-r", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
if (cmd.getVmIpAddress() != null) { if (cmd.getVmIpAddress() != null) {
command.add("-v", cmd.getVmIpAddress()); command.add("-v", cmd.getVmIpAddress());
} }
command.add("-m", cmd.getVmMac()); command.add("-m", cmd.getVmMac());
command.add("-n", cmd.getVmName()); command.add("-n", cmd.getVmName());
@ -571,66 +571,66 @@ public class VirtualRoutingResource implements Manager {
command.add("-d", cmd.getDefaultRouter()); command.add("-d", cmd.getDefaultRouter());
} }
if (cmd.getStaticRoutes() != null) { if (cmd.getStaticRoutes() != null) {
command.add("-s", cmd.getStaticRoutes()); command.add("-s", cmd.getStaticRoutes());
} }
if (cmd.getDefaultDns() != null) { if (cmd.getDefaultDns() != null) {
command.add("-N", cmd.getDefaultDns()); command.add("-N", cmd.getDefaultDns());
} }
if (cmd.getVmIp6Address() != null) { if (cmd.getVmIp6Address() != null) {
command.add("-6", cmd.getVmIp6Address()); command.add("-6", cmd.getVmIp6Address());
command.add("-u", cmd.getDuid()); command.add("-u", cmd.getDuid());
} }
if (!cmd.isDefault()) { if (!cmd.isDefault()) {
command.add("-z"); command.add("-z");
} }
final String result = command.execute(); final String result = command.execute();
return new Answer(cmd, result==null, result); return new Answer(cmd, result == null, result);
} }
protected Answer execute(final CreateIpAliasCommand cmd) { protected Answer execute(final CreateIpAliasCommand cmd) {
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
final Script command = new Script(_createIpAliasPath, _timeout, s_logger); final Script command = new Script(_createIpAliasPath, _timeout, s_logger);
List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList(); List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
String args = ""; String args = "";
command.add(routerIp); command.add(routerIp);
for (IpAliasTO ipaliasto : ipAliasTOs) { for (IpAliasTO ipaliasto : ipAliasTOs) {
args = args + ipaliasto.getAlias_count()+":"+ipaliasto.getRouterip()+":"+ipaliasto.getNetmask()+"-"; args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-";
} }
command.add(args); command.add(args);
final String result = command.execute(); final String result = command.execute();
return new Answer(cmd, result==null, result); return new Answer(cmd, result == null, result);
} }
protected Answer execute(final DeleteIpAliasCommand cmd) { protected Answer execute(final DeleteIpAliasCommand cmd) {
final Script command = new Script(_deleteIpAliasPath, _timeout, s_logger); final Script command = new Script(_deleteIpAliasPath, _timeout, s_logger);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String args =""; String args = "";
command.add(routerIp); command.add(routerIp);
List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos();
for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
} }
args = args + "- " ; args = args + "- ";
List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos(); List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos();
for (IpAliasTO ipAliasTO : activeIpAliasTOs) { for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
} }
command.add(args); command.add(args);
final String result = command.execute(); final String result = command.execute();
return new Answer(cmd, result==null, result); return new Answer(cmd, result == null, result);
} }
protected Answer execute(final DnsMasqConfigCommand cmd) { protected Answer execute(final DnsMasqConfigCommand cmd) {
final Script command = new Script(_callDnsMasqPath, _timeout, s_logger); final Script command = new Script(_callDnsMasqPath, _timeout, s_logger);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
List<DhcpTO> dhcpTos = cmd.getIps(); List<DhcpTO> dhcpTos = cmd.getIps();
String args =""; String args = "";
for(DhcpTO dhcpTo : dhcpTos) { for (DhcpTO dhcpTo : dhcpTos) {
args = args + dhcpTo.getRouterIp()+":"+dhcpTo.getGateway()+":"+dhcpTo.getNetmask()+":"+dhcpTo.getStartIpOfSubnet()+"-"; args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-";
} }
command.add(routerIp); command.add(routerIp);
command.add(args); command.add(args);
@ -642,13 +642,12 @@ public class VirtualRoutingResource implements Manager {
return routerProxyWithParser("checkrouter.sh", routerIP, null); return routerProxyWithParser("checkrouter.sh", routerIP, null);
} }
public String routerProxyWithParser(String script, String routerIP, String args) { public String routerProxyWithParser(String script, String routerIP, String args) {
final Script command = new Script(_routerProxyPath, _timeout, s_logger); final Script command = new Script(_routerProxyPath, _timeout, s_logger);
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
command.add(script); command.add(script);
command.add(routerIP); command.add(routerIP);
if ( args != null ) { if (args != null) {
command.add(args); command.add(args);
} }
String result = command.execute(parser); String result = command.execute(parser);
@ -674,10 +673,10 @@ public class VirtualRoutingResource implements Manager {
} }
public String routerProxy(String script, String routerIP, String args) { public String routerProxy(String script, String routerIP, String args) {
final Script command = new Script(_routerProxyPath, _timeout, s_logger); final Script command = new Script(_routerProxyPath, _timeout, s_logger);
command.add(script); command.add(script);
command.add(routerIP); command.add(routerIP);
if ( args != null ) { if (args != null) {
command.add(args); command.add(args);
} }
return command.execute(); return command.execute();
@ -695,7 +694,7 @@ public class VirtualRoutingResource implements Manager {
protected Answer execute(BumpUpPriorityCommand cmd) { protected Answer execute(BumpUpPriorityCommand cmd) {
final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
final Script command = new Script(_bumpUpPriorityPath, _timeout, s_logger); final Script command = new Script(_bumpUpPriorityPath, _timeout, s_logger);
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
command.add(routerPrivateIPAddress); command.add(routerPrivateIPAddress);
String result = command.execute(parser); String result = command.execute(parser);
@ -736,31 +735,31 @@ public class VirtualRoutingResource implements Manager {
if (cmd.isCreate()) { if (cmd.isCreate()) {
args = "-A"; args = "-A";
args += " -l "; args += " -l ";
args += cmd.getLocalPublicIp(); args += cmd.getLocalPublicIp();
args += " -n "; args += " -n ";
args += cmd.getLocalGuestCidr(); args += cmd.getLocalGuestCidr();
args += " -g "; args += " -g ";
args += cmd.getLocalPublicGateway(); args += cmd.getLocalPublicGateway();
args += " -r "; args += " -r ";
args += cmd.getPeerGatewayIp(); args += cmd.getPeerGatewayIp();
args += " -N "; args += " -N ";
args += cmd.getPeerGuestCidrList(); args += cmd.getPeerGuestCidrList();
args += " -e "; args += " -e ";
args += "\"" + cmd.getEspPolicy() + "\""; args += "\"" + cmd.getEspPolicy() + "\"";
args += " -i "; args += " -i ";
args += "\"" + cmd.getIkePolicy() + "\""; args += "\"" + cmd.getIkePolicy() + "\"";
args += " -t "; args += " -t ";
args += Long.toString(cmd.getIkeLifetime()); args += Long.toString(cmd.getIkeLifetime());
args += " -T "; args += " -T ";
args += Long.toString(cmd.getEspLifetime()); args += Long.toString(cmd.getEspLifetime());
args += " -s "; args += " -s ";
args += "\"" + cmd.getIpsecPsk() + "\""; args += "\"" + cmd.getIpsecPsk() + "\"";
args += " -d "; args += " -d ";
if (cmd.getDpd()) { if (cmd.getDpd()) {
args += "1"; args += "1";
} else { } else {
args += "0"; args += "0";
} }
} else { } else {
args = "-D"; args = "-D";
args += " -r "; args += " -r ";
@ -807,7 +806,7 @@ public class VirtualRoutingResource implements Manager {
success = false; success = false;
} }
} }
} catch(final IOException e) { } catch (final IOException e) {
s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp);
success = false; success = false;
} }
@ -815,11 +814,8 @@ public class VirtualRoutingResource implements Manager {
return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result);
} }
public String savePassword(final String privateIpAddress, final String vmIpAddress, final String password, final String localPath) { public String savePassword(final String privateIpAddress, final String vmIpAddress, final String password, final String localPath) {
final Script command = new Script(_savepasswordPath, _startTimeout, s_logger); final Script command = new Script(_savepasswordPath, _startTimeout, s_logger);
command.add("-r", privateIpAddress); command.add("-r", privateIpAddress);
command.add("-v", vmIpAddress); command.add("-v", vmIpAddress);
command.add("-p", password); command.add("-p", password);
@ -830,7 +826,7 @@ public class VirtualRoutingResource implements Manager {
public String assignGuestNetwork(final String dev, final String routerIP, public String assignGuestNetwork(final String dev, final String routerIP,
final String routerGIP, final String gateway, final String cidr, final String routerGIP, final String gateway, final String cidr,
final String netmask, final String dns, final String domainName){ final String netmask, final String dns, final String domainName) {
String args = " -C"; String args = " -C";
args += " -d " + dev; args += " -d " + dev;
@ -838,17 +834,17 @@ public class VirtualRoutingResource implements Manager {
args += " -g " + gateway; args += " -g " + gateway;
args += " -m " + cidr; args += " -m " + cidr;
args += " -n " + netmask; args += " -n " + netmask;
if ( dns != null && !dns.isEmpty() ) { if (dns != null && !dns.isEmpty()) {
args += " -s " + dns; args += " -s " + dns;
} }
if ( domainName != null && !domainName.isEmpty() ) { if (domainName != null && !domainName.isEmpty()) {
args += " -e " + domainName; args += " -e " + domainName;
} }
return routerProxy("vpc_guestnw.sh", routerIP, args); return routerProxy("vpc_guestnw.sh", routerIP, args);
} }
public String assignNetworkACL(final String routerIP, final String dev, public String assignNetworkACL(final String routerIP, final String dev,
final String routerGIP, final String netmask, final String rule, String privateGw){ final String routerGIP, final String netmask, final String rule, String privateGw) {
String args = " -d " + dev; String args = " -d " + dev;
if (privateGw != null) { if (privateGw != null) {
args += " -a " + rule; args += " -a " + rule;
@ -897,7 +893,7 @@ public class VirtualRoutingResource implements Manager {
} }
public void assignVpcIpToRouter(final String routerIP, final boolean add, final String pubIP, public void assignVpcIpToRouter(final String routerIP, final boolean add, final String pubIP,
final String nicname, final String gateway, final String netmask, final String subnet, boolean sourceNat) throws InternalErrorException { final String nicname, final String gateway, final String netmask, final String subnet, boolean sourceNat) throws InternalErrorException {
String args = ""; String args = "";
String snatArgs = ""; String snatArgs = "";
@ -922,7 +918,7 @@ public class VirtualRoutingResource implements Manager {
String result = routerProxy("vpc_ipassoc.sh", routerIP, args); String result = routerProxy("vpc_ipassoc.sh", routerIP, args);
if (result != null) { if (result != null) {
throw new InternalErrorException("KVM plugin \"vpc_ipassoc\" failed:"+result); throw new InternalErrorException("KVM plugin \"vpc_ipassoc\" failed:" + result);
} }
if (sourceNat) { if (sourceNat) {
snatArgs += " -l " + pubIP; snatArgs += " -l " + pubIP;
@ -930,7 +926,7 @@ public class VirtualRoutingResource implements Manager {
result = routerProxy("vpc_privateGateway.sh", routerIP, snatArgs); result = routerProxy("vpc_privateGateway.sh", routerIP, snatArgs);
if (result != null) { if (result != null) {
throw new InternalErrorException("KVM plugin \"vpc_privateGateway\" failed:"+result); throw new InternalErrorException("KVM plugin \"vpc_privateGateway\" failed:" + result);
} }
} }
@ -940,7 +936,7 @@ public class VirtualRoutingResource implements Manager {
String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
try { try {
String[] results = new String[cmd.getStaticRoutes().length]; String[] results = new String[cmd.getStaticRoutes().length];
String [][] rules = cmd.generateSRouteRules(); String[][] rules = cmd.generateSRouteRules();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String[] srRules = rules[0]; String[] srRules = rules[0];
@ -952,7 +948,7 @@ public class VirtualRoutingResource implements Manager {
String result = routerProxy("vpc_staticroute.sh", routerIP, args); String result = routerProxy("vpc_staticroute.sh", routerIP, args);
if (result != null) { if (result != null) {
for (int i=0; i < results.length; i++) { for (int i = 0; i < results.length; i++) {
results[i] = "Failed"; results[i] = "Failed";
} }
return new SetStaticRouteAnswer(cmd, false, results); return new SetStaticRouteAnswer(cmd, false, results);
@ -966,12 +962,11 @@ public class VirtualRoutingResource implements Manager {
} }
} }
public String assignPublicIpAddress(final String vmName, public String assignPublicIpAddress(final String vmName,
final String privateIpAddress, final String publicIpAddress, final String privateIpAddress, final String publicIpAddress,
final boolean add, final boolean firstIP, final boolean sourceNat, final boolean add, final boolean firstIP, final boolean sourceNat,
final String vlanId, final String vlanGateway, final String broadcastUri, final String vlanGateway,
final String vlanNetmask, final String vifMacAddress, int nicNum, boolean newNic){ final String vlanNetmask, final String vifMacAddress, int nicNum, boolean newNic) {
String args = ""; String args = "";
if (add) { if (add) {
@ -981,7 +976,7 @@ public class VirtualRoutingResource implements Manager {
} }
String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask));
if (sourceNat) { if (sourceNat) {
args +=" -s"; args += " -s";
} }
if (firstIP) { if (firstIP) {
args += " -f"; args += " -f";
@ -993,7 +988,7 @@ public class VirtualRoutingResource implements Manager {
args += " -c "; args += " -c ";
args += publicNic; args += publicNic;
args +=" -g "; args += " -g ";
args += vlanGateway; args += vlanGateway;
if (newNic) { if (newNic) {
@ -1025,7 +1020,7 @@ public class VirtualRoutingResource implements Manager {
private void stopDnsmasq(String dnsmasqName) { private void stopDnsmasq(String dnsmasqName) {
Script cmd = new Script("/bin/sh", _timeout); Script cmd = new Script("/bin/sh", _timeout);
cmd.add("-c"); cmd.add("-c");
cmd.add("kill -9 `cat /var/run/libvirt/network/" + dnsmasqName +".pid`"); cmd.add("kill -9 `cat /var/run/libvirt/network/" + dnsmasqName + ".pid`");
cmd.execute(); cmd.execute();
} }
@ -1094,13 +1089,13 @@ public class VirtualRoutingResource implements Manager {
_scriptsDir = (String)params.get("domr.scripts.dir"); _scriptsDir = (String)params.get("domr.scripts.dir");
if (_scriptsDir == null) { if (_scriptsDir == null) {
if(s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default" ); s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default");
} }
_scriptsDir = getDefaultScriptsDir(); _scriptsDir = getDefaultScriptsDir();
} }
if(s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir); s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir);
} }
@ -1135,12 +1130,12 @@ public class VirtualRoutingResource implements Manager {
} }
_savepasswordPath = findScript("save_password_to_domr.sh"); _savepasswordPath = findScript("save_password_to_domr.sh");
if(_savepasswordPath == null) { if (_savepasswordPath == null) {
throw new ConfigurationException("Unable to find save_password_to_domr.sh"); throw new ConfigurationException("Unable to find save_password_to_domr.sh");
} }
_dhcpEntryPath = findScript("dhcp_entry.sh"); _dhcpEntryPath = findScript("dhcp_entry.sh");
if(_dhcpEntryPath == null) { if (_dhcpEntryPath == null) {
throw new ConfigurationException("Unable to find dhcp_entry.sh"); throw new ConfigurationException("Unable to find dhcp_entry.sh");
} }
@ -1157,7 +1152,7 @@ public class VirtualRoutingResource implements Manager {
_privateEthIf = _privateEthIf.toLowerCase(); _privateEthIf = _privateEthIf.toLowerCase();
_bumpUpPriorityPath = findScript("bumpUpPriority.sh"); _bumpUpPriorityPath = findScript("bumpUpPriority.sh");
if(_bumpUpPriorityPath == null) { if (_bumpUpPriorityPath == null) {
throw new ConfigurationException("Unable to find bumpUpPriority.sh"); throw new ConfigurationException("Unable to find bumpUpPriority.sh");
} }
@ -1171,17 +1166,16 @@ public class VirtualRoutingResource implements Manager {
} }
_deleteIpAliasPath = findScript("deleteipAlias.sh"); _deleteIpAliasPath = findScript("deleteipAlias.sh");
if (_deleteIpAliasPath == null) { if (_deleteIpAliasPath == null) {
throw new ConfigurationException("unable to find deleteipAlias.sh"); throw new ConfigurationException("unable to find deleteipAlias.sh");
} }
_callDnsMasqPath = findScript("call_dnsmasq.sh"); _callDnsMasqPath = findScript("call_dnsmasq.sh");
if (_callDnsMasqPath == null) { if (_callDnsMasqPath == null) {
throw new ConfigurationException("unable to find call_dnsmasq.sh"); throw new ConfigurationException("unable to find call_dnsmasq.sh");
} }
return true; return true;
} }
public String connect(final String ipAddress) { public String connect(final String ipAddress) {
return connect(ipAddress, _port); return connect(ipAddress, _port);
} }
@ -1207,7 +1201,8 @@ public class VirtualRoutingResource implements Manager {
if (sch != null) { if (sch != null) {
try { try {
sch.close(); sch.close();
} catch (final IOException e) {} } catch (final IOException e) {
}
} }
} }
try { try {
@ -1221,7 +1216,6 @@ public class VirtualRoutingResource implements Manager {
return "Unable to connect"; return "Unable to connect";
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
@ -1229,10 +1223,9 @@ public class VirtualRoutingResource implements Manager {
@Override @Override
public void setName(String name) { public void setName(String name) {
_name = name; _name = name;
} }
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
@ -1245,29 +1238,27 @@ public class VirtualRoutingResource implements Manager {
@Override @Override
public int getRunLevel() { public int getRunLevel() {
return ComponentLifecycle.RUN_LEVEL_COMPONENT; return ComponentLifecycle.RUN_LEVEL_COMPONENT;
} }
public void setRunLevel() { public void setRunLevel() {
} }
@Override @Override
public void setConfigParams(Map<String, Object> params) { public void setConfigParams(Map<String, Object> params) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public Map<String, Object> getConfigParams() { public Map<String, Object> getConfigParams() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
@Override @Override
public void setRunLevel(int level) { public void setRunLevel(int level) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -104,7 +104,7 @@ public interface NetworkDao extends GenericDao<NetworkVO, Long> , StateDao<State
List<NetworkVO> listByVpc(long vpcId); List<NetworkVO> listByVpc(long vpcId);
NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId); NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId, Long networkOfferingId);
long countVpcNetworks(long vpcId); long countVpcNetworks(long vpcId);

View File

@ -562,13 +562,16 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
@Override @Override
public NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId) { public NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId, Long networkOfferingId) {
if (networkOfferingId == null) {
networkOfferingId = _ntwkOffDao.findByUniqueName(NetworkOffering.SystemPrivateGatewayNetworkOffering).getId();
}
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
sc.setParameters("datacenter", zoneId); sc.setParameters("datacenter", zoneId);
sc.setParameters("broadcastUri", broadcastUri); sc.setParameters("broadcastUri", broadcastUri);
sc.setParameters("cidr", cidr); sc.setParameters("cidr", cidr);
sc.setParameters("account", accountId); sc.setParameters("account", accountId);
sc.setParameters("offering", _ntwkOffDao.findByUniqueName(NetworkOffering.SystemPrivateGatewayNetworkOffering).getId()); sc.setParameters("offering", networkOfferingId);
return findOneBy(sc); return findOneBy(sc);
} }

View File

@ -50,7 +50,7 @@ public class VpcGatewayVO implements VpcGateway {
String netmask; String netmask;
@Column(name="vlan_tag") @Column(name="vlan_tag")
String vlanTag; String broadcastUri;
@Column(name = "type") @Column(name = "type")
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
@ -102,7 +102,7 @@ public class VpcGatewayVO implements VpcGateway {
* @param vpcId * @param vpcId
* @param zoneId * @param zoneId
* @param networkId * @param networkId
* @param vlanTag TODO * @param broadcastUri TODO
* @param gateway TODO * @param gateway TODO
* @param netmask TODO * @param netmask TODO
* @param accountId TODO * @param accountId TODO
@ -110,14 +110,14 @@ public class VpcGatewayVO implements VpcGateway {
* @param account_id * @param account_id
* @param sourceNat * @param sourceNat
*/ */
public VpcGatewayVO(String ip4Address, Type type, long vpcId, long zoneId, long networkId, String vlanTag, public VpcGatewayVO(String ip4Address, Type type, long vpcId, long zoneId, long networkId, String broadcastUri,
String gateway, String netmask, long accountId, long domainId, boolean sourceNat, long networkACLId) { String gateway, String netmask, long accountId, long domainId, boolean sourceNat, long networkACLId) {
this.ip4Address = ip4Address; this.ip4Address = ip4Address;
this.type = type; this.type = type;
this.vpcId = vpcId; this.vpcId = vpcId;
this.zoneId = zoneId; this.zoneId = zoneId;
this.networkId = networkId; this.networkId = networkId;
this.vlanTag = vlanTag; this.broadcastUri = broadcastUri;
this.gateway = gateway; this.gateway = gateway;
this.netmask = netmask; this.netmask = netmask;
this.uuid = UUID.randomUUID().toString(); this.uuid = UUID.randomUUID().toString();
@ -182,8 +182,8 @@ public class VpcGatewayVO implements VpcGateway {
} }
@Override @Override
public String getVlanTag() { public String getBroadcastUri() {
return vlanTag; return broadcastUri;
} }
@Override @Override

View File

@ -75,7 +75,7 @@ import com.cloud.utils.db.ScriptRunner;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@Local(value = { SystemIntegrityChecker.class }) @Local(value = {SystemIntegrityChecker.class})
public class DatabaseUpgradeChecker implements SystemIntegrityChecker { public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
private final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class); private final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class);
@ -85,114 +85,122 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
public DatabaseUpgradeChecker() { public DatabaseUpgradeChecker() {
_dao = new VersionDaoImpl(); _dao = new VersionDaoImpl();
_upgradeMap.put("2.1.7", new DbUpgrade[] { new Upgrade217to218(), new Upgrade218to22(), new Upgrade221to222(), _upgradeMap.put("2.1.7", new DbUpgrade[] {new Upgrade217to218(), new Upgrade218to22(), new Upgrade221to222(),
new UpgradeSnapshot217to224(), new Upgrade222to224(), new Upgrade224to225(), new Upgrade225to226(), new UpgradeSnapshot217to224(), new Upgrade222to224(), new Upgrade224to225(), new Upgrade225to226(),
new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(),
new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.1.8", new DbUpgrade[] { new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(), _upgradeMap.put("2.1.8", new DbUpgrade[] {new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(),
new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(), new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(),
new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(),
new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.1.9", new DbUpgrade[] { new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(), _upgradeMap.put("2.1.9", new DbUpgrade[] {new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(),
new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(), new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(),
new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(),
new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.1", new DbUpgrade[] { new Upgrade221to222(), new UpgradeSnapshot223to224(), new Upgrade222to224(), _upgradeMap.put("2.2.1", new DbUpgrade[] {new Upgrade221to222(), new UpgradeSnapshot223to224(), new Upgrade222to224(),
new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(),
new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("2.2.2", new DbUpgrade[] { new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(), _upgradeMap.put("2.2.2", new DbUpgrade[] {new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(),
new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.3", new DbUpgrade[] { new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(), _upgradeMap.put("2.2.3", new DbUpgrade[] {new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(),
new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.4", new DbUpgrade[] { new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(), _upgradeMap.put("2.2.4", new DbUpgrade[] {new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(),
new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(),
new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.5", new DbUpgrade[] { new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), _upgradeMap.put("2.2.5", new DbUpgrade[] {new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(),
new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.6", new DbUpgrade[] { new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), _upgradeMap.put("2.2.6", new DbUpgrade[] {new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.7", new DbUpgrade[] { new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(), _upgradeMap.put("2.2.7", new DbUpgrade[] {new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("2.2.8", new DbUpgrade[] { new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), _upgradeMap.put("2.2.8", new DbUpgrade[] {new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(),
new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30() new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30()
, new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); , new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.9", new DbUpgrade[] { new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), _upgradeMap.put("2.2.9", new DbUpgrade[] {new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(),
new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.10", new DbUpgrade[] { new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), _upgradeMap.put("2.2.10", new DbUpgrade[] {new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("2.2.11", new DbUpgrade[] { new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), _upgradeMap.put("2.2.11", new DbUpgrade[] {new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.12", new DbUpgrade[] { new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), _upgradeMap.put("2.2.12", new DbUpgrade[] {new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.13", new DbUpgrade[] { new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), _upgradeMap.put("2.2.13", new DbUpgrade[] {new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.14", new DbUpgrade[] { new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), _upgradeMap.put("2.2.14", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.0", new DbUpgrade[] {new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("3.0.1", new DbUpgrade[] {new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.0", new DbUpgrade[] { new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.2", new DbUpgrade[] {new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.1", new DbUpgrade[] { new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.0.0", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.2", new DbUpgrade[] { new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.0.1", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("4.0.0", new DbUpgrade[] { new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.0.2", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("4.0.1", new DbUpgrade[] { new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.1.0", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("4.0.2", new DbUpgrade[] { new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.1.1", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("4.1.0", new DbUpgrade[] { new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("4.2.0", new DbUpgrade[] {new Upgrade420to430()});
_upgradeMap.put("4.2.0", new DbUpgrade[] { new Upgrade420to430() });
//CP Upgrades //CP Upgrades
_upgradeMap.put("3.0.3", new DbUpgrade[] { new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.3", new DbUpgrade[] {new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(),
new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.4", new DbUpgrade[] { new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.4", new DbUpgrade[] {new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("3.0.5", new DbUpgrade[] { new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.5", new DbUpgrade[] {new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.6", new DbUpgrade[] { new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.6", new DbUpgrade[] {new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("3.0.7", new DbUpgrade[] { new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430() }); _upgradeMap.put("3.0.7", new DbUpgrade[] {new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430()});
_upgradeMap.put("2.2.15", new DbUpgrade[] { new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), _upgradeMap.put("2.2.15", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(),new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430()}); new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(),
new Upgrade420to430()});
_upgradeMap.put("2.2.16", new DbUpgrade[] { new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), _upgradeMap.put("2.2.16", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(),new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to430()}); new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(),
new Upgrade420to430()});
} }
protected void runScript(Connection conn, File file) { protected void runScript(Connection conn, File file) {
@ -225,8 +233,10 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
} }
if (Version.compare(trimmedCurrentVersion, upgrades[upgrades.length - 1].getUpgradedVersion()) != 0) { if (Version.compare(trimmedCurrentVersion, upgrades[upgrades.length - 1].getUpgradedVersion()) != 0) {
s_logger.error("The end upgrade version is actually at " + upgrades[upgrades.length - 1].getUpgradedVersion() + " but our management server code version is at " + currentVersion); s_logger.error("The end upgrade version is actually at " + upgrades[upgrades.length - 1].getUpgradedVersion() + " but our management server code version is at "
throw new CloudRuntimeException("The end upgrade version is actually at " + upgrades[upgrades.length - 1].getUpgradedVersion() + " but our management server code version is at " + currentVersion);
throw new CloudRuntimeException("The end upgrade version is actually at " + upgrades[upgrades.length - 1].getUpgradedVersion()
+ " but our management server code version is at "
+ currentVersion); + currentVersion);
} }
@ -241,11 +251,13 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
if (!supportsRollingUpgrade && false) { // FIXME: Needs to detect if there are management servers running if (!supportsRollingUpgrade && false) { // FIXME: Needs to detect if there are management servers running
// ClusterManagerImpl.arePeersRunning(null)) { // ClusterManagerImpl.arePeersRunning(null)) {
s_logger.error("Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running"); s_logger.error("Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running");
throw new CloudRuntimeException("Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running"); throw new CloudRuntimeException(
"Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running");
} }
for (DbUpgrade upgrade : upgrades) { for (DbUpgrade upgrade : upgrades) {
s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade.getUpgradableVersionRange()[1] s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-"
+ upgrade.getUpgradableVersionRange()[1]
+ " to " + upgrade.getUpgradedVersion()); + " to " + upgrade.getUpgradedVersion());
Transaction txn = Transaction.open("Upgrade"); Transaction txn = Transaction.open("Upgrade");
txn.start(); txn.start();
@ -289,10 +301,10 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
} }
txn.commit(); txn.commit();
} catch (CloudRuntimeException e){ } catch (CloudRuntimeException e) {
s_logger.error("Unable to upgrade the database", e); s_logger.error("Unable to upgrade the database", e);
throw new CloudRuntimeException("Unable to upgrade the database", e); throw new CloudRuntimeException("Unable to upgrade the database", e);
}finally { } finally {
txn.close(); txn.close();
} }
} }
@ -375,7 +387,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
currentVersion = this.getClass().getSuperclass().getPackage().getImplementationVersion(); currentVersion = this.getClass().getSuperclass().getPackage().getImplementationVersion();
} }
if ( currentVersion == null ) if (currentVersion == null)
return; return;
s_logger.info("DB version = " + dbVersion + " Code Version = " + currentVersion); s_logger.info("DB version = " + dbVersion + " Code Version = " + currentVersion);

View File

@ -57,7 +57,7 @@ import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext; import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@Local(value = { NetworkGuru.class }) @Local(value = {NetworkGuru.class})
public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru { public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru {
private static final Logger s_logger = Logger.getLogger(BaremetaNetworkGuru.class); private static final Logger s_logger = Logger.getLogger(BaremetaNetworkGuru.class);
@Inject @Inject

View File

@ -54,13 +54,12 @@ public class BridgeVifDriver extends VifDriverBase {
// Set the domr scripts directory // Set the domr scripts directory
params.put("domr.scripts.dir", "scripts/network/domr/kvm"); params.put("domr.scripts.dir", "scripts/network/domr/kvm");
String networkScriptsDir = (String)params.get("network.scripts.dir");
String networkScriptsDir = (String) params.get("network.scripts.dir");
if (networkScriptsDir == null) { if (networkScriptsDir == null) {
networkScriptsDir = "scripts/vm/network/vnet"; networkScriptsDir = "scripts/vm/network/vnet";
} }
String value = (String) params.get("scripts.timeout"); String value = (String)params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;
_modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
@ -94,10 +93,10 @@ public class BridgeVifDriver extends VifDriverBase {
} }
String trafficLabel = nic.getName(); String trafficLabel = nic.getName();
if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getType() == Networks.TrafficType.Guest) {
Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1)? nic.getNetworkRateMbps().intValue() * 128: 0; Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0;
if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) { && !vlanId.equalsIgnoreCase("untagged")) {
if(trafficLabel != null && !trafficLabel.isEmpty()) { if (trafficLabel != null && !trafficLabel.isEmpty()) {
s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel);
String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); String brName = createVlanBr(vlanId, _pifs.get(trafficLabel));
intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
@ -113,10 +112,10 @@ public class BridgeVifDriver extends VifDriverBase {
createControlNetwork(); createControlNetwork();
intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType));
} else if (nic.getType() == Networks.TrafficType.Public) { } else if (nic.getType() == Networks.TrafficType.Public) {
Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1)? nic.getNetworkRateMbps().intValue() * 128: 0; Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0;
if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) { && !vlanId.equalsIgnoreCase("untagged")) {
if(trafficLabel != null && !trafficLabel.isEmpty()){ if (trafficLabel != null && !trafficLabel.isEmpty()) {
s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel);
String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); String brName = createVlanBr(vlanId, _pifs.get(trafficLabel));
intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
@ -143,7 +142,7 @@ public class BridgeVifDriver extends VifDriverBase {
} }
private String setVnetBrName(String pifName, String vnetId) { private String setVnetBrName(String pifName, String vnetId) {
String brName = "br" + pifName + "-"+ vnetId; String brName = "br" + pifName + "-" + vnetId;
String oldStyleBrName = "cloudVirBr" + vnetId; String oldStyleBrName = "cloudVirBr" + vnetId;
String cmdout = Script.runSimpleBashScript("brctl show | grep " + oldStyleBrName); String cmdout = Script.runSimpleBashScript("brctl show | grep " + oldStyleBrName);
@ -179,7 +178,7 @@ public class BridgeVifDriver extends VifDriverBase {
} }
} }
private void deleteVnetBr(String brName){ private void deleteVnetBr(String brName) {
synchronized (_vnetBridgeMonitor) { synchronized (_vnetBridgeMonitor) {
String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | grep vnet"); String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | grep vnet");
if (cmdout != null && cmdout.contains("vnet")) { if (cmdout != null && cmdout.contains("vnet")) {
@ -199,7 +198,7 @@ public class BridgeVifDriver extends VifDriverBase {
pName = "undefined"; pName = "undefined";
vNetId = oldStyleBrNameMatcher.group(1); vNetId = oldStyleBrNameMatcher.group(1);
} else if (brNameMatcher.find()) { } else if (brNameMatcher.find()) {
if(brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) {
pName = brNameMatcher.group(1); pName = brNameMatcher.group(1);
} else { } else {
pName = "undefined"; pName = "undefined";
@ -208,7 +207,7 @@ public class BridgeVifDriver extends VifDriverBase {
} }
if (vNetId == null || vNetId.isEmpty()) { if (vNetId == null || vNetId.isEmpty()) {
s_logger.debug("unable to get a vNet ID from name "+ brName); s_logger.debug("unable to get a vNet ID from name " + brName);
return; return;
} }

View File

@ -1720,15 +1720,15 @@ ServerResource {
return new Answer(cmd, true, result); return new Answer(cmd, true, result);
} }
private void VifHotPlug(Connect conn, String vmName, String vlanId, private void VifHotPlug(Connect conn, String vmName, String broadcastUri,
String macAddr) throws InternalErrorException, LibvirtException { String macAddr) throws InternalErrorException, LibvirtException {
NicTO nicTO = new NicTO(); NicTO nicTO = new NicTO();
nicTO.setMac(macAddr); nicTO.setMac(macAddr);
nicTO.setType(TrafficType.Public); nicTO.setType(TrafficType.Public);
if (vlanId == null) { if (broadcastUri == null) {
nicTO.setBroadcastType(BroadcastDomainType.Native); nicTO.setBroadcastType(BroadcastDomainType.Native);
} else { } else {
URI uri = BroadcastDomainType.fromString(vlanId); URI uri = BroadcastDomainType.fromString(broadcastUri);
nicTO.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); nicTO.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
nicTO.setBroadcastUri(uri); nicTO.setBroadcastUri(uri);
} }
@ -1908,7 +1908,7 @@ ServerResource {
try { try {
conn = LibvirtConnection.getConnectionByVmName(routerName); conn = LibvirtConnection.getConnectionByVmName(routerName);
Integer devNum = 0; Integer devNum = 0;
String pubVlan = pubIP.getVlanId(); String pubVlan = pubIP.getBroadcastUri();
List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName);
for (InterfaceDef pluggedNic : pluggedNics) { for (InterfaceDef pluggedNic : pluggedNics) {
@ -1972,7 +1972,7 @@ ServerResource {
} }
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
String nicName = "eth" + vlanToNicNum.get(ip.getVlanId()); String nicName = "eth" + vlanToNicNum.get(ip.getBroadcastUri());
String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
_virtRouterResource.assignVpcIpToRouter(routerIP, ip.isAdd(), ip.getPublicIp(), _virtRouterResource.assignVpcIpToRouter(routerIP, ip.isAdd(), ip.getPublicIp(),
@ -2023,18 +2023,18 @@ ServerResource {
int nicNum = 0; int nicNum = 0;
boolean newNic = false; boolean newNic = false;
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) { if (!vlanAllocatedToVM.containsKey(ip.getBroadcastUri())) {
/* plug a vif into router */ /* plug a vif into router */
VifHotPlug(conn, routerName, ip.getVlanId(), VifHotPlug(conn, routerName, ip.getBroadcastUri(),
ip.getVifMacAddress()); ip.getVifMacAddress());
vlanAllocatedToVM.put(ip.getVlanId(), nicPos++); vlanAllocatedToVM.put(ip.getBroadcastUri(), nicPos++);
newNic = true; newNic = true;
} }
nicNum = vlanAllocatedToVM.get(ip.getVlanId()); nicNum = vlanAllocatedToVM.get(ip.getBroadcastUri());
networkUsage(routerIp, "addVif", "eth" + nicNum); networkUsage(routerIp, "addVif", "eth" + nicNum);
result = _virtRouterResource.assignPublicIpAddress(routerName, result = _virtRouterResource.assignPublicIpAddress(routerName,
routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(),
ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(),
ip.getVlanNetmask(), ip.getVifMacAddress(), nicNum, newNic); ip.getVlanNetmask(), ip.getVifMacAddress(), nicNum, newNic);
if (result != null) { if (result != null) {

View File

@ -42,12 +42,12 @@ public class OvsVifDriver extends VifDriverBase {
public void configure(Map<String, Object> params) throws ConfigurationException { public void configure(Map<String, Object> params) throws ConfigurationException {
super.configure(params); super.configure(params);
String networkScriptsDir = (String) params.get("network.scripts.dir"); String networkScriptsDir = (String)params.get("network.scripts.dir");
if (networkScriptsDir == null) { if (networkScriptsDir == null) {
networkScriptsDir = "scripts/vm/network/vnet"; networkScriptsDir = "scripts/vm/network/vnet";
} }
String value = (String) params.get("scripts.timeout"); String value = (String)params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;
createControlNetwork(_bridges.get("linklocal")); createControlNetwork(_bridges.get("linklocal"));
@ -74,10 +74,10 @@ public class OvsVifDriver extends VifDriverBase {
} }
String trafficLabel = nic.getName(); String trafficLabel = nic.getName();
if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getType() == Networks.TrafficType.Guest) {
Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1)? nic.getNetworkRateMbps().intValue() * 128: 0; Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0;
if ((nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Pvlan) if ((nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Pvlan)
&& !vlanId.equalsIgnoreCase("untagged")) { && !vlanId.equalsIgnoreCase("untagged")) {
if(trafficLabel != null && !trafficLabel.isEmpty()) { if (trafficLabel != null && !trafficLabel.isEmpty()) {
s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel);
intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
intf.setVlanTag(Integer.parseInt(vlanId)); intf.setVlanTag(Integer.parseInt(vlanId));
@ -99,10 +99,10 @@ public class OvsVifDriver extends VifDriverBase {
createControlNetwork(_bridges.get("linklocal")); createControlNetwork(_bridges.get("linklocal"));
intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType));
} else if (nic.getType() == Networks.TrafficType.Public) { } else if (nic.getType() == Networks.TrafficType.Public) {
Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1)? nic.getNetworkRateMbps().intValue() * 128: 0; Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0;
if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) { && !vlanId.equalsIgnoreCase("untagged")) {
if(trafficLabel != null && !trafficLabel.isEmpty()){ if (trafficLabel != null && !trafficLabel.isEmpty()) {
s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel);
intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
intf.setVlanTag(Integer.parseInt(vlanId)); intf.setVlanTag(Integer.parseInt(vlanId));
@ -128,18 +128,6 @@ public class OvsVifDriver extends VifDriverBase {
// Libvirt apparently takes care of this, see BridgeVifDriver unplug // Libvirt apparently takes care of this, see BridgeVifDriver unplug
} }
private String setVnetBrName(String pifName, String vnetId) {
String brName = "br" + pifName + "-"+ vnetId;
String oldStyleBrName = "cloudVirBr" + vnetId;
if (isBridgeExists(oldStyleBrName)) {
s_logger.info("Using old style bridge name for vlan " + vnetId + " because existing bridge " + oldStyleBrName + " was found");
brName = oldStyleBrName;
}
return brName;
}
private void deleteExitingLinkLocalRouteTable(String linkLocalBr) { private void deleteExitingLinkLocalRouteTable(String linkLocalBr) {
Script command = new Script("/bin/bash", _timeout); Script command = new Script("/bin/bash", _timeout);
command.add("-c"); command.add("-c");

View File

@ -1793,7 +1793,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
} }
protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP,
final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { final boolean sourceNat, final String broadcastId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception {
/**
* TODO support other networks
*/
URI broadcastUri = BroadcastDomainType.fromString(broadcastId);
if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) {
throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + broadcastId);
}
String vlanId = BroadcastDomainType.getValue(broadcastUri);
String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId);
Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName);
@ -2011,7 +2020,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
} }
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), ip.getVlanNetmask(),
ip.getVifMacAddress()); ip.getVifMacAddress());
results[i++] = ip.getPublicIp() + " - success"; results[i++] = ip.getPublicIp() + " - success";
} }

View File

@ -1062,7 +1062,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
return network.getNetwork(); return network.getNetwork();
} else if (type == BroadcastDomainType.Pvlan) { } else if (type == BroadcastDomainType.Pvlan) {
assert BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Pvlan; assert BroadcastDomainType.getSchemeValue(uri) == BroadcastDomainType.Pvlan;
// TODO considder moving this NetUtils method to BroadcastDomainType // should we consider moving this NetUtils method to BroadcastDomainType?
long vlan = Long.parseLong(NetUtils.getPrimaryPvlanFromUri(uri)); long vlan = Long.parseLong(NetUtils.getPrimaryPvlanFromUri(uri));
return enableVlanNetwork(conn, vlan, network); return enableVlanNetwork(conn, vlan, network);
} }
@ -2445,7 +2445,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
IpAddressTO[] ips = cmd.getIpAddresses(); IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
assignPublicIpAddress(conn, routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), assignPublicIpAddress(conn, routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(),
ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), ip.getNetworkRate(), ip.getTrafficType(), ip.getNetworkName()); ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), ip.getNetworkRate(), ip.getTrafficType(), ip.getNetworkName());
results[i++] = ip.getPublicIp() + " - success"; results[i++] = ip.getPublicIp() + " - success";
} }
@ -4202,10 +4202,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
NicTO nic = new NicTO(); NicTO nic = new NicTO();
nic.setType(ip.getTrafficType()); nic.setType(ip.getTrafficType());
nic.setName(ip.getNetworkName()); nic.setName(ip.getNetworkName());
if (ip.getVlanId() == null) { if (ip.getBroadcastUri() == null) {
nic.setBroadcastType(BroadcastDomainType.Native); nic.setBroadcastType(BroadcastDomainType.Native);
} else { } else {
URI uri = BroadcastDomainType.fromString(ip.getVlanId()); URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri());
nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
nic.setBroadcastUri(uri); nic.setBroadcastUri(uri);
} }

View File

@ -247,7 +247,7 @@ public class BigSwitchVnsGuestNetworkGuru extends GuestNetworkGuru {
String tenantId = profile.getNetworkDomain(); String tenantId = profile.getNetworkDomain();
DeleteVnsNetworkCommand cmd = new DeleteVnsNetworkCommand(tenantId, DeleteVnsNetworkCommand cmd = new DeleteVnsNetworkCommand(tenantId,
networkObject.getBroadcastUri().getSchemeSpecificPart()); BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
_agentMgr.easySend(bigswitchVnsHost.getId(), cmd); _agentMgr.easySend(bigswitchVnsHost.getId(), cmd);
super.shutdown(profile, offering); super.shutdown(profile, offering);

View File

@ -132,8 +132,8 @@ import com.cloud.vm.VirtualMachineProfile;
@Local(value = NetworkElement.class) @Local(value = NetworkElement.class)
public class CiscoVnmcElement extends AdapterBase implements SourceNatServiceProvider, FirewallServiceProvider, public class CiscoVnmcElement extends AdapterBase implements SourceNatServiceProvider, FirewallServiceProvider,
PortForwardingServiceProvider, IpDeployer, StaticNatServiceProvider, ResourceStateAdapter, NetworkElement, PortForwardingServiceProvider, IpDeployer, StaticNatServiceProvider, ResourceStateAdapter, NetworkElement,
CiscoVnmcElementService, CiscoAsa1000vService { CiscoVnmcElementService, CiscoAsa1000vService {
private static final Logger s_logger = Logger.getLogger(CiscoVnmcElement.class); private static final Logger s_logger = Logger.getLogger(CiscoVnmcElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@ -375,7 +375,8 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
try { try {
outsideIp = _ipAddrMgr.associateIPToGuestNetwork(outsideIp.getId(), network.getId(), true); outsideIp = _ipAddrMgr.associateIPToGuestNetwork(outsideIp.getId(), network.getId(), true);
} catch (ResourceAllocationException e) { } catch (ResourceAllocationException e) {
s_logger.error("Unable to assign allocated additional public Ip " + outsideIp.getAddress().addr() + " to network with vlan " + vlanId + ". Exception details " + e); s_logger.error("Unable to assign allocated additional public Ip " + outsideIp.getAddress().addr() + " to network with vlan " + vlanId + ". Exception details "
+ e);
return false; return false;
} }
} }
@ -532,7 +533,8 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
} }
long zoneId = physicalNetwork.getDataCenterId(); long zoneId = physicalNetwork.getDataCenterId();
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder()); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(),
networkDevice.getNetworkServiceProvder());
if (ntwkSvcProvider == null) { if (ntwkSvcProvider == null) {
throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() +
" is not enabled in the physical network: " + physicalNetworkId + "to add this device"); " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
@ -545,7 +547,7 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
throw new CloudRuntimeException("A Cisco Vnmc device is already configured on this physical network"); throw new CloudRuntimeException("A Cisco Vnmc device is already configured on this physical network");
} }
Map<String, String> params = new HashMap<String,String>(); Map<String, String> params = new HashMap<String, String>();
params.put("guid", UUID.randomUUID().toString()); params.put("guid", UUID.randomUUID().toString());
params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
@ -554,7 +556,7 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
params.put("username", cmd.getUsername()); params.put("username", cmd.getUsername());
params.put("password", cmd.getPassword()); params.put("password", cmd.getPassword());
Map<String, Object> hostdetails = new HashMap<String,Object>(); Map<String, Object> hostdetails = new HashMap<String, Object>();
hostdetails.putAll(params); hostdetails.putAll(params);
ServerResource resource = new CiscoVnmcResource(); ServerResource resource = new CiscoVnmcResource();
@ -614,7 +616,7 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
if (responseList.size() > 0) { if (responseList.size() > 0) {
throw new CloudRuntimeException( throw new CloudRuntimeException(
"Cisco VNMC appliance with id " + vnmcResourceId + "Cisco VNMC appliance with id " + vnmcResourceId +
" cannot be deleted as there Cisco ASA 1000v appliances using it"); " cannot be deleted as there Cisco ASA 1000v appliances using it");
} }
} }
@ -687,7 +689,8 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
} }
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -745,7 +748,8 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
} }
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply port forwarding rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply port forwarding rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -800,7 +804,8 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
} }
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply static NAT rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply static NAT rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -913,7 +918,7 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro
if (networkAsaMap != null) { if (networkAsaMap != null) {
throw new CloudRuntimeException( throw new CloudRuntimeException(
"Cisco ASA 1000v appliance with id " + asaResourceId + "Cisco ASA 1000v appliance with id " + asaResourceId +
" cannot be deleted as it is associated with guest network"); " cannot be deleted as it is associated with guest network");
} }
_ciscoAsa1000vDao.remove(asaResourceId); _ciscoAsa1000vDao.remove(asaResourceId);

View File

@ -294,8 +294,9 @@ public class F5BigIpResource implements ServerResource {
try { try {
IpAddressTO[] ips = cmd.getIpAddresses(); IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
// TODO BroadcastDomain.getValue(ip.getVlanId) ??? // is it saver to use Long.valueOf(BroadcastDomain.getValue(ip.getBroadcastUri())) ???
long guestVlanTag = Long.valueOf(ip.getVlanId()); // i.o.w. can this contain vlan:// then change !!!
long guestVlanTag = Long.valueOf(ip.getBroadcastUri());
// It's a hack, using isOneToOneNat field for indicate if it's inline or not // It's a hack, using isOneToOneNat field for indicate if it's inline or not
boolean inline = ip.isOneToOneNat(); boolean inline = ip.isOneToOneNat();
String vlanSelfIp = inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); String vlanSelfIp = inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway();

View File

@ -68,6 +68,7 @@ import com.cloud.host.Host;
import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.resource.ServerResource; import com.cloud.resource.ServerResource;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.exception.ExecutionException;
@ -697,11 +698,11 @@ public class JuniperSrxResource implements ServerResource {
String guestVlanSubnet = NetUtils.getCidrSubNet(guestVlanGateway, cidrSize); String guestVlanSubnet = NetUtils.getCidrSubNet(guestVlanGateway, cidrSize);
Long publicVlanTag = null; Long publicVlanTag = null;
if (ip.getVlanId() != null && !ip.getVlanId().equals("untagged")) { if (ip.getBroadcastUri() != null && !ip.getBroadcastUri().equals("untagged")) {
try { try {
publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(ip.getVlanId())); publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(ip.getVlanId()));
} catch (Exception e) { } catch (Exception e) {
throw new ExecutionException("Could not parse public VLAN tag: " + ip.getVlanId()); throw new ExecutionException("Could not parse public VLAN tag: " + ip.getBroadcastUri());
} }
} }

View File

@ -442,7 +442,7 @@ public class NetscalerResource implements ServerResource {
try { try {
IpAddressTO[] ips = cmd.getIpAddresses(); IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) { for (IpAddressTO ip : ips) {
long guestVlanTag = Long.valueOf(ip.getVlanId()); long guestVlanTag = Long.valueOf(ip.getBroadcastUri());
String vlanSelfIp = ip.getVlanGateway(); String vlanSelfIp = ip.getVlanGateway();
String vlanNetmask = ip.getVlanNetmask(); String vlanNetmask = ip.getVlanNetmask();

View File

@ -127,9 +127,9 @@ import com.cloud.vm.dao.NicDao;
SourceNatServiceProvider.class, StaticNatServiceProvider.class, SourceNatServiceProvider.class, StaticNatServiceProvider.class,
PortForwardingServiceProvider.class, IpDeployer.class} ) PortForwardingServiceProvider.class, IpDeployer.class} )
public class NiciraNvpElement extends AdapterBase implements public class NiciraNvpElement extends AdapterBase implements
ConnectivityProvider, SourceNatServiceProvider, ConnectivityProvider, SourceNatServiceProvider,
PortForwardingServiceProvider, StaticNatServiceProvider, PortForwardingServiceProvider, StaticNatServiceProvider,
NiciraNvpElementService, ResourceStateAdapter, IpDeployer { NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger
.getLogger(NiciraNvpElement.class); .getLogger(NiciraNvpElement.class);
@ -216,8 +216,8 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
@Override @Override
public boolean implement(Network network, NetworkOffering offering, public boolean implement(Network network, NetworkOffering offering,
DeployDestination dest, ReservationContext context) DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException, throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException { InsufficientCapacityException {
s_logger.debug("entering NiciraNvpElement implement function for network " s_logger.debug("entering NiciraNvpElement implement function for network "
+ network.getDisplayText() + network.getDisplayText()
+ " (state " + " (state "
@ -276,10 +276,10 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
BroadcastDomainType.getValue(network.getBroadcastUri()), BroadcastDomainType.getValue(network.getBroadcastUri()),
"router-" + network.getDisplayText(), publicCidr, "router-" + network.getDisplayText(), publicCidr,
sourceNatIp.getGateway(), internalCidr, context sourceNatIp.getGateway(), internalCidr, context
.getDomain().getName() .getDomain().getName()
+ "-" + "-"
+ context.getAccount().getAccountName()); + context.getAccount().getAccountName());
CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer) _agentMgr CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer)_agentMgr
.easySend(niciraNvpHost.getId(), cmd); .easySend(niciraNvpHost.getId(), cmd);
if (answer.getResult() == false) { if (answer.getResult() == false) {
s_logger.error("Failed to create Logical Router for network " s_logger.error("Failed to create Logical Router for network "
@ -293,7 +293,6 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
_niciraNvpRouterMappingDao.persist(routermapping); _niciraNvpRouterMappingDao.persist(routermapping);
} }
return true; return true;
} }
@ -331,7 +330,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand( FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(
existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchUuid(),
existingNicMap.getLogicalSwitchPortUuid()); existingNicMap.getLogicalSwitchPortUuid());
FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) _agentMgr FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer)_agentMgr
.easySend(niciraNvpHost.getId(), findCmd); .easySend(niciraNvpHost.getId(), findCmd);
if (answer.getResult()) { if (answer.getResult()) {
@ -343,7 +342,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
BroadcastDomainType.getValue(network.getBroadcastUri()), BroadcastDomainType.getValue(network.getBroadcastUri()),
nicVO.getUuid(), context.getDomain().getName() + "-" nicVO.getUuid(), context.getDomain().getName() + "-"
+ context.getAccount().getAccountName(), + context.getAccount().getAccountName(),
nic.getName()); nic.getName());
_agentMgr.easySend(niciraNvpHost.getId(), cmd); _agentMgr.easySend(niciraNvpHost.getId(), cmd);
return true; return true;
} else { } else {
@ -358,7 +357,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
BroadcastDomainType.getValue(network.getBroadcastUri()), BroadcastDomainType.getValue(network.getBroadcastUri()),
nicVO.getUuid(), context.getDomain().getName() + "-" nicVO.getUuid(), context.getDomain().getName() + "-"
+ context.getAccount().getAccountName(), nic.getName()); + context.getAccount().getAccountName(), nic.getName());
CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer)_agentMgr
.easySend(niciraNvpHost.getId(), cmd); .easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
@ -410,7 +409,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand( DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(
nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchUuid(),
nicMap.getLogicalSwitchPortUuid()); nicMap.getLogicalSwitchPortUuid());
DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer)_agentMgr
.easySend(niciraNvpHost.getId(), cmd); .easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
@ -458,7 +457,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid());
DeleteLogicalRouterAnswer answer = DeleteLogicalRouterAnswer answer =
(DeleteLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); (DeleteLogicalRouterAnswer)_agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer.getResult() == false) { if (answer.getResult() == false) {
s_logger.error("Failed to delete LogicalRouter for network " s_logger.error("Failed to delete LogicalRouter for network "
+ network.getDisplayText()); + network.getDisplayText());
@ -489,7 +488,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
@Override @Override
public boolean shutdownProviderInstances( public boolean shutdownProviderInstances(
PhysicalNetworkServiceProvider provider, ReservationContext context) PhysicalNetworkServiceProvider provider, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException { throws ConcurrentOperationException, ResourceUnavailableException {
// Nothing to do here. // Nothing to do here.
return true; return true;
} }
@ -763,7 +762,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
.listByPhysicalNetwork(physicalNetworkId); .listByPhysicalNetwork(physicalNetworkId);
// Networks with broadcast type lswitch are ours // Networks with broadcast type lswitch are ours
List<NetworkVO> responseList = new ArrayList<NetworkVO>(); List<NetworkVO> responseList = new ArrayList<NetworkVO>();
for (NetworkVO network : networkList) { for (NetworkVO network : networkList) {
if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
responseList.add(network); responseList.add(network);
@ -820,7 +819,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
@Override @Override
public boolean applyIps(Network network, public boolean applyIps(Network network,
List<? extends PublicIpAddress> ipAddress, Set<Service> services) List<? extends PublicIpAddress> ipAddress, Set<Service> services)
throws ResourceUnavailableException { throws ResourceUnavailableException {
if (services.contains(Service.SourceNat)) { if (services.contains(Service.SourceNat)) {
// Only if we need to provide SourceNat we need to configure the logical router // Only if we need to provide SourceNat we need to configure the logical router
// SourceNat is required for StaticNat and PortForwarding // SourceNat is required for StaticNat and PortForwarding
@ -854,7 +853,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
} }
ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(),
niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs);
ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)_agentMgr.easySend(niciraNvpHost.getId(), cmd);
//FIXME answer can be null if the host is down //FIXME answer can be null if the host is down
return answer.getResult(); return answer.getResult();
} }
@ -871,7 +870,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
@Override @Override
public boolean applyStaticNats(Network network, public boolean applyStaticNats(Network network,
List<? extends StaticNat> rules) List<? extends StaticNat> rules)
throws ResourceUnavailableException { throws ResourceUnavailableException {
if (!canHandle(network, Service.StaticNat)) { if (!canHandle(network, Service.StaticNat)) {
return false; return false;
} }
@ -909,7 +908,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
ConfigureStaticNatRulesOnLogicalRouterCommand cmd = ConfigureStaticNatRulesOnLogicalRouterCommand cmd =
new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules);
ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer)_agentMgr.easySend(niciraNvpHost.getId(), cmd);
return answer.getResult(); return answer.getResult();
} }
@ -952,7 +951,7 @@ NiciraNvpElementService, ResourceStateAdapter, IpDeployer {
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = ConfigurePortForwardingRulesOnLogicalRouterCommand cmd =
new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules);
ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)_agentMgr.easySend(niciraNvpHost.getId(), cmd);
return answer.getResult(); return answer.getResult();
} }

View File

@ -41,11 +41,11 @@ import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao; import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkModel; import com.cloud.network.NetworkModel;
import com.cloud.network.NetworkProfile; import com.cloud.network.NetworkProfile;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetwork;
@ -65,11 +65,10 @@ import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@Local(value=NetworkGuru.class) @Local(value = NetworkGuru.class)
public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
private static final Logger s_logger = Logger.getLogger(NiciraNvpGuestNetworkGuru.class); private static final Logger s_logger = Logger.getLogger(NiciraNvpGuestNetworkGuru.class);
@Inject @Inject
NetworkModel _networkModel; NetworkModel _networkModel;
@Inject @Inject
@ -95,7 +94,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
public NiciraNvpGuestNetworkGuru() { public NiciraNvpGuestNetworkGuru() {
super(); super();
_isolationMethods = new IsolationMethod[] { IsolationMethod.STT }; _isolationMethods = new IsolationMethod[] {IsolationMethod.STT};
} }
@Override @Override
@ -119,7 +118,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
// Check of the isolation type of the related physical network is STT // Check of the isolation type of the related physical network is STT
PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
DataCenter dc = _dcDao.findById(plan.getDataCenterId()); DataCenter dc = _dcDao.findById(plan.getDataCenterId());
if (!canHandle(offering,dc.getNetworkType(),physnet)) { if (!canHandle(offering, dc.getNetworkType(), physnet)) {
s_logger.debug("Refusing to design this network"); s_logger.debug("Refusing to design this network");
return null; return null;
} }
@ -132,7 +131,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId()); s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());
s_logger.debug("Physical isolation type is STT, asking GuestNetworkGuru to design this network"); s_logger.debug("Physical isolation type is STT, asking GuestNetworkGuru to design this network");
NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, owner); NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner);
if (networkObject == null) { if (networkObject == null) {
return null; return null;
} }
@ -174,7 +173,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
if (name == null || name.isEmpty()) { if (name == null || name.isEmpty()) {
name = ((NetworkVO)network).getUuid(); name = ((NetworkVO)network).getUuid();
} }
if (name.length() > 40 ) { if (name.length() > 40) {
name = name.substring(0, 39); // max length 40 name = name.substring(0, 39); // max length 40
} }
@ -191,10 +190,10 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name,
context.getDomain().getName() + "-" + context.getAccount().getAccountName()); context.getDomain().getName() + "-" + context.getAccount().getAccountName());
CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer)_agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.error ("CreateLogicalSwitchCommand failed"); s_logger.error("CreateLogicalSwitchCommand failed");
return null; return null;
} }
@ -249,7 +248,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.error ("DeleteLogicalSwitchCommand failed"); s_logger.error("DeleteLogicalSwitchCommand failed");
} }
super.shutdown(profile, offering); super.shutdown(profile, offering);
@ -260,8 +259,4 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
return super.trash(network, offering); return super.trash(network, offering);
} }
} }

View File

@ -68,171 +68,180 @@ import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
@Component @Component
@Local(value={OvsTunnelManager.class}) @Local(value = {OvsTunnelManager.class})
public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager { public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager {
public static final Logger s_logger = public static final Logger s_logger =
Logger.getLogger(OvsTunnelManagerImpl.class.getName()); Logger.getLogger(OvsTunnelManagerImpl.class.getName());
boolean _isEnabled; boolean _isEnabled;
ScheduledExecutorService _executorPool; ScheduledExecutorService _executorPool;
ScheduledExecutorService _cleanupExecutor; ScheduledExecutorService _cleanupExecutor;
@Inject ConfigurationDao _configDao; @Inject
@Inject NicDao _nicDao; ConfigurationDao _configDao;
@Inject HostDao _hostDao; @Inject
@Inject PhysicalNetworkTrafficTypeDao _physNetTTDao; NicDao _nicDao;
@Inject UserVmDao _userVmDao; @Inject
@Inject DomainRouterDao _routerDao; HostDao _hostDao;
@Inject OvsTunnelNetworkDao _tunnelNetworkDao; @Inject
@Inject OvsTunnelInterfaceDao _tunnelInterfaceDao; PhysicalNetworkTrafficTypeDao _physNetTTDao;
@Inject AgentManager _agentMgr; @Inject
UserVmDao _userVmDao;
@Inject
DomainRouterDao _routerDao;
@Inject
OvsTunnelNetworkDao _tunnelNetworkDao;
@Inject
OvsTunnelInterfaceDao _tunnelInterfaceDao;
@Inject
AgentManager _agentMgr;
@Override @Override
public boolean configure(String name, Map<String, Object> params) public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException { throws ConfigurationException {
_isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key())); _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));
if (_isEnabled) { if (_isEnabled) {
_executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS")); _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS"));
_cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup")); _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup"));
} }
return true; return true;
} }
@DB @DB
protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, protected OvsTunnelNetworkVO createTunnelRecord(long from, long to,
long networkId, int key) { long networkId, int key) {
OvsTunnelNetworkVO ta = null; OvsTunnelNetworkVO ta = null;
try { try {
ta = new OvsTunnelNetworkVO(from, to, key, networkId); ta = new OvsTunnelNetworkVO(from, to, key, networkId);
OvsTunnelNetworkVO lock = OvsTunnelNetworkVO lock =
_tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
if (lock == null) { if (lock == null) {
s_logger.warn("Cannot lock table ovs_tunnel_account"); s_logger.warn("Cannot lock table ovs_tunnel_account");
return null; return null;
} }
_tunnelNetworkDao.persist(ta); _tunnelNetworkDao.persist(ta);
_tunnelNetworkDao.releaseFromLockTable(lock.getId()); _tunnelNetworkDao.releaseFromLockTable(lock.getId());
} catch (EntityExistsException e) { } catch (EntityExistsException e) {
s_logger.debug("A record for the tunnel from " + from + s_logger.debug("A record for the tunnel from " + from +
" to " + to + " already exists"); " to " + to + " already exists");
} }
return ta; return ta;
} }
@DB @DB
protected OvsTunnelInterfaceVO createInterfaceRecord(String ip, protected OvsTunnelInterfaceVO createInterfaceRecord(String ip,
String netmask,String mac,long hostId, String label) { String netmask, String mac, long hostId, String label) {
OvsTunnelInterfaceVO ti = null; OvsTunnelInterfaceVO ti = null;
try { try {
ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label); ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label);
//TODO: Is locking really necessary here? //TODO: Is locking really necessary here?
OvsTunnelInterfaceVO lock = OvsTunnelInterfaceVO lock =
_tunnelInterfaceDao.acquireInLockTable(Long.valueOf(1)); _tunnelInterfaceDao.acquireInLockTable(Long.valueOf(1));
if (lock == null) { if (lock == null) {
s_logger.warn("Cannot lock table ovs_tunnel_account"); s_logger.warn("Cannot lock table ovs_tunnel_account");
return null; return null;
} }
_tunnelInterfaceDao.persist(ti); _tunnelInterfaceDao.persist(ti);
_tunnelInterfaceDao.releaseFromLockTable(lock.getId()); _tunnelInterfaceDao.releaseFromLockTable(lock.getId());
} catch (EntityExistsException e) { } catch (EntityExistsException e) {
s_logger.debug("A record for the interface for network " + label + s_logger.debug("A record for the interface for network " + label +
" on host id " + hostId + " already exists"); " on host id " + hostId + " already exists");
} }
return ti; return ti;
} }
private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId){ private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) {
OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer) answers[0]; OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer)answers[0];
if (ans.getResult()) { if (ans.getResult()) {
if (ans.getIp() != null && if (ans.getIp() != null &&
!("".equals(ans.getIp()))) { !("".equals(ans.getIp()))) {
OvsTunnelInterfaceVO ti = OvsTunnelInterfaceVO ti =
createInterfaceRecord(ans.getIp(), ans.getNetmask(), createInterfaceRecord(ans.getIp(), ans.getNetmask(),
ans.getMac(), hostId, ans.getLabel()); ans.getMac(), hostId, ans.getLabel());
return ti.getIp(); return ti.getIp();
} }
} }
// Fetch interface failed! // Fetch interface failed!
s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" + s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" +
ans.getDetails()); ans.getDetails());
return null; return null;
} }
private void handleCreateTunnelAnswer(Answer[] answers){ private void handleCreateTunnelAnswer(Answer[] answers) {
OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer) answers[0]; OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer)answers[0];
String s = String.format( String s = String.format(
"(hostIP:%1$s, remoteIP:%2$s, bridge:%3$s," + "(hostIP:%1$s, remoteIP:%2$s, bridge:%3$s," +
"greKey:%4$s, portName:%5$s)", "greKey:%4$s, portName:%5$s)",
r.getFromIp(), r.getToIp(), r.getBridge(), r.getFromIp(), r.getToIp(), r.getBridge(),
r.getKey(), r.getInPortName()); r.getKey(), r.getInPortName());
Long from = r.getFrom(); Long from = r.getFrom();
Long to = r.getTo(); Long to = r.getTo();
long networkId = r.getNetworkId(); long networkId = r.getNetworkId();
OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.getByFromToNetwork(from, to, networkId); OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.getByFromToNetwork(from, to, networkId);
if (tunnel == null) { if (tunnel == null) {
throw new CloudRuntimeException( throw new CloudRuntimeException(
String.format("Unable find tunnelNetwork record" + String.format("Unable find tunnelNetwork record" +
"(from=%1$s,to=%2$s, account=%3$s", "(from=%1$s,to=%2$s, account=%3$s",
from, to, networkId)); from, to, networkId));
} }
if (!r.getResult()) { if (!r.getResult()) {
tunnel.setState("FAILED"); tunnel.setState("FAILED");
s_logger.warn("Create GRE tunnel failed due to " + s_logger.warn("Create GRE tunnel failed due to " +
r.getDetails() + s); r.getDetails() + s);
} else { } else {
tunnel.setState("SUCCESS"); tunnel.setState("SUCCESS");
tunnel.setPortName(r.getInPortName()); tunnel.setPortName(r.getInPortName());
s_logger.warn("Create GRE tunnel " + s_logger.warn("Create GRE tunnel " +
r.getDetails() + s); r.getDetails() + s);
} }
_tunnelNetworkDao.update(tunnel.getId(), tunnel); _tunnelNetworkDao.update(tunnel.getId(), tunnel);
} }
private String getGreEndpointIP(Host host, Network nw) throws private String getGreEndpointIP(Host host, Network nw) throws
AgentUnavailableException, OperationTimedoutException { AgentUnavailableException, OperationTimedoutException {
String endpointIp = null; String endpointIp = null;
// Fetch fefault name for network label from configuration // Fetch fefault name for network label from configuration
String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key()); String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key());
Long physNetId = nw.getPhysicalNetworkId(); Long physNetId = nw.getPhysicalNetworkId();
PhysicalNetworkTrafficType physNetTT = PhysicalNetworkTrafficType physNetTT =
_physNetTTDao.findBy(physNetId, TrafficType.Guest); _physNetTTDao.findBy(physNetId, TrafficType.Guest);
HypervisorType hvType = host.getHypervisorType(); HypervisorType hvType = host.getHypervisorType();
switch (hvType) { switch (hvType) {
case XenServer: case XenServer:
String label = physNetTT.getXenNetworkLabel(); String label = physNetTT.getXenNetworkLabel();
if ((label!=null) && (!label.equals(""))) { if ((label != null) && (!label.equals(""))) {
physNetLabel = label; physNetLabel = label;
} }
break; break;
default: default:
throw new CloudRuntimeException("Hypervisor " + throw new CloudRuntimeException("Hypervisor " +
hvType.toString() + hvType.toString() +
" unsupported by OVS Tunnel Manager"); " unsupported by OVS Tunnel Manager");
} }
// Try to fetch GRE endpoint IP address for cloud db // Try to fetch GRE endpoint IP address for cloud db
// If not found, then find it on the hypervisor // If not found, then find it on the hypervisor
OvsTunnelInterfaceVO tunnelIface = OvsTunnelInterfaceVO tunnelIface =
_tunnelInterfaceDao.getByHostAndLabel(host.getId(), _tunnelInterfaceDao.getByHostAndLabel(host.getId(),
physNetLabel); physNetLabel);
if (tunnelIface == null) { if (tunnelIface == null) {
//Now find and fetch configuration for physical interface //Now find and fetch configuration for physical interface
//for network with label on target host //for network with label on target host
Commands fetchIfaceCmds = Commands fetchIfaceCmds =
new Commands(new OvsFetchInterfaceCommand(physNetLabel)); new Commands(new OvsFetchInterfaceCommand(physNetLabel));
s_logger.debug("Ask host " + host.getId() + s_logger.debug("Ask host " + host.getId() +
" to retrieve interface for phy net with label:" + " to retrieve interface for phy net with label:" +
physNetLabel); physNetLabel);
Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(),
fetchIfaceCmds); fetchIfaceCmds);
//And finally save it for future use //And finally save it for future use
endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers, endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers,
host.getId()); host.getId());
} else { } else {
endpointIp = tunnelIface.getIp(); endpointIp = tunnelIface.getIp();
} }
return endpointIp; return endpointIp;
} }
@ -243,7 +252,7 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
//The GRE key is actually in the host part of the URI //The GRE key is actually in the host part of the URI
// this is not true for lswitch/NiciraNvp! // this is not true for lswitch/NiciraNvp!
String keyStr = BroadcastDomainType.getValue(network.getBroadcastUri()); String keyStr = BroadcastDomainType.getValue(network.getBroadcastUri());
// The key is most certainly and int if network is a vlan. // The key is most certainly and int if network is a vlan.
// !! not in the case of lswitch/pvlan/(possibly)vswitch // !! not in the case of lswitch/pvlan/(possibly)vswitch
// So we now feel quite safe in converting it into a string // So we now feel quite safe in converting it into a string
// by calling the appropriate BroadcastDomainType method // by calling the appropriate BroadcastDomainType method
@ -261,148 +270,148 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
@DB @DB
protected void CheckAndCreateTunnel(VirtualMachine instance, protected void CheckAndCreateTunnel(VirtualMachine instance,
Network nw, DeployDestination dest) { Network nw, DeployDestination dest) {
if (!_isEnabled) { if (!_isEnabled) {
return; return;
} }
s_logger.debug("Creating tunnels with OVS tunnel manager"); s_logger.debug("Creating tunnels with OVS tunnel manager");
if (instance.getType() != VirtualMachine.Type.User if (instance.getType() != VirtualMachine.Type.User
&& instance.getType() != VirtualMachine.Type.DomainRouter) { && instance.getType() != VirtualMachine.Type.DomainRouter) {
s_logger.debug("Will not work if you're not" + s_logger.debug("Will not work if you're not" +
"an instance or a virtual router"); "an instance or a virtual router");
return; return;
} }
long hostId = dest.getHost().getId(); long hostId = dest.getHost().getId();
int key = getGreKey(nw); int key = getGreKey(nw);
// Find active VMs with a NIC on the target network // Find active VMs with a NIC on the target network
List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(nw.getId(), List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(nw.getId(),
State.Running, State.Starting, State.Running, State.Starting,
State.Stopping, State.Unknown, State.Migrating); State.Stopping, State.Unknown, State.Migrating);
// Find routers for the network // Find routers for the network
List<DomainRouterVO> routers = _routerDao.findByNetwork(nw.getId()); List<DomainRouterVO> routers = _routerDao.findByNetwork(nw.getId());
List<VMInstanceVO>ins = new ArrayList<VMInstanceVO>(); List<VMInstanceVO> ins = new ArrayList<VMInstanceVO>();
if (vms != null) { if (vms != null) {
ins.addAll(vms); ins.addAll(vms);
} }
if (routers.size() != 0) { if (routers.size() != 0) {
ins.addAll(routers); ins.addAll(routers);
} }
List<Long> toHostIds = new ArrayList<Long>(); List<Long> toHostIds = new ArrayList<Long>();
List<Long> fromHostIds = new ArrayList<Long>(); List<Long> fromHostIds = new ArrayList<Long>();
for (VMInstanceVO v : ins) { for (VMInstanceVO v : ins) {
Long rh = v.getHostId(); Long rh = v.getHostId();
if (rh == null || rh.longValue() == hostId) { if (rh == null || rh.longValue() == hostId) {
continue; continue;
} }
OvsTunnelNetworkVO ta = OvsTunnelNetworkVO ta =
_tunnelNetworkDao.getByFromToNetwork(hostId, _tunnelNetworkDao.getByFromToNetwork(hostId,
rh.longValue(), nw.getId()); rh.longValue(), nw.getId());
// Try and create the tunnel even if a previous attempt failed // Try and create the tunnel even if a previous attempt failed
if (ta == null || ta.getState().equals("FAILED")) { if (ta == null || ta.getState().equals("FAILED")) {
s_logger.debug("Attempting to create tunnel from:" + s_logger.debug("Attempting to create tunnel from:" +
hostId + " to:" + rh.longValue()); hostId + " to:" + rh.longValue());
if (ta == null) { if (ta == null) {
this.createTunnelRecord(hostId, rh.longValue(), this.createTunnelRecord(hostId, rh.longValue(),
nw.getId(), key); nw.getId(), key);
} }
if (!toHostIds.contains(rh)) { if (!toHostIds.contains(rh)) {
toHostIds.add(rh); toHostIds.add(rh);
} }
} }
ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(), ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(),
hostId, nw.getId()); hostId, nw.getId());
// Try and create the tunnel even if a previous attempt failed // Try and create the tunnel even if a previous attempt failed
if (ta == null || ta.getState().equals("FAILED")) { if (ta == null || ta.getState().equals("FAILED")) {
s_logger.debug("Attempting to create tunnel from:" + s_logger.debug("Attempting to create tunnel from:" +
rh.longValue() + " to:" + hostId); rh.longValue() + " to:" + hostId);
if (ta == null) { if (ta == null) {
this.createTunnelRecord(rh.longValue(), hostId, this.createTunnelRecord(rh.longValue(), hostId,
nw.getId(), key); nw.getId(), key);
} }
if (!fromHostIds.contains(rh)) { if (!fromHostIds.contains(rh)) {
fromHostIds.add(rh); fromHostIds.add(rh);
} }
} }
} }
//TODO: Should we propagate the exception here? //TODO: Should we propagate the exception here?
try { try {
String myIp = getGreEndpointIP(dest.getHost(), nw); String myIp = getGreEndpointIP(dest.getHost(), nw);
if (myIp == null) if (myIp == null)
throw new GreTunnelException("Unable to retrieve the source " + throw new GreTunnelException("Unable to retrieve the source " +
"endpoint for the GRE tunnel." + "endpoint for the GRE tunnel." +
"Failure is on host:" + dest.getHost().getId()); "Failure is on host:" + dest.getHost().getId());
boolean noHost = true; boolean noHost = true;
for (Long i : toHostIds) { for (Long i : toHostIds) {
HostVO rHost = _hostDao.findById(i); HostVO rHost = _hostDao.findById(i);
String otherIp = getGreEndpointIP(rHost, nw); String otherIp = getGreEndpointIP(rHost, nw);
if (otherIp == null) if (otherIp == null)
throw new GreTunnelException("Unable to retrieve the remote " + throw new GreTunnelException("Unable to retrieve the remote " +
"endpoint for the GRE tunnel." + "endpoint for the GRE tunnel." +
"Failure is on host:" + rHost.getId()); "Failure is on host:" + rHost.getId());
Commands cmds = new Commands( Commands cmds = new Commands(
new OvsCreateTunnelCommand(otherIp, key, new OvsCreateTunnelCommand(otherIp, key,
Long.valueOf(hostId), i, nw.getId(), myIp)); Long.valueOf(hostId), i, nw.getId(), myIp));
s_logger.debug("Ask host " + hostId + s_logger.debug("Ask host " + hostId +
" to create gre tunnel to " + i); " to create gre tunnel to " + i);
Answer[] answers = _agentMgr.send(hostId, cmds); Answer[] answers = _agentMgr.send(hostId, cmds);
handleCreateTunnelAnswer(answers); handleCreateTunnelAnswer(answers);
noHost = false; noHost = false;
} }
for (Long i : fromHostIds) { for (Long i : fromHostIds) {
HostVO rHost = _hostDao.findById(i); HostVO rHost = _hostDao.findById(i);
String otherIp = getGreEndpointIP(rHost, nw); String otherIp = getGreEndpointIP(rHost, nw);
Commands cmds = new Commands( Commands cmds = new Commands(
new OvsCreateTunnelCommand(myIp, key, i, new OvsCreateTunnelCommand(myIp, key, i,
Long.valueOf(hostId), Long.valueOf(hostId),
nw.getId(), otherIp)); nw.getId(), otherIp));
s_logger.debug("Ask host " + i + s_logger.debug("Ask host " + i +
" to create gre tunnel to " + hostId); " to create gre tunnel to " + hostId);
Answer[] answers = _agentMgr.send(i, cmds); Answer[] answers = _agentMgr.send(i, cmds);
handleCreateTunnelAnswer(answers); handleCreateTunnelAnswer(answers);
noHost = false; noHost = false;
} }
// If no tunnels have been configured, perform the bridge setup anyway // If no tunnels have been configured, perform the bridge setup anyway
// This will ensure VIF rules will be triggered // This will ensure VIF rules will be triggered
if (noHost) { if (noHost) {
Commands cmds = new Commands( Commands cmds = new Commands(
new OvsSetupBridgeCommand(key, hostId, nw.getId())); new OvsSetupBridgeCommand(key, hostId, nw.getId()));
s_logger.debug("Ask host " + hostId + s_logger.debug("Ask host " + hostId +
" to configure bridge for network:" + nw.getId()); " to configure bridge for network:" + nw.getId());
Answer[] answers = _agentMgr.send(hostId, cmds); Answer[] answers = _agentMgr.send(hostId, cmds);
handleSetupBridgeAnswer(answers); handleSetupBridgeAnswer(answers);
} }
} catch (Exception e) { } catch (Exception e) {
// I really thing we should do a better handling of these exceptions // I really thing we should do a better handling of these exceptions
s_logger.warn("Ovs Tunnel network created tunnel failed", e); s_logger.warn("Ovs Tunnel network created tunnel failed", e);
} }
} }
@Override @Override
public boolean isOvsTunnelEnabled() { public boolean isOvsTunnelEnabled() {
return _isEnabled; return _isEnabled;
} }
@Override @Override
public void VmCheckAndCreateTunnel( public void VmCheckAndCreateTunnel(
VirtualMachineProfile vm, VirtualMachineProfile vm,
Network nw, DeployDestination dest) { Network nw, DeployDestination dest) {
CheckAndCreateTunnel(vm.getVirtualMachine(), nw, dest); CheckAndCreateTunnel(vm.getVirtualMachine(), nw, dest);
} }
@DB @DB
private void handleDestroyTunnelAnswer(Answer ans, long from, private void handleDestroyTunnelAnswer(Answer ans, long from,
long to, long network_id) { long to, long network_id) {
if (ans.getResult()) { if (ans.getResult()) {
OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
if (lock == null) { if (lock == null) {
s_logger.warn(String.format("failed to lock" + s_logger.warn(String.format("failed to lock" +
"ovs_tunnel_account, remove record of " + "ovs_tunnel_account, remove record of " +
"tunnel(from=%1$s, to=%2$s account=%3$s) failed", "tunnel(from=%1$s, to=%2$s account=%3$s) failed",
from, to, network_id)); from, to, network_id));
return; return;
} }
@ -410,25 +419,25 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
_tunnelNetworkDao.releaseFromLockTable(lock.getId()); _tunnelNetworkDao.releaseFromLockTable(lock.getId());
s_logger.debug(String.format("Destroy tunnel(account:%1$s," + s_logger.debug(String.format("Destroy tunnel(account:%1$s," +
"from:%2$s, to:%3$s) successful", "from:%2$s, to:%3$s) successful",
network_id, from, to)); network_id, from, to));
} else { } else {
s_logger.debug(String.format("Destroy tunnel(account:%1$s," + s_logger.debug(String.format("Destroy tunnel(account:%1$s," +
"from:%2$s, to:%3$s) failed", "from:%2$s, to:%3$s) failed",
network_id, from, to)); network_id, from, to));
} }
} }
@DB @DB
private void handleDestroyBridgeAnswer(Answer ans, private void handleDestroyBridgeAnswer(Answer ans,
long host_id, long network_id) { long host_id, long network_id) {
if (ans.getResult()) { if (ans.getResult()) {
OvsTunnelNetworkVO lock = OvsTunnelNetworkVO lock =
_tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
if (lock == null) { if (lock == null) {
s_logger.warn("failed to lock ovs_tunnel_network," + s_logger.warn("failed to lock ovs_tunnel_network," +
"remove record"); "remove record");
return; return;
} }
@ -436,71 +445,71 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
_tunnelNetworkDao.releaseFromLockTable(lock.getId()); _tunnelNetworkDao.releaseFromLockTable(lock.getId());
s_logger.debug(String.format("Destroy bridge for" + s_logger.debug(String.format("Destroy bridge for" +
"network %1$s successful", network_id)); "network %1$s successful", network_id));
} else { } else {
s_logger.debug(String.format("Destroy bridge for" + s_logger.debug(String.format("Destroy bridge for" +
"network %1$s failed", network_id)); "network %1$s failed", network_id));
} }
} }
private void handleSetupBridgeAnswer(Answer[] answers) { private void handleSetupBridgeAnswer(Answer[] answers) {
//TODO: Add some error management here? //TODO: Add some error management here?
s_logger.debug("Placeholder for something more meanginful to come"); s_logger.debug("Placeholder for something more meanginful to come");
} }
@Override @Override
public void CheckAndDestroyTunnel(VirtualMachine vm, Network nw) { public void CheckAndDestroyTunnel(VirtualMachine vm, Network nw) {
if (!_isEnabled) { if (!_isEnabled) {
return; return;
} }
List<UserVmVO> userVms = _userVmDao.listByAccountIdAndHostId( List<UserVmVO> userVms = _userVmDao.listByAccountIdAndHostId(
vm.getAccountId(), vm.getHostId()); vm.getAccountId(), vm.getHostId());
if (vm.getType() == VirtualMachine.Type.User) { if (vm.getType() == VirtualMachine.Type.User) {
if (userVms.size() > 1) { if (userVms.size() > 1) {
return; return;
} }
List<DomainRouterVO> routers = List<DomainRouterVO> routers =
_routerDao.findByNetwork(nw.getId()); _routerDao.findByNetwork(nw.getId());
for (DomainRouterVO router : routers) { for (DomainRouterVO router : routers) {
if (router.getHostId() == vm.getHostId()) { if (router.getHostId() == vm.getHostId()) {
return; return;
} }
} }
} else if (vm.getType() == VirtualMachine.Type.DomainRouter && } else if (vm.getType() == VirtualMachine.Type.DomainRouter &&
userVms.size() != 0) { userVms.size() != 0) {
return; return;
} }
try { try {
/* Now we are last one on host, destroy the bridge with all /* Now we are last one on host, destroy the bridge with all
* the tunnels for this network */ * the tunnels for this network */
int key = getGreKey(nw); int key = getGreKey(nw);
Command cmd = new OvsDestroyBridgeCommand(nw.getId(), key); Command cmd = new OvsDestroyBridgeCommand(nw.getId(), key);
s_logger.debug("Destroying bridge for network " + nw.getId() + s_logger.debug("Destroying bridge for network " + nw.getId() +
" on host:" + vm.getHostId()); " on host:" + vm.getHostId());
Answer ans = _agentMgr.send(vm.getHostId(), cmd); Answer ans = _agentMgr.send(vm.getHostId(), cmd);
handleDestroyBridgeAnswer(ans, vm.getHostId(), nw.getId()); handleDestroyBridgeAnswer(ans, vm.getHostId(), nw.getId());
/* Then ask hosts have peer tunnel with me to destroy them */ /* Then ask hosts have peer tunnel with me to destroy them */
List<OvsTunnelNetworkVO> peers = List<OvsTunnelNetworkVO> peers =
_tunnelNetworkDao.listByToNetwork(vm.getHostId(), _tunnelNetworkDao.listByToNetwork(vm.getHostId(),
nw.getId()); nw.getId());
for (OvsTunnelNetworkVO p : peers) { for (OvsTunnelNetworkVO p : peers) {
// If the tunnel was not successfully created don't bother to remove it // If the tunnel was not successfully created don't bother to remove it
if (p.getState().equals("SUCCESS")) { if (p.getState().equals("SUCCESS")) {
cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key, cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key,
p.getPortName()); p.getPortName());
s_logger.debug("Destroying tunnel to " + vm.getHostId() + s_logger.debug("Destroying tunnel to " + vm.getHostId() +
" from " + p.getFrom()); " from " + p.getFrom());
ans = _agentMgr.send(p.getFrom(), cmd); ans = _agentMgr.send(p.getFrom(), cmd);
handleDestroyTunnelAnswer(ans, p.getFrom(), handleDestroyTunnelAnswer(ans, p.getFrom(),
p.getTo(), p.getNetworkId()); p.getTo(), p.getNetworkId());
} }
} }
} catch (Exception e) { } catch (Exception e) {
s_logger.warn(String.format("Destroy tunnel(account:%1$s," + s_logger.warn(String.format("Destroy tunnel(account:%1$s," +
"hostId:%2$s) failed", vm.getAccountId(), vm.getHostId()), e); "hostId:%2$s) failed", vm.getAccountId(), vm.getHostId()), e);
} }
} }

View File

@ -2942,7 +2942,7 @@ public class ApiResponseHelper implements ResponseGenerator {
public PrivateGatewayResponse createPrivateGatewayResponse(PrivateGateway result) { public PrivateGatewayResponse createPrivateGatewayResponse(PrivateGateway result) {
PrivateGatewayResponse response = new PrivateGatewayResponse(); PrivateGatewayResponse response = new PrivateGatewayResponse();
response.setId(result.getUuid()); response.setId(result.getUuid());
response.setVlan(result.getVlanTag()); response.setBroadcastUri(result.getBroadcastUri());
response.setGateway(result.getGateway()); response.setGateway(result.getGateway());
response.setNetmask(result.getNetmask()); response.setNetmask(result.getNetmask());
if (result.getVpcId() != null) { if (result.getVpcId() != null) {

View File

@ -1906,7 +1906,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
|| zone.getNetworkType() == NetworkType.Basic) { || zone.getNetworkType() == NetworkType.Basic) {
broadcastDomainType = BroadcastDomainType.Vlan; broadcastDomainType = BroadcastDomainType.Vlan;
} else { } else {
continue; continue; // so broadcastDomainType remains null! why have None/Undecided/UnKnown?
} }
} else if (offering.getTrafficType() == TrafficType.Guest) { } else if (offering.getTrafficType() == TrafficType.Guest) {
continue; continue;
@ -2434,6 +2434,11 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
String newVlanGateway = cmd.getGateway(); String newVlanGateway = cmd.getGateway();
String newVlanNetmask = cmd.getNetmask(); String newVlanNetmask = cmd.getNetmask();
String vlanId = cmd.getVlan(); String vlanId = cmd.getVlan();
// TODO decide if we should be forgiving or demand a valid and complete URI
if (!((vlanId == null)
|| ("".equals(vlanId))
|| vlanId.startsWith(BroadcastDomainType.Vlan.scheme())))
vlanId = BroadcastDomainType.Vlan.toUri(vlanId).toString();
Boolean forVirtualNetwork = cmd.isForVirtualNetwork(); Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
Long networkId = cmd.getNetworkID(); Long networkId = cmd.getNetworkID();
Long physicalNetworkId = cmd.getPhysicalNetworkId(); Long physicalNetworkId = cmd.getPhysicalNetworkId();

View File

@ -89,7 +89,7 @@ import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.NicDao;
@Component @Component
@Local(value = { ExternalDeviceUsageManager.class }) @Local(value = {ExternalDeviceUsageManager.class})
public class ExternalDeviceUsageManagerImpl extends ManagerBase implements ExternalDeviceUsageManager { public class ExternalDeviceUsageManagerImpl extends ManagerBase implements ExternalDeviceUsageManager {
String _name; String _name;
@ -150,7 +150,6 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
@Inject @Inject
NetworkModel _networkModel; NetworkModel _networkModel;
ScheduledExecutorService _executor; ScheduledExecutorService _executor;
private int _externalNetworkStatsInterval; private int _externalNetworkStatsInterval;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDeviceUsageManagerImpl.class); private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDeviceUsageManagerImpl.class);
@ -199,26 +198,26 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
if (fwDeviceForNetwork != null) { if (fwDeviceForNetwork != null) {
long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId(); long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId();
ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId); ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId);
assert(fwDevice != null); assert (fwDevice != null);
return fwDevice; return fwDevice;
} }
return null; return null;
} }
@Override @Override
public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId){ public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId) {
LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId); LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId);
if(lb == null){ if (lb == null) {
if(s_logger.isDebugEnabled()){ if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, LB rule is not found"); s_logger.debug("Cannot update usage stats, LB rule is not found");
} }
return; return;
} }
long networkId = lb.getNetworkId(); long networkId = lb.getNetworkId();
Network network = _networkDao.findById(networkId); Network network = _networkDao.findById(networkId);
if(network == null){ if (network == null) {
if(s_logger.isDebugEnabled()){ if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, Network is not found"); s_logger.debug("Cannot update usage stats, Network is not found");
} }
return; return;
@ -226,7 +225,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
if(s_logger.isDebugEnabled()){ if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, No external LB device found"); s_logger.debug("Cannot update usage stats, No external LB device found");
} }
return; return;
@ -237,7 +236,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
if (externalLoadBalancer != null) { if (externalLoadBalancer != null) {
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); lbAnswer = (ExternalNetworkResourceUsageAnswer)_agentMgr.easySend(externalLoadBalancer.getId(), cmd);
if (lbAnswer == null || !lbAnswer.getResult()) { if (lbAnswer == null || !lbAnswer.getResult()) {
String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable";
String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + "."; String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + ".";
@ -255,7 +254,8 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
String publicIp = _networkModel.getIp(lb.getSourceIpAddressId()).getAddress().addr(); String publicIp = _networkModel.getIp(lb.getSourceIpAddressId()).getAddress().addr();
DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + externalLoadBalancer.getName(); String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID "
+ externalLoadBalancer.getName();
long newCurrentBytesSent = 0; long newCurrentBytesSent = 0;
long newCurrentBytesReceived = 0; long newCurrentBytesReceived = 0;
@ -294,12 +294,13 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
txn.start(); txn.start();
userStats = _userStatsDao.lock(accountId, zone.getId(), networkId, publicIp, externalLoadBalancer.getId(), externalLoadBalancer.getType().toString()); userStats = _userStatsDao.lock(accountId, zone.getId(), networkId, publicIp, externalLoadBalancer.getId(), externalLoadBalancer.getType().toString());
if(userStats != null){ if (userStats != null) {
long oldNetBytesSent = userStats.getNetBytesSent(); long oldNetBytesSent = userStats.getNetBytesSent();
long oldNetBytesReceived = userStats.getNetBytesReceived(); long oldNetBytesReceived = userStats.getNetBytesReceived();
long oldCurrentBytesSent = userStats.getCurrentBytesSent(); long oldCurrentBytesSent = userStats.getCurrentBytesSent();
long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); long oldCurrentBytesReceived = userStats.getCurrentBytesReceived();
String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId()
+ ", account ID: " + userStats.getAccountId() + ".";
userStats.setCurrentBytesSent(newCurrentBytesSent); userStats.setCurrentBytesSent(newCurrentBytesSent);
if (oldCurrentBytesSent > newCurrentBytesSent) { if (oldCurrentBytesSent > newCurrentBytesSent) {
@ -318,12 +319,12 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} else { } else {
s_logger.debug("Failed to update stats for " + statsEntryIdentifier); s_logger.debug("Failed to update stats for " + statsEntryIdentifier);
} }
}else { } else {
s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier);
} }
txn.commit(); txn.commit();
}catch (final Exception e) { } catch (final Exception e) {
txn.rollback(); txn.rollback();
throw new CloudRuntimeException("Problem getting stats after reboot/stop ", e); throw new CloudRuntimeException("Problem getting stats after reboot/stop ", e);
} }
@ -398,14 +399,14 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
// Get network stats from the external firewall // Get network stats from the external firewall
ExternalNetworkResourceUsageAnswer firewallAnswer = null; ExternalNetworkResourceUsageAnswer firewallAnswer = null;
HostVO externalFirewall = null; HostVO externalFirewall = null;
if(fwDeviceVO != null){ if (fwDeviceVO != null) {
externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
if (externalFirewall != null) { if (externalFirewall != null) {
Long fwDeviceId = new Long(externalFirewall.getId()); Long fwDeviceId = new Long(externalFirewall.getId());
if(!fwDeviceUsageAnswerMap.containsKey(fwDeviceId)){ if (!fwDeviceUsageAnswerMap.containsKey(fwDeviceId)) {
try{ try {
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
firewallAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalFirewall.getId(), cmd); firewallAnswer = (ExternalNetworkResourceUsageAnswer)_agentMgr.easySend(externalFirewall.getId(), cmd);
if (firewallAnswer == null || !firewallAnswer.getResult()) { if (firewallAnswer == null || !firewallAnswer.getResult()) {
String details = (firewallAnswer != null) ? firewallAnswer.getDetails() : "details unavailable"; String details = (firewallAnswer != null) ? firewallAnswer.getDetails() : "details unavailable";
String msg = "Unable to get external firewall stats for network" + zone.getName() + " due to: " + details + "."; String msg = "Unable to get external firewall stats for network" + zone.getName() + " due to: " + details + ".";
@ -413,7 +414,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} else { } else {
fwDeviceUsageAnswerMap.put(fwDeviceId, firewallAnswer); fwDeviceUsageAnswerMap.put(fwDeviceId, firewallAnswer);
} }
} catch (Exception e){ } catch (Exception e) {
String msg = "Unable to get external firewall stats for network" + zone.getName(); String msg = "Unable to get external firewall stats for network" + zone.getName();
s_logger.error(msg, e); s_logger.error(msg, e);
} }
@ -423,19 +424,20 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} }
firewallAnswer = fwDeviceUsageAnswerMap.get(fwDeviceId); firewallAnswer = fwDeviceUsageAnswerMap.get(fwDeviceId);
} }
}} }
}
// Get network stats from the external load balancer // Get network stats from the external load balancer
ExternalNetworkResourceUsageAnswer lbAnswer = null; ExternalNetworkResourceUsageAnswer lbAnswer = null;
HostVO externalLoadBalancer = null; HostVO externalLoadBalancer = null;
if(lbDeviceVO !=null){ if (lbDeviceVO != null) {
externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
if (externalLoadBalancer != null) { if (externalLoadBalancer != null) {
Long lbDeviceId = new Long(externalLoadBalancer.getId()); Long lbDeviceId = new Long(externalLoadBalancer.getId());
if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) { if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) {
try { try {
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); lbAnswer = (ExternalNetworkResourceUsageAnswer)_agentMgr.easySend(externalLoadBalancer.getId(), cmd);
if (lbAnswer == null || !lbAnswer.getResult()) { if (lbAnswer == null || !lbAnswer.getResult()) {
String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable";
String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + "."; String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + ".";
@ -443,7 +445,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} else { } else {
lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer); lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer);
} }
} catch (Exception e){ } catch (Exception e) {
String msg = "Unable to get external load balancer stats for " + zone.getName(); String msg = "Unable to get external load balancer stats for " + zone.getName();
s_logger.error(msg, e); s_logger.error(msg, e);
} }
@ -456,7 +458,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} }
} }
if(firewallAnswer == null && lbAnswer == null){ if (firewallAnswer == null && lbAnswer == null) {
continue; continue;
} }
@ -483,7 +485,8 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
long oldNetBytesReceived = userStats.getNetBytesReceived(); long oldNetBytesReceived = userStats.getNetBytesReceived();
long oldCurrentBytesSent = userStats.getCurrentBytesSent(); long oldCurrentBytesSent = userStats.getCurrentBytesSent();
long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); long oldCurrentBytesReceived = userStats.getCurrentBytesReceived();
String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: "
+ userStats.getAccountId() + ".";
userStats.setCurrentBytesSent(newCurrentBytesSent); userStats.setCurrentBytesSent(newCurrentBytesSent);
if (oldCurrentBytesSent > newCurrentBytesSent) { if (oldCurrentBytesSent > newCurrentBytesSent) {
@ -584,7 +587,8 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} }
} }
private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer, boolean inline) { private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId,
ExternalNetworkResourceUsageAnswer answer, boolean inline) {
if (create) { if (create) {
return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId); return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId);
} else { } else {
@ -598,8 +602,8 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
* balancing rules * balancing rules
*/ */
private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network, private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network,
HostVO externalFirewall, ExternalNetworkResourceUsageAnswer firewallAnswer, HostVO externalFirewall, ExternalNetworkResourceUsageAnswer firewallAnswer,
HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) {
String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId;
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
try { try {
@ -615,7 +619,7 @@ public class ExternalDeviceUsageManagerImpl extends ManagerBase implements Exter
} }
} }
if(externalFirewall != null && firewallAnswer != null){ if (externalFirewall != null && firewallAnswer != null) {
if (!sharedSourceNat) { if (!sharedSourceNat) {
// Manage the entry for this network's source NAT IP address // Manage the entry for this network's source NAT IP address
List<IPAddressVO> sourceNatIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); List<IPAddressVO> sourceNatIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true);

View File

@ -1,4 +1,3 @@
// Licensed to the Apache Software Foundation (ASF) under one // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file // or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information // distributed with this work for additional information
@ -162,11 +161,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
@DB @DB
public ExternalFirewallDeviceVO addExternalFirewall(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource) { public ExternalFirewallDeviceVO addExternalFirewall(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource) {
String guid; String guid;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName);
long zoneId; long zoneId;
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null) ) { if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter."); " server resource, zone id/physical network id) is not specified or a valid parameter.");
} }
@ -266,7 +265,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
// delete the external load balancer entry // delete the external load balancer entry
_externalFirewallDeviceDao.remove(fwDeviceId); _externalFirewallDeviceDao.remove(fwDeviceId);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
s_logger.debug("Failed to delete external firewall device due to " + e.getMessage()); s_logger.debug("Failed to delete external firewall device due to " + e.getMessage());
return false; return false;
@ -277,7 +276,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
public List<Host> listExternalFirewalls(long physicalNetworkId, String deviceName) { public List<Host> listExternalFirewalls(long physicalNetworkId, String deviceName) {
List<Host> firewallHosts = new ArrayList<Host>(); List<Host> firewallHosts = new ArrayList<Host>();
NetworkDevice fwNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); NetworkDevice fwNetworkDevice = NetworkDevice.getNetworkDevice(deviceName);
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
pNetwork = _physicalNetworkDao.findById(physicalNetworkId); pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) { if (pNetwork == null) {
@ -306,7 +305,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (fwDeviceForNetwork != null) { if (fwDeviceForNetwork != null) {
long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId(); long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId();
ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId); ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId);
assert(fwDevice != null); assert (fwDevice != null);
return fwDevice; return fwDevice;
} }
return null; return null;
@ -345,7 +344,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
@DB @DB
protected boolean freeFirewallForNetwork(Network network) { protected boolean freeFirewallForNetwork(Network network) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap"); GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap");
try { try {
if (deviceMapLock.lock(120)) { if (deviceMapLock.lock(120)) {
try { try {
@ -400,11 +399,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
HostVO externalFirewall = null; HostVO externalFirewall = null;
if (add) { if (add) {
GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap"); GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap");
try { try {
if (deviceMapLock.lock(120)) { if (deviceMapLock.lock(120)) {
try { try {
ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network); ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network);
long externalFirewallId = device.getId(); long externalFirewallId = device.getId();
NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId); NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId);
@ -422,7 +421,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
if (fwDeviceVO == null) { if (fwDeviceVO == null) {
s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." + s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." +
" Either network implement failed half way through or already network shutdown is completed."); " Either network implement failed half way through or already network shutdown is completed.");
return true; return true;
} }
externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
@ -441,7 +440,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (sourceNatIps.size() != 1) { if (sourceNatIps.size() != 1) {
String errorMsg = "External firewall was unable to find the source NAT IP address for account " String errorMsg = "External firewall was unable to find the source NAT IP address for account "
+ account.getAccountName(); + account.getAccountName();
s_logger.error(errorMsg); s_logger.error(errorMsg);
return true; return true;
} else { } else {
@ -491,7 +490,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
// Insert a new NIC for this guest network to reserve the gateway address // Insert a new NIC for this guest network to reserve the gateway address
_networkMgr.savePlaceholderNic(network, network.getGateway(), null, null); _networkMgr.savePlaceholderNic(network, network.getGateway(), null, null);
} }
// Delete any mappings used for inline external load balancers in this network // Delete any mappings used for inline external load balancers in this network
@ -518,12 +517,12 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
} }
String action = add ? "implemented" : "shut down"; String action = add ? "implemented" : "shut down";
s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag "
+ guestVlanTag);
return true; return true;
} }
@Override @Override
public boolean applyFirewallRules(Network network, List<? extends FirewallRule> rules) throws ResourceUnavailableException { public boolean applyFirewallRules(Network network, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
// Find the external firewall in this zone // Find the external firewall in this zone
@ -536,10 +535,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
} }
HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
assert(externalFirewall != null); assert (externalFirewall != null);
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -570,7 +570,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
sendFirewallRules(rulesTO, zone, externalFirewall.getId()); sendFirewallRules(rulesTO, zone, externalFirewall.getId());
return true; return true;
} }
public boolean applyStaticNatRules(Network network, List<? extends StaticNat> rules) throws ResourceUnavailableException { public boolean applyStaticNatRules(Network network, List<? extends StaticNat> rules) throws ResourceUnavailableException {
long zoneId = network.getDataCenterId(); long zoneId = network.getDataCenterId();
@ -578,10 +578,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
assert(externalFirewall != null); assert (externalFirewall != null);
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -591,7 +592,8 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); Vlan vlan = _vlanDao.findById(sourceIp.getVlanId());
StaticNatRuleTO ruleTO = new StaticNatRuleTO(0,vlan.getVlanTag(), sourceIp.getAddress().addr(), -1, -1, rule.getDestIpAddress(), -1, -1, "any", rule.isForRevoke(), false); StaticNatRuleTO ruleTO = new StaticNatRuleTO(0, vlan.getVlanTag(), sourceIp.getAddress().addr(), -1, -1, rule.getDestIpAddress(), -1, -1, "any", rule.isForRevoke(),
false);
staticNatRules.add(ruleTO); staticNatRules.add(ruleTO);
} }
@ -602,7 +604,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
protected void sendFirewallRules(List<FirewallRuleTO> firewallRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { protected void sendFirewallRules(List<FirewallRuleTO> firewallRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException {
if (!firewallRules.isEmpty()) { if (!firewallRules.isEmpty()) {
SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(firewallRules); SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(firewallRules);
Answer answer = _agentMgr.easySend(externalFirewallId, cmd); Answer answer = _agentMgr.easySend(externalFirewallId, cmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable"; String details = (answer != null) ? answer.getDetails() : "details unavailable";
@ -672,10 +674,10 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd); Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable"; String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + "."; String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg); s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
} }
// Add/delete users // Add/delete users
@ -695,7 +697,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
List<VpnUser> removeUsers = new ArrayList<VpnUser>(); List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (VpnUser user : vpnUsers) { for (VpnUser user : vpnUsers) {
if (user.getState() == VpnUser.State.Add || if (user.getState() == VpnUser.State.Add ||
user.getState() == VpnUser.State.Active) { user.getState() == VpnUser.State.Active) {
addUsers.add(user); addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) { } else if (user.getState() == VpnUser.State.Revoke) {
removeUsers.add(user); removeUsers.add(user);
@ -708,11 +710,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd); Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable"; String details = (answer != null) ? answer.getDetails() : "details unavailable";
DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + "."; String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg); s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
} }
return true; return true;
@ -730,13 +732,13 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
Integer lowestVlanTag = null; Integer lowestVlanTag = null;
List<Pair<Integer, Integer>> vnetList = pNetwork.getVnet(); List<Pair<Integer, Integer>> vnetList = pNetwork.getVnet();
//finding the vlanrange in which the vlanTag lies. //finding the vlanrange in which the vlanTag lies.
for (Pair <Integer,Integer> vnet : vnetList){ for (Pair<Integer, Integer> vnet : vnetList) {
if (vlanTag >= vnet.first() && vlanTag <= vnet.second()){ if (vlanTag >= vnet.first() && vlanTag <= vnet.second()) {
lowestVlanTag = vnet.first(); lowestVlanTag = vnet.first();
} }
} }
if (lowestVlanTag == null) { if (lowestVlanTag == null) {
throw new InvalidParameterValueException ("The vlan tag does not belong to any of the existing vlan ranges"); throw new InvalidParameterValueException("The vlan tag does not belong to any of the existing vlan ranges");
} }
return vlanTag - lowestVlanTag; return vlanTag - lowestVlanTag;
} }
@ -769,8 +771,8 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
@Override @Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) { if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) {
return null; return null;
} }
return new DeleteHostAnswer(true); return new DeleteHostAnswer(true);
} }
@ -782,10 +784,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
assert(externalFirewall != null); assert (externalFirewall != null);
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }

View File

@ -106,6 +106,7 @@ import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceState;
import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ResourceStateAdapter.DeleteHostAnswer;
import com.cloud.resource.ServerResource; import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException; import com.cloud.resource.UnableDeleteHostException;
import com.cloud.user.Account; import com.cloud.user.Account;
@ -195,8 +196,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
@Override @Override
@DB @DB
public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url,
String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider,
String gslbSitePublicIp, String gslbSitePrivateIp) { String gslbSitePublicIp, String gslbSitePrivateIp) {
PhysicalNetworkVO pNetwork = null; PhysicalNetworkVO pNetwork = null;
NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName);
@ -264,7 +265,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails);
if (host != null) { if (host != null) {
boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams
.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false;
long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
if (capacity == 0) { if (capacity == 0) {
capacity = _defaultLbCapacity; capacity = _defaultLbCapacity;
@ -310,7 +312,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (lbDevices != null) { if (lbDevices != null) {
for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
if (lbDevice.getParentHostId() == hostId) { if (lbDevice.getParentHostId() == hostId) {
throw new CloudRuntimeException("This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); throw new CloudRuntimeException(
"This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device.");
} }
} }
} }
@ -469,7 +472,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// a new LB appliance // a new LB appliance
if (tryLbProvisioning) { if (tryLbProvisioning) {
// check if LB appliance can be dynamically provisioned // check if LB appliance can be dynamically provisioned
List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider,
LBDeviceAllocationState.Provider);
if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) {
for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) {
if (lbProviderDevice.getState() == LBDeviceState.Enabled) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) {
@ -489,13 +493,14 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway);
CreateLoadBalancerApplianceAnswer createLbAnswer = null; CreateLoadBalancerApplianceAnswer createLbAnswer = null;
try { try {
createLbAnswer = (CreateLoadBalancerApplianceAnswer) _agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd);
if (createLbAnswer == null || !createLbAnswer.getResult()) { if (createLbAnswer == null || !createLbAnswer.getResult()) {
s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId());
continue; continue;
} }
} catch (Exception agentException) { } catch (Exception agentException) {
s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to "
+ agentException.getMessage());
continue; continue;
} }
@ -532,7 +537,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false,
null, null); null, null);
} catch (Exception e) { } catch (Exception e) {
s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage()
+ ". So provisioned load balancer appliance will be destroyed.");
} }
if (lbAppliance != null) { if (lbAppliance != null) {
@ -547,7 +553,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP);
DestroyLoadBalancerApplianceAnswer answer = null; DestroyLoadBalancerApplianceAnswer answer = null;
try { try {
answer = (DestroyLoadBalancerApplianceAnswer) _agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.warn("Failed to destroy load balancer appliance created"); s_logger.warn("Failed to destroy load balancer appliance created");
} else { } else {
@ -684,7 +690,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP);
DestroyLoadBalancerApplianceAnswer answer = null; DestroyLoadBalancerApplianceAnswer answer = null;
try { try {
answer = (DestroyLoadBalancerApplianceAnswer) _agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd);
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer.getDetails()); s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer.getDetails());
} }
@ -726,7 +732,6 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
return false; return false;
} }
private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException {
List<StaticNat> staticNats = new ArrayList<StaticNat>(); List<StaticNat> staticNats = new ArrayList<StaticNat>();
IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0);
@ -754,9 +759,11 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public void setNic(Nic nic) { public void setNic(Nic nic) {
this.nic = nic; this.nic = nic;
} }
public MappingState getState() { public MappingState getState() {
return state; return state;
} }
public void setState(MappingState state) { public void setState(MappingState state) {
this.state = state; this.state = state;
} }
@ -779,7 +786,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (loadBalancingIpAddress == null) { if (loadBalancingIpAddress == null) {
String msg = "Ran out of guest IP addresses."; String msg = "Ran out of guest IP addresses.";
s_logger.error(msg); s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId());
} }
@ -861,7 +868,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network);
if (network.getState() == Network.State.Allocated) { if (network.getState() == Network.State.Allocated) {
s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId()
+ "; this network is not implemented. Skipping backend commands.");
return true; return true;
} }
@ -884,7 +892,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
mappingStates.add(nic.getState()); mappingStates.add(nic.getState());
Nic loadBalancingIpNic = nic.getNic(); Nic loadBalancingIpNic = nic.getNic();
if (loadBalancingIpNic == null) { if (loadBalancingIpNic == null) {
continue; continue;
} }
// Change the source IP address for the load balancing rule to be the load balancing IP address // Change the source IP address for the load balancing rule to be the load balancing IP address
@ -893,7 +901,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
boolean inline = _networkMgr.isNetworkInlineMode(network); boolean inline = _networkMgr.isNetworkInlineMode(network);
LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies()); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(),
rule.getHealthCheckPolicies());
if (rule.isAutoScaleConfig()) { if (rule.isAutoScaleConfig()) {
loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
} }
@ -955,16 +964,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (add) { if (add) {
ExternalLoadBalancerDeviceVO lbDeviceVO = null; ExternalLoadBalancerDeviceVO lbDeviceVO = null;
// on restart network, device could have been allocated already, skip allocation if a device is assigned // on restart network, device could have been allocated already, skip allocation if a device is assigned
lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
// allocate a load balancer device for the network // allocate a load balancer device for the network
lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId();
s_logger.error(msg); s_logger.error(msg);
throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId());
} }
} }
externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId());
@ -988,10 +997,10 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null);
if (add) { if (add) {
// on restart network, network could have already been implemented. If already implemented then return // on restart network, network could have already been implemented. If already implemented then return
Nic selfipNic = getPlaceholderNic(guestConfig); Nic selfipNic = getPlaceholderNic(guestConfig);
if (selfipNic != null) { if (selfipNic != null) {
return true; return true;
} }
// Acquire a self-ip address from the guest network IP address range // Acquire a self-ip address from the guest network IP address range
@ -1048,7 +1057,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId());
String action = add ? "implemented" : "shut down"; String action = add ? "implemented" : "shut down";
s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId()
+ ") with VLAN tag " + guestVlanTag);
} }
return true; return true;
@ -1100,7 +1110,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
//We won't deploy IP, instead the firewall in front of us would do it //We won't deploy IP, instead the firewall in front of us would do it
List<Provider> providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); List<Provider> providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall);
//Only support one provider now //Only support one provider now
if (providers == null) { if (providers == null) {
s_logger.error("Cannot find firewall provider for network " + network.getId()); s_logger.error("Cannot find firewall provider for network " + network.getId());
return null; return null;
} }
@ -1193,7 +1203,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri()));
cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); answer = (HealthCheckLBConfigAnswer)_agentMgr.easySend(externalLoadBalancer.getId(), cmd);
} }
} catch (Exception ex) { } catch (Exception ex) {
s_logger.error("Exception Occured ", ex); s_logger.error("Exception Occured ", ex);

View File

@ -18,6 +18,7 @@ package com.cloud.network;
import java.net.Inet6Address; import java.net.Inet6Address;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.security.InvalidParameterException; import java.security.InvalidParameterException;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -1124,8 +1125,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
} else { } else {
ipv4 = true; ipv4 = true;
} }
} } catch (UnknownHostException e) {
catch (UnknownHostException e) {
s_logger.error("Unable to convert gateway IP to a InetAddress", e); s_logger.error("Unable to convert gateway IP to a InetAddress", e);
throw new InvalidParameterValueException("Gateway parameter is invalid"); throw new InvalidParameterValueException("Gateway parameter is invalid");
} }
@ -3805,13 +3805,21 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
@Override @DB @Override @DB
public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId,
String vlan, String startIp, String endIp, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat) String broadcastUriString, String startIp, String endIp, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat, Long networkOfferingId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
Account owner = _accountMgr.getAccount(networkOwnerId); Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offeirng // Get system network offering
NetworkOfferingVO ntwkOff = findSystemNetworkOffering(NetworkOffering.SystemPrivateGatewayNetworkOffering); NetworkOfferingVO ntwkOff = null;
if (networkOfferingId != null)
{
ntwkOff = _networkOfferingDao.findById(networkOfferingId);
}
if (ntwkOff == null)
{
ntwkOff = findSystemNetworkOffering(NetworkOffering.SystemPrivateGatewayNetworkOffering);
}
// Validate physical network // Validate physical network
PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId); PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
@ -3843,6 +3851,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
URI uri = BroadcastDomainType.fromString(broadcastUriString);
String uriString = uri.toString();
BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
// numeric vlan or vlan uri are ok for now
// TODO make a test for any supported scheme
if (!(tiep == BroadcastDomainType.Vlan
|| tiep == BroadcastDomainType.Lswitch)) {
throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
}
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
@ -3851,18 +3868,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true); DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
//check if we need to create guest network //check if we need to create guest network
Network privateNetwork = _networksDao.getPrivateNetwork(BroadcastDomainType.Vlan.toUri(vlan).toString(), cidr, Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr,
networkOwnerId, pNtwk.getDataCenterId()); networkOwnerId, pNtwk.getDataCenterId(), null);
if (privateNetwork == null) { if (privateNetwork == null) {
//create Guest network //create Guest network
privateNetwork = _networkMgr.createGuestNetwork(ntwkOff.getId(), networkName, displayText, gateway, cidr, vlan, privateNetwork = _networkMgr.createGuestNetwork(ntwkOff.getId(), networkName, displayText, gateway, cidr, uriString,
null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null); null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null);
s_logger.debug("Created private network " + privateNetwork); s_logger.debug("Created private network " + privateNetwork);
} else { } else {
s_logger.debug("Private network already exists: " + privateNetwork); s_logger.debug("Private network already exists: " + privateNetwork);
//Do not allow multiple private gateways with same Vlan within a VPC //Do not allow multiple private gateways with same Vlan within a VPC
if(vpcId.equals(privateNetwork.getVpcId())){ if(vpcId.equals(privateNetwork.getVpcId())){
throw new InvalidParameterValueException("Private network for the vlan: " + vlan + " and cidr "+ cidr +" already exists " + throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr "+ cidr +" already exists " +
"for Vpc "+vpcId+" in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); "for Vpc "+vpcId+" in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
} }
} }

View File

@ -78,10 +78,9 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
@Inject @Inject
IpAddressManager _ipAddrMgr; IpAddressManager _ipAddrMgr;
public ExternalGuestNetworkGuru() { public ExternalGuestNetworkGuru() {
super(); super();
_isolationMethods = new IsolationMethod[] { IsolationMethod.GRE, IsolationMethod.L3, IsolationMethod.VLAN }; _isolationMethods = new IsolationMethod[] {IsolationMethod.GRE, IsolationMethod.L3, IsolationMethod.VLAN};
} }
@Override @Override
@ -109,7 +108,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
return null; return null;
} }
NetworkVO config = (NetworkVO) super.design(offering, plan, userSpecified, owner); NetworkVO config = (NetworkVO)super.design(offering, plan, userSpecified, owner);
if (config == null) { if (config == null) {
return null; return null;
} else if (_networkModel.networkIsConfiguredForExternalNetworking(plan.getDataCenterId(), config.getId())) { } else if (_networkModel.networkIsConfiguredForExternalNetworking(plan.getDataCenterId(), config.getId())) {
@ -151,7 +150,8 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
} }
implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag)); implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag));
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0); ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN,
"Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0);
} else { } else {
vlanTag = Integer.parseInt(BroadcastDomainType.getValue(config.getBroadcastUri())); vlanTag = Integer.parseInt(BroadcastDomainType.getValue(config.getBroadcastUri()));
implemented.setBroadcastUri(config.getBroadcastUri()); implemented.setBroadcastUri(config.getBroadcastUri());
@ -195,20 +195,20 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
// Mask the destination address of all port forwarding rules in this network with the new guest VLAN offset // Mask the destination address of all port forwarding rules in this network with the new guest VLAN offset
List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId()); List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId());
for (PortForwardingRuleVO pfRule : pfRulesInNetwork) { for (PortForwardingRuleVO pfRule : pfRulesInNetwork) {
if (pfRule.getDestinationIpAddress() != null) { if (pfRule.getDestinationIpAddress() != null) {
long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize); long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize);
String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask); String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask);
pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress)); pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress));
_pfRulesDao.update(pfRule.getId(), pfRule); _pfRulesDao.update(pfRule.getId(), pfRule);
} }
} }
// Mask the destination address of all static nat rules in this network with the new guest VLAN offset // Mask the destination address of all static nat rules in this network with the new guest VLAN offset
// Here the private ip of the nic get updated. When secondary ip are present the gc will not triggered // Here the private ip of the nic get updated. When secondary ip are present the gc will not triggered
List <IPAddressVO> ipAddrsOfNw = _ipAddressDao.listStaticNatPublicIps(config.getId()); List<IPAddressVO> ipAddrsOfNw = _ipAddressDao.listStaticNatPublicIps(config.getId());
for (IPAddressVO ip: ipAddrsOfNw) { for (IPAddressVO ip : ipAddrsOfNw) {
if (ip.getVmIp() != null) { if (ip.getVmIp() != null) {
long ipMask = getIpMask(ip.getVmIp(), cidrSize); long ipMask = getIpMask(ip.getVmIp(), cidrSize);
String maskedVmIp = NetUtils.long2Ip(newCidrAddress | ipMask); String maskedVmIp = NetUtils.long2Ip(newCidrAddress | ipMask);
ip.setVmIp(maskedVmIp); ip.setVmIp(maskedVmIp);
_ipAddressDao.update(ip.getId(), ip); _ipAddressDao.update(ip.getId(), ip);
} }
@ -227,7 +227,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
NicProfile profile = super.allocate(config, nic, vm); NicProfile profile = super.allocate(config, nic, vm);
boolean _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key())); boolean _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));
if (_isEnabled) { if (_isEnabled) {
return null; return null;
} }
@ -243,7 +243,8 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
return profile; return profile;
} }
@Override @DB @Override
@DB
public void deallocate(Network config, NicProfile nic, VirtualMachineProfile vm) { public void deallocate(Network config, NicProfile nic, VirtualMachineProfile vm) {
super.deallocate(config, nic, vm); super.deallocate(config, nic, vm);
@ -264,7 +265,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
public void reserve(NicProfile nic, Network config, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) public void reserve(NicProfile nic, Network config, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
assert (nic.getReservationStrategy() == ReservationStrategy.Start) : "What can I do for nics that are not allocated at start? "; assert (nic.getReservationStrategy() == ReservationStrategy.Start) : "What can I do for nics that are not allocated at start? ";
boolean _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key())); boolean _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));
if (_isEnabled) { if (_isEnabled) {
return; return;
} }
@ -314,7 +315,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
} }
private long getIpMask(String ipAddress, long cidrSize) { private long getIpMask(String ipAddress, long cidrSize) {
return NetUtils.ip2Long(ipAddress) & ~(0xffffffffffffffffl << (32 - cidrSize)); return NetUtils.ip2Long(ipAddress) & ~(0xffffffffffffffffl << (32 - cidrSize));
} }
} }

View File

@ -215,7 +215,8 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
return network; return network;
} }
@Override @DB @Override
@DB
public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) { public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) {
if (network.getSpecifyIpRanges()) { if (network.getSpecifyIpRanges()) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
@ -234,7 +235,6 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
} }
} }
public int getVlanOffset(long physicalNetworkId, int vlanTag) { public int getVlanOffset(long physicalNetworkId, int vlanTag) {
PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId); PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) { if (pNetwork == null) {
@ -247,13 +247,13 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
Integer lowestVlanTag = null; Integer lowestVlanTag = null;
List<Pair<Integer, Integer>> vnetList = pNetwork.getVnet(); List<Pair<Integer, Integer>> vnetList = pNetwork.getVnet();
//finding the vlanrange in which the vlanTag lies. //finding the vlanrange in which the vlanTag lies.
for (Pair <Integer,Integer> vnet : vnetList){ for (Pair<Integer, Integer> vnet : vnetList) {
if (vlanTag >= vnet.first() && vlanTag <= vnet.second()){ if (vlanTag >= vnet.first() && vlanTag <= vnet.second()) {
lowestVlanTag = vnet.first(); lowestVlanTag = vnet.first();
} }
} }
if (lowestVlanTag == null) { if (lowestVlanTag == null) {
throw new InvalidParameterValueException ("The vlan tag does not belong to any of the existing vlan ranges"); throw new InvalidParameterValueException("The vlan tag does not belong to any of the existing vlan ranges");
} }
return vlanTag - lowestVlanTag; return vlanTag - lowestVlanTag;
} }
@ -268,12 +268,12 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
} }
protected void allocateVnet(Network network, NetworkVO implemented, long dcId, protected void allocateVnet(Network network, NetworkVO implemented, long dcId,
long physicalNetworkId, String reservationId) throws InsufficientVirtualNetworkCapcityException { long physicalNetworkId, String reservationId) throws InsufficientVirtualNetworkCapcityException {
if (network.getBroadcastUri() == null) { if (network.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId, UseSystemGuestVlans.valueIn(network.getAccountId())); String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId, UseSystemGuestVlans.valueIn(network.getAccountId()));
if (vnet == null) { if (vnet == null) {
throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a " + throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a " +
"part of network " + network + " implement ", DataCenter.class, dcId); "part of network " + network + " implement ", DataCenter.class, dcId);
} }
implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vnet)); implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vnet));
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), network.getAccountId(), ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), network.getAccountId(),
@ -317,10 +317,10 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
@Override @Override
public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile vm) public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile vm)
throws InsufficientVirtualNetworkCapcityException, throws InsufficientVirtualNetworkCapcityException,
InsufficientAddressCapacityException { InsufficientAddressCapacityException {
assert (network.getTrafficType() == TrafficType.Guest) : "Look at my name! Why are you calling" + assert (network.getTrafficType() == TrafficType.Guest) : "Look at my name! Why are you calling" +
" me when the traffic type is : " + network.getTrafficType(); " me when the traffic type is : " + network.getTrafficType();
if (nic == null) { if (nic == null) {
nic = new NicProfile(ReservationStrategy.Start, null, null, null, null); nic = new NicProfile(ReservationStrategy.Start, null, null, null, null);
@ -413,7 +413,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
if (profile.getBroadcastDomainType() == BroadcastDomainType.Vlan && if (profile.getBroadcastDomainType() == BroadcastDomainType.Vlan &&
profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) { profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) {
s_logger.debug("Releasing vnet for the network id=" + profile.getId()); s_logger.debug("Releasing vnet for the network id=" + profile.getId());
_dcDao.releaseVnet(BroadcastDomainType.getValue(profile.getBroadcastUri()), profile.getDataCenterId(), _dcDao.releaseVnet(BroadcastDomainType.getValue(profile.getBroadcastUri()), profile.getDataCenterId(),
profile.getPhysicalNetworkId(), profile.getAccountId(), profile.getReservationId()); profile.getPhysicalNetworkId(), profile.getAccountId(), profile.getReservationId());
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), profile.getAccountId(), ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), profile.getAccountId(),

View File

@ -106,7 +106,16 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
return null; return null;
} }
NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Vlan, offering.getId(), BroadcastDomainType broadcastType;
if (userSpecified != null)
{
broadcastType = userSpecified.getBroadcastDomainType();
}
else
{
broadcastType = BroadcastDomainType.Vlan;
}
NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Static, broadcastType, offering.getId(),
State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId()); State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId());
if (userSpecified != null) { if (userSpecified != null) {
if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) || if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) ||
@ -146,7 +155,6 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
nic.deallocate(); nic.deallocate();
} }
@Override @Override
public Network implement(Network network, NetworkOffering offering, DeployDestination dest, public Network implement(Network network, NetworkOffering offering, DeployDestination dest,
ReservationContext context) throws InsufficientVirtualNetworkCapcityException { ReservationContext context) throws InsufficientVirtualNetworkCapcityException {
@ -178,9 +186,8 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
return nic; return nic;
} }
protected void getIp(NicProfile nic, DataCenter dc, Network network) protected void getIp(NicProfile nic, DataCenter dc, Network network)
throws InsufficientVirtualNetworkCapcityException,InsufficientAddressCapacityException { throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
if (nic.getIp4Address() == null) { if (nic.getIp4Address() == null) {
PrivateIpVO ipVO = _privateIpDao.allocateIpAddress(network.getDataCenterId(), network.getId(), null); PrivateIpVO ipVO = _privateIpDao.allocateIpAddress(network.getDataCenterId(), network.getId(), null);
String vlanTag = BroadcastDomainType.getValue(network.getBroadcastUri()); String vlanTag = BroadcastDomainType.getValue(network.getBroadcastUri());
@ -191,11 +198,11 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
nic.setIp4Address(ip.getIpAddress()); nic.setIp4Address(ip.getIpAddress());
nic.setGateway(ip.getGateway()); nic.setGateway(ip.getGateway());
nic.setNetmask(ip.getNetmask()); nic.setNetmask(ip.getNetmask());
nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag())); nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getBroadcastUri()));
nic.setBroadcastUri(IsolationType.Vlan.toUri(ip.getVlanTag())); nic.setBroadcastUri(IsolationType.Vlan.toUri(ip.getBroadcastUri()));
nic.setBroadcastType(BroadcastDomainType.Vlan); nic.setBroadcastType(BroadcastDomainType.Vlan);
nic.setFormat(AddressFormat.Ip4); nic.setFormat(AddressFormat.Ip4);
nic.setReservationId(String.valueOf(ip.getVlanTag())); nic.setReservationId(String.valueOf(ip.getBroadcastUri()));
nic.setMacAddress(ip.getMacAddress()); nic.setMacAddress(ip.getMacAddress());
} }
@ -203,7 +210,6 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
nic.setDns2(dc.getDns2()); nic.setDns2(dc.getDns2());
} }
@Override @Override
public void updateNicProfile(NicProfile profile, Network network) { public void updateNicProfile(NicProfile profile, Network network) {
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());

View File

@ -433,7 +433,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
for (final PublicIpAddress ipAddr : ipAddrList) { for (final PublicIpAddress ipAddr : ipAddrList) {
boolean add = (ipAddr.getState() == IpAddress.State.Releasing ? false : true); boolean add = (ipAddr.getState() == IpAddress.State.Releasing ? false : true);
String macAddress = vlanMacAddress.get(ipAddr.getVlanTag()); String macAddress = vlanMacAddress.get(BroadcastDomainType.getValue(BroadcastDomainType.fromString(ipAddr.getVlanTag())));
IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, false, IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, false,
ipAddr.isSourceNat(), ipAddr.getVlanTag(), ipAddr.getGateway(), ipAddr.getNetmask(), macAddress, ipAddr.isSourceNat(), ipAddr.getVlanTag(), ipAddr.getGateway(), ipAddr.getNetmask(), macAddress,
@ -580,7 +580,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
" as its nic is already gone from VPC router " + router); " as its nic is already gone from VPC router " + router);
} else { } else {
macAddress = nic.getMacAddress(); macAddress = nic.getMacAddress();
vlanMacAddress.put(ipAddr.getVlanTag(), macAddress); vlanMacAddress.put(BroadcastDomainType.getValue(BroadcastDomainType.fromString(ipAddr.getVlanTag())), macAddress);
ipsToSend.add(ipAddr); ipsToSend.add(ipAddr);
} }
} }
@ -653,7 +653,6 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
}); });
} }
protected boolean sendNetworkACLs(VirtualRouter router, List<? extends NetworkACLItem> rules, long guestNetworkId, boolean isPrivateGateway) protected boolean sendNetworkACLs(VirtualRouter router, List<? extends NetworkACLItem> rules, long guestNetworkId, boolean isPrivateGateway)
throws ResourceUnavailableException { throws ResourceUnavailableException {
Commands cmds = new Commands(Command.OnError.Continue); Commands cmds = new Commands(Command.OnError.Continue);
@ -1118,7 +1117,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
// Ensure that in multiple vlans case we first send all ip addresses of vlan1, then all ip addresses of vlan2, etc.. // Ensure that in multiple vlans case we first send all ip addresses of vlan1, then all ip addresses of vlan2, etc..
Map<String, ArrayList<PrivateIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PrivateIpAddress>>(); Map<String, ArrayList<PrivateIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PrivateIpAddress>>();
for (final PrivateIpAddress ipAddress : ips) { for (final PrivateIpAddress ipAddress : ips) {
String vlanTag = ipAddress.getVlanTag(); String vlanTag = ipAddress.getBroadcastUri();
ArrayList<PrivateIpAddress> ipList = vlanIpMap.get(vlanTag); ArrayList<PrivateIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) { if (ipList == null) {
ipList = new ArrayList<PrivateIpAddress>(); ipList = new ArrayList<PrivateIpAddress>();
@ -1136,7 +1135,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
for (final PrivateIpAddress ipAddr : ipAddrList) { for (final PrivateIpAddress ipAddr : ipAddrList) {
Network network = _networkModel.getNetwork(ipAddr.getNetworkId()); Network network = _networkModel.getNetwork(ipAddr.getNetworkId());
IpAddressTO ip = new IpAddressTO(Account.ACCOUNT_ID_SYSTEM, ipAddr.getIpAddress(), add, false, IpAddressTO ip = new IpAddressTO(Account.ACCOUNT_ID_SYSTEM, ipAddr.getIpAddress(), add, false,
ipAddr.getSourceNat(), ipAddr.getVlanTag(), ipAddr.getGateway(), ipAddr.getNetmask(), ipAddr.getMacAddress(), ipAddr.getSourceNat(), ipAddr.getBroadcastUri(), ipAddr.getGateway(), ipAddr.getNetmask(), ipAddr.getMacAddress(),
null, false); null, false);
ip.setTrafficType(network.getTrafficType()); ip.setTrafficType(network.getTrafficType());
@ -1229,20 +1228,21 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
_networkModel.isSecurityGroupSupportedInNetwork(privateNetwork), _networkModel.isSecurityGroupSupportedInNetwork(privateNetwork),
_networkModel.getNetworkTag(vm.getHypervisorType(), privateNetwork)); _networkModel.getNetworkTag(vm.getHypervisorType(), privateNetwork));
} else { } else {
String vlanTag = BroadcastDomainType.getValue(privateNetwork.getBroadcastUri());
String netmask = NetUtils.getCidrNetmask(privateNetwork.getCidr()); String netmask = NetUtils.getCidrNetmask(privateNetwork.getCidr());
PrivateIpAddress ip = new PrivateIpAddress(ipVO, vlanTag, privateNetwork.getGateway(), netmask, PrivateIpAddress ip = new PrivateIpAddress(ipVO, privateNetwork.getBroadcastUri().toString(), privateNetwork.getGateway(), netmask,
NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(ipVO.getMacAddress()))); NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(ipVO.getMacAddress())));
URI netUri = BroadcastDomainType.fromString(ip.getVlanTag()); URI netUri = BroadcastDomainType.fromString(ip.getBroadcastUri());
privateNicProfile.setIp4Address(ip.getIpAddress()); privateNicProfile.setIp4Address(ip.getIpAddress());
privateNicProfile.setGateway(ip.getGateway()); privateNicProfile.setGateway(ip.getGateway());
privateNicProfile.setNetmask(ip.getNetmask()); privateNicProfile.setNetmask(ip.getNetmask());
privateNicProfile.setIsolationUri(netUri); privateNicProfile.setIsolationUri(netUri);
privateNicProfile.setBroadcastUri(netUri); privateNicProfile.setBroadcastUri(netUri);
privateNicProfile.setBroadcastType(BroadcastDomainType.Vlan); // can we solve this in setBroadcastUri()???
// or more plugable construct is desirable
privateNicProfile.setBroadcastType(BroadcastDomainType.getSchemeValue(netUri));
privateNicProfile.setFormat(AddressFormat.Ip4); privateNicProfile.setFormat(AddressFormat.Ip4);
privateNicProfile.setReservationId(String.valueOf(ip.getVlanTag())); privateNicProfile.setReservationId(String.valueOf(ip.getBroadcastUri()));
privateNicProfile.setMacAddress(ip.getMacAddress()); privateNicProfile.setMacAddress(ip.getMacAddress());
} }

View File

@ -67,8 +67,8 @@ public class PrivateGatewayProfile implements PrivateGateway {
} }
@Override @Override
public String getVlanTag() { public String getBroadcastUri() {
return vpcGateway.getVlanTag(); return vpcGateway.getBroadcastUri();
} }
@Override @Override

View File

@ -19,7 +19,7 @@ package com.cloud.network.vpc;
public class PrivateIpAddress implements PrivateIp{ public class PrivateIpAddress implements PrivateIp{
String vlanTag; String broadcastUri;
String gateway; String gateway;
String netmask; String netmask;
String ipAddress; String ipAddress;
@ -29,16 +29,16 @@ public class PrivateIpAddress implements PrivateIp{
/** /**
* @param privateIp * @param privateIp
* @param vlanTag * @param broadcastUri
* @param gateway * @param gateway
* @param netmask * @param netmask
* @param macAddress TODO * @param macAddress TODO
* @param physicalNetworkId TODO * @param physicalNetworkId TODO
*/ */
public PrivateIpAddress(PrivateIpVO privateIp, String vlanTag, String gateway, String netmask, String macAddress) { public PrivateIpAddress(PrivateIpVO privateIp, String broadcastUri, String gateway, String netmask, String macAddress) {
super(); super();
this.ipAddress = privateIp.getIpAddress(); this.ipAddress = privateIp.getIpAddress();
this.vlanTag = vlanTag; this.broadcastUri = broadcastUri;
this.gateway = gateway; this.gateway = gateway;
this.netmask = netmask; this.netmask = netmask;
this.macAddress = macAddress; this.macAddress = macAddress;
@ -47,8 +47,8 @@ public class PrivateIpAddress implements PrivateIp{
} }
@Override @Override
public String getVlanTag() { public String getBroadcastUri() {
return vlanTag; return broadcastUri;
} }
@Override @Override

View File

@ -45,6 +45,7 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO; import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
@ -297,6 +298,9 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>(); Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>();
Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>(); Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>();
defaultProviders.add(Provider.VPCVirtualRouter); defaultProviders.add(Provider.VPCVirtualRouter);
// Just here for 4.1, replaced by commit 836ce6c1 in newer versions
Set<Network.Provider> sdnProviders = new HashSet<Network.Provider>();
sdnProviders.add(Provider.NiciraNvp);
boolean sourceNatSvc = false; boolean sourceNatSvc = false;
boolean firewallSvs = false; boolean firewallSvs = false;
@ -308,7 +312,13 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw new InvalidParameterValueException("Service " + serviceName + " is not supported in VPC"); throw new InvalidParameterValueException("Service " + serviceName + " is not supported in VPC");
} }
svcProviderMap.put(service, defaultProviders); if (service == Service.Connectivity) {
s_logger.debug("Applying Connectivity workaround, setting provider to NiciraNvp");
svcProviderMap.put(service, sdnProviders);
}
else {
svcProviderMap.put(service, defaultProviders);
}
if (service == Service.NetworkACL) { if (service == Service.NetworkACL) {
firewallSvs = true; firewallSvs = true;
} }
@ -319,7 +329,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
} }
if (!sourceNatSvc) { if (!sourceNatSvc) {
throw new InvalidParameterValueException("SourceNat service is required by VPC offering"); s_logger.debug("Automatically adding source nat service to the list of VPC services");
svcProviderMap.put(Service.SourceNat, defaultProviders);
} }
if (!firewallSvs) { if (!firewallSvs) {
@ -1327,7 +1338,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
List<VpcGatewayVO> gateways = _vpcGatewayDao.listByVpcIdAndType(vpcId, VpcGateway.Type.Private); List<VpcGatewayVO> gateways = _vpcGatewayDao.listByVpcIdAndType(vpcId, VpcGateway.Type.Private);
if (gateways != null) { if (gateways != null) {
List<PrivateGateway> pvtGateway = new ArrayList(); List<PrivateGateway> pvtGateway = new ArrayList<PrivateGateway>();
for (VpcGatewayVO gateway: gateways) { for (VpcGatewayVO gateway: gateways) {
pvtGateway.add(getPrivateGatewayProfile(gateway)); pvtGateway.add(getPrivateGatewayProfile(gateway));
} }
@ -1355,8 +1366,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
@Override @Override
@DB @DB
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating vpc private gateway", create=true) @ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating vpc private gateway", create=true)
public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String broadcastUri, String ipAddress,
String gateway, String netmask, long gatewayOwnerId, Boolean isSourceNat, Long aclId) throws ResourceAllocationException, String gateway, String netmask, long gatewayOwnerId, Long networkOfferingId, Boolean isSourceNat, Long aclId) throws ResourceAllocationException,
ConcurrentOperationException, InsufficientCapacityException { ConcurrentOperationException, InsufficientCapacityException {
//Validate parameters //Validate parameters
@ -1367,22 +1378,58 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
throw ex; throw ex;
} }
PhysicalNetwork physNet = null;
//Validate physical network //Validate physical network
if (physicalNetworkId == null) { if (physicalNetworkId == null) {
List<? extends PhysicalNetwork> pNtwks = _ntwkModel.getPhysicalNtwksSupportingTrafficType(vpc.getZoneId(), TrafficType.Guest); List<? extends PhysicalNetwork> pNtwks = _ntwkModel.getPhysicalNtwksSupportingTrafficType(vpc.getZoneId(), TrafficType.Guest);
if (pNtwks.isEmpty() || pNtwks.size() != 1) { if (pNtwks.isEmpty() || pNtwks.size() != 1) {
throw new InvalidParameterValueException("Physical network can't be determined; pass physical network id"); throw new InvalidParameterValueException("Physical network can't be determined; pass physical network id");
} }
physicalNetworkId = pNtwks.get(0).getId(); physNet = pNtwks.get(0);
physicalNetworkId = physNet.getId();
} }
if (physNet == null) {
physNet = _entityMgr.findById(PhysicalNetwork.class,physicalNetworkId);
}
Long dcId = physNet.getDataCenterId();
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
s_logger.debug("Creating Private gateway for VPC " + vpc); s_logger.debug("Creating Private gateway for VPC " + vpc);
//1) create private network //1) create private network unless it is existing and lswitch'd
String networkName = "vpc-" + vpc.getName() + "-privateNetwork"; Network privateNtwk = null;
Network privateNtwk = _ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkId, if (BroadcastDomainType.getSchemeValue(BroadcastDomainType.fromString(broadcastUri)) == BroadcastDomainType.Lswitch) {
vlan, ipAddress, null, gateway, netmask, gatewayOwnerId, vpcId, isSourceNat); String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
privateNtwk = _ntwkDao.getPrivateNetwork(broadcastUri, cidr,
gatewayOwnerId, dcId, networkOfferingId);
s_logger.info("found and using existing network for vpc " + vpc + ": " + broadcastUri);
}
if (privateNtwk == null) {
s_logger.info("creating new network for vpc " + vpc + " using broadcast uri: " + broadcastUri);
String networkName = "vpc-" + vpc.getName() + "-privateNetwork";
privateNtwk = _ntwkSvc.createPrivateNetwork(networkName, networkName, physicalNetworkId,
broadcastUri, ipAddress, null, gateway, netmask, gatewayOwnerId, vpcId, isSourceNat, networkOfferingId);
} else { // create the nic/ip as createPrivateNetwork doesn''t do that work for us now
DataCenterVO dc = _dcDao.lockRow(physNet.getDataCenterId(), true);
//add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + ipAddress + " already used for private gateway" +
" in zone " + _entityMgr.findById(DataCenter.class,dcId).getName());
}
Long mac = dc.getMacAddress();
Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, true);
_privateIpDao.persist(privateIp);
_dcDao.update(dc.getId(), dc);
}
long networkAclId = NetworkACL.DEFAULT_DENY; long networkAclId = NetworkACL.DEFAULT_DENY;
if (aclId != null) { if (aclId != null) {
@ -1399,7 +1446,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
//2) create gateway entry //2) create gateway entry
VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(),
privateNtwk.getId(), vlan, gateway, netmask, vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId); privateNtwk.getId(), broadcastUri, gateway, netmask, vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
_vpcGatewayDao.persist(gatewayVO); _vpcGatewayDao.persist(gatewayVO);
s_logger.debug("Created vpc gateway entry " + gatewayVO); s_logger.debug("Created vpc gateway entry " + gatewayVO);

View File

@ -24,6 +24,8 @@ import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import junit.framework.Assert; import junit.framework.Assert;
@ -61,8 +63,9 @@ import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO; import com.cloud.user.AccountVO;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@Ignore("Requires database to be set up") //@Ignore("Requires database to be set up")
public class CreatePrivateNetworkTest { public class CreatePrivateNetworkTest {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger
@ -109,6 +112,10 @@ public class CreatePrivateNetworkTest {
false, false, false, false); false, false, false, false);
when(networkService._networkOfferingDao.findById(anyLong())) when(networkService._networkOfferingDao.findById(anyLong()))
.thenReturn(ntwkOff); .thenReturn(ntwkOff);
List<NetworkOfferingVO>netofferlist = new ArrayList<NetworkOfferingVO>();
netofferlist.add(ntwkOff);
when(networkService._networkOfferingDao.listSystemNetworkOfferings())
.thenReturn(netofferlist);
PhysicalNetworkVO physicalNetwork = new PhysicalNetworkVO(1L, 1L, PhysicalNetworkVO physicalNetwork = new PhysicalNetworkVO(1L, 1L,
"2-5", "200", 1L, null, "testphysicalnetwork"); "2-5", "200", 1L, null, "testphysicalnetwork");
@ -122,7 +129,7 @@ public class CreatePrivateNetworkTest {
.thenReturn(dc); .thenReturn(dc);
when(networkService._networksDao.getPrivateNetwork(anyString(), when(networkService._networksDao.getPrivateNetwork(anyString(),
anyString(), eq(1L), eq(1L))).thenReturn(null); anyString(), eq(1L), eq(1L), anyLong())).thenReturn(null);
Network net = new NetworkVO(1L, TrafficType.Guest, Mode.None, Network net = new NetworkVO(1L, TrafficType.Guest, Mode.None,
BroadcastDomainType.Vlan, 1L, 1L, 1L, 1L, "bla", "fake", BroadcastDomainType.Vlan, 1L, 1L, 1L, 1L, "bla", "fake",
@ -139,6 +146,7 @@ public class CreatePrivateNetworkTest {
when(networkService._privateIpDao.findByIpAndSourceNetworkId( when(networkService._privateIpDao.findByIpAndSourceNetworkId(
net.getId(), "10.1.1.2")).thenReturn(null); net.getId(), "10.1.1.2")).thenReturn(null);
when(networkService._privateIpDao.findByIpAndSourceNetworkIdAndVpcId(eq(1L), anyString(), eq(1L))).thenReturn(null);
} }
@Test @Test
@ -149,26 +157,26 @@ public class CreatePrivateNetworkTest {
/* Network nw; */ /* Network nw; */
try { try {
/* nw = */ /* nw = */
networkService.createPrivateNetwork("bla", "fake", 1L, "vlan:1", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, null); networkService.createPrivateNetwork("bla", "fake", 1L, "vlan:1", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, true, 1L);
/* nw = */ /* nw = */
networkService.createPrivateNetwork("bla", "fake", 1L, "lswitch:3", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, null); networkService.createPrivateNetwork("bla", "fake", 1L, "lswitch:3", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, false, 1L);
boolean invalid = false; boolean invalid = false;
boolean unsupported = false; boolean unsupported = false;
try { try {
/* nw = */ /* nw = */
networkService.createPrivateNetwork("bla", "fake", 1, "bla:2", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, null); networkService.createPrivateNetwork("bla", "fake", 1, "bla:2", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, true, 1L);
} catch (InvalidParameterValueException e) { } catch (CloudRuntimeException e) {
Assert.assertEquals("unexpected parameter exception", Assert.assertEquals("unexpected parameter exception",
"unsupported type of broadcastUri specified: bla:2", "string 'bla:2' has an unknown BroadcastDomainType.",
e.getMessage()); e.getMessage());
invalid = true; invalid = true;
} }
try { try {
/* nw = */ /* nw = */
networkService.createPrivateNetwork("bla", "fake", 1, "mido:4", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, null); networkService.createPrivateNetwork("bla", "fake", 1, "mido://4", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, false, 1L);
} catch (InvalidParameterValueException e) { } catch (InvalidParameterValueException e) {
Assert.assertEquals("unexpected parameter exception", Assert.assertEquals("unexpected parameter exception",
"unsupported type of broadcastUri specified: mido:4", "unsupported type of broadcastUri specified: mido://4",
e.getMessage()); e.getMessage());
unsupported = true; unsupported = true;
} }

View File

@ -640,7 +640,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches
*/ */
@Override @Override
public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan,
String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat) String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId, Boolean sourceNat, Long networkOfferingId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;

View File

@ -328,7 +328,7 @@ public class MockNetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implemen
* @see com.cloud.network.dao.NetworkDao#getPrivateNetwork(java.lang.String, java.lang.String, long, long) * @see com.cloud.network.dao.NetworkDao#getPrivateNetwork(java.lang.String, java.lang.String, long, long)
*/ */
@Override @Override
public NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId) { public NetworkVO getPrivateNetwork(String broadcastUri, String cidr, long accountId, long zoneId, Long netofferid) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }

View File

@ -26,10 +26,18 @@ import java.net.NetworkInterface;
import java.net.SocketException; import java.net.SocketException;
import java.net.URI; import java.net.URI;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.*; import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.googlecode.ipv6.IPv6Address; import com.googlecode.ipv6.IPv6Address;
@ -39,7 +47,6 @@ import com.googlecode.ipv6.IPv6Network;
import com.cloud.utils.IteratorUtil; import com.cloud.utils.IteratorUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import org.apache.commons.lang.SystemUtils;
public class NetUtils { public class NetUtils {
protected final static Logger s_logger = Logger.getLogger(NetUtils.class); protected final static Logger s_logger = Logger.getLogger(NetUtils.class);
@ -64,7 +71,7 @@ public class NetUtils {
private final static Random _rand = new Random(System.currentTimeMillis()); private final static Random _rand = new Random(System.currentTimeMillis());
public static long createSequenceBasedMacAddress(long macAddress) { public static long createSequenceBasedMacAddress(long macAddress) {
return macAddress | 0x060000000000l | (((long) _rand.nextInt(32768) << 25) & 0x00fffe000000l); return macAddress | 0x060000000000l | (((long)_rand.nextInt(32768) << 25) & 0x00fffe000000l);
} }
public static String getHostName() { public static String getHostName() {
@ -131,7 +138,7 @@ public class NetUtils {
int prefixLength = address.getNetworkPrefixLength(); int prefixLength = address.getNetworkPrefixLength();
if (prefixLength < 32 && prefixLength > 0) { if (prefixLength < 32 && prefixLength > 0) {
String ip = ipFromInetAddress(addr); String ip = ipFromInetAddress(addr);
if(ip.equalsIgnoreCase(defaultHostIp)) if (ip.equalsIgnoreCase(defaultHostIp))
cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength))); cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
} }
} }
@ -146,16 +153,14 @@ public class NetUtils {
private static boolean isWindows() { private static boolean isWindows() {
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
if(os != null && os.startsWith("Windows")) if (os != null && os.startsWith("Windows"))
return true; return true;
return false; return false;
} }
public static String getDefaultHostIp() { public static String getDefaultHostIp() {
if(SystemUtils.IS_OS_WINDOWS) { if (SystemUtils.IS_OS_WINDOWS) {
Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*"); Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*");
try { try {
Process result = Runtime.getRuntime().exec("route print -4"); Process result = Runtime.getRuntime().exec("route print -4");
@ -163,14 +168,14 @@ public class NetUtils {
(new InputStreamReader(result.getInputStream())); (new InputStreamReader(result.getInputStream()));
String line = output.readLine(); String line = output.readLine();
while(line != null){ while (line != null) {
Matcher matcher = pattern.matcher(line); Matcher matcher = pattern.matcher(line);
if (matcher.find()) { if (matcher.find()) {
return matcher.group(2); return matcher.group(2);
} }
line = output.readLine(); line = output.readLine();
} }
} catch( Exception e ) { } catch (Exception e) {
} }
return null; return null;
} else { } else {
@ -212,8 +217,6 @@ public class NetUtils {
return defaultRouteList[7]; return defaultRouteList[7];
} }
public static InetAddress getFirstNonLoopbackLocalInetAddress() { public static InetAddress getFirstNonLoopbackLocalInetAddress() {
InetAddress[] addrs = getAllLocalInetAddresses(); InetAddress[] addrs = getAllLocalInetAddresses();
if (addrs != null) { if (addrs != null) {
@ -322,7 +325,7 @@ public class NetUtils {
byte[] mac = ni.getHardwareAddress(); byte[] mac = ni.getHardwareAddress();
for (int i = 0; i < mac.length; i++) { for (int i = 0; i < mac.length; i++) {
macAddressAsLong |= ((long) (mac[i] & 0xff) << (mac.length - i - 1) * 8); macAddressAsLong |= ((long)(mac[i] & 0xff) << (mac.length - i - 1) * 8);
} }
} catch (SocketException e) { } catch (SocketException e) {
@ -451,7 +454,8 @@ public class NetUtils {
public static String long2Mac(long macAddress) { public static String long2Mac(long macAddress) {
StringBuilder result = new StringBuilder(17); StringBuilder result = new StringBuilder(17);
Formatter formatter = new Formatter(result); Formatter formatter = new Formatter(result);
formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", (macAddress >> 40) & 0xff, (macAddress >> 32) & 0xff, (macAddress >> 24) & 0xff, (macAddress >> 16) & 0xff, (macAddress >> 8) & 0xff, formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", (macAddress >> 40) & 0xff, (macAddress >> 32) & 0xff, (macAddress >> 24) & 0xff, (macAddress >> 16) & 0xff,
(macAddress >> 8) & 0xff,
(macAddress & 0xff)); (macAddress & 0xff));
return result.toString(); return result.toString();
@ -593,7 +597,7 @@ public class NetUtils {
if (st.countTokens() == 4) { if (st.countTokens() == 4) {
try { try {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
bytes[i] = (byte) Integer.parseInt(st.nextToken()); bytes[i] = (byte)Integer.parseInt(st.nextToken());
} }
return InetAddress.getByAddress(address, bytes); return InetAddress.getByAddress(address, bytes);
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
@ -646,7 +650,7 @@ public class NetUtils {
end = (end << (32 - size)) - 2; end = (end << (32 - size)) - 2;
int maxIps = 255; // get 255 ips as maximum int maxIps = 255; // get 255 ips as maximum
while (start <= end && maxIps > 0) { while (start <= end && maxIps > 0) {
if (!usedIps.contains(start)){ if (!usedIps.contains(start)) {
result.add(start); result.add(start);
maxIps--; maxIps--;
} }
@ -686,7 +690,7 @@ public class NetUtils {
long startNetMask = ip2Long(getCidrNetmask(size)); long startNetMask = ip2Long(getCidrNetmask(size));
long startIp = (cidr & startNetMask) + 1; //exclude the first ip since it isnt valid, e.g., 192.168.10.0 long startIp = (cidr & startNetMask) + 1; //exclude the first ip since it isnt valid, e.g., 192.168.10.0
int range = 1 << (32 - size); //e.g., /24 = 2^8 = 256 int range = 1 << (32 - size); //e.g., /24 = 2^8 = 256
range = range -1; //exclude end of the range since that is the broadcast address, e.g., 192.168.10.255 range = range - 1; //exclude end of the range since that is the broadcast address, e.g., 192.168.10.255
if (avoid.size() >= range) { if (avoid.size() >= range) {
return -1; return -1;
@ -788,7 +792,7 @@ public class NetUtils {
end++; end++;
end = (end << (32 - bits)) - 2; end = (end << (32 - bits)) - 2;
return new String[] { long2Ip(start), long2Ip(end) }; return new String[] {long2Ip(start), long2Ip(end)};
} }
@ -797,17 +801,18 @@ public class NetUtils {
return new Pair<String, Integer>(tokens[0], Integer.parseInt(tokens[1])); return new Pair<String, Integer>(tokens[0], Integer.parseInt(tokens[1]));
} }
public static enum supersetOrSubset { public static enum supersetOrSubset {
isSuperset, isSuperset,
isSubset, isSubset,
neitherSubetNorSuperset, neitherSubetNorSuperset,
sameSubnet, sameSubnet,
errorInCidrFormat errorInCidrFormat
} }
public static supersetOrSubset isNetowrkASubsetOrSupersetOfNetworkB (String cidrA, String cidrB) {
public static supersetOrSubset isNetowrkASubsetOrSupersetOfNetworkB(String cidrA, String cidrB) {
Long[] cidrALong = cidrToLong(cidrA); Long[] cidrALong = cidrToLong(cidrA);
Long[] cidrBLong = cidrToLong(cidrB); Long[] cidrBLong = cidrToLong(cidrB);
long shift =0; long shift = 0;
if (cidrALong == null || cidrBLong == null) { if (cidrALong == null || cidrBLong == null) {
//implies error in the cidr format //implies error in the cidr format
return supersetOrSubset.errorInCidrFormat; return supersetOrSubset.errorInCidrFormat;
@ -825,7 +830,7 @@ public class NetUtils {
return supersetOrSubset.isSuperset; return supersetOrSubset.isSuperset;
} }
else if (cidrALong[1] == cidrBLong[1]) { else if (cidrALong[1] == cidrBLong[1]) {
//this implies both the cidrs are equal //this implies both the cidrs are equal
return supersetOrSubset.sameSubnet; return supersetOrSubset.sameSubnet;
} }
// implies cidrA is subset of cidrB // implies cidrA is subset of cidrB
@ -867,7 +872,7 @@ public class NetUtils {
} }
long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum); long numericNetmask = (0xffffffff >> (32 - cidrSizeNum)) << (32 - cidrSizeNum);
long ipAddr = ip2Long(cidrAddress); long ipAddr = ip2Long(cidrAddress);
Long[] cidrlong = { ipAddr & numericNetmask, (long) cidrSizeNum }; Long[] cidrlong = {ipAddr & numericNetmask, (long)cidrSizeNum};
return cidrlong; return cidrlong;
} }
@ -1008,7 +1013,6 @@ public class NetUtils {
return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]); return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]);
} }
public static boolean verifyDomainNameLabel(String hostName, boolean isHostName) { public static boolean verifyDomainNameLabel(String hostName, boolean isHostName) {
// must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a // must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a
// case-insensitive manner), // case-insensitive manner),
@ -1064,13 +1068,13 @@ public class NetUtils {
} }
// Check if 2 CIDRs have exactly same IP Range // Check if 2 CIDRs have exactly same IP Range
public static boolean isSameIpRange (String cidrA, String cidrB) { public static boolean isSameIpRange(String cidrA, String cidrB) {
if(!NetUtils.isValidCIDR(cidrA)) { if (!NetUtils.isValidCIDR(cidrA)) {
s_logger.info("Invalid value of cidr " + cidrA); s_logger.info("Invalid value of cidr " + cidrA);
return false; return false;
} }
if (!NetUtils.isValidCIDR(cidrB)) { if (!NetUtils.isValidCIDR(cidrB)) {
s_logger.info("Invalid value of cidr " + cidrB); s_logger.info("Invalid value of cidr " + cidrB);
return false; return false;
} }
@ -1079,18 +1083,19 @@ public class NetUtils {
Long networkSizeFirst = Long.valueOf(cidrPairFirst[1]); Long networkSizeFirst = Long.valueOf(cidrPairFirst[1]);
Long networkSizeSecond = Long.valueOf(cidrPairSecond[1]); Long networkSizeSecond = Long.valueOf(cidrPairSecond[1]);
String ipRangeFirst [] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeFirst); String ipRangeFirst[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeFirst);
String ipRangeSecond [] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeSecond); String ipRangeSecond[] = NetUtils.getIpRangeFromCidr(cidrPairFirst[0], networkSizeSecond);
long startIpFirst = NetUtils.ip2Long(ipRangeFirst[0]); long startIpFirst = NetUtils.ip2Long(ipRangeFirst[0]);
long endIpFirst = NetUtils.ip2Long(ipRangeFirst[1]); long endIpFirst = NetUtils.ip2Long(ipRangeFirst[1]);
long startIpSecond = NetUtils.ip2Long(ipRangeSecond[0]); long startIpSecond = NetUtils.ip2Long(ipRangeSecond[0]);
long endIpSecond = NetUtils.ip2Long(ipRangeSecond[1]); long endIpSecond = NetUtils.ip2Long(ipRangeSecond[1]);
if(startIpFirst == startIpSecond && endIpFirst == endIpSecond) { if (startIpFirst == startIpSecond && endIpFirst == endIpSecond) {
return true; return true;
} }
return false; return false;
} }
public static boolean validateGuestCidr(String cidr) { public static boolean validateGuestCidr(String cidr) {
// RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the // RFC 1918 - The Internet Assigned Numbers Authority (IANA) has reserved the
// following three blocks of the IP address space for private internets: // following three blocks of the IP address space for private internets:
@ -1181,7 +1186,7 @@ public class NetUtils {
public static boolean validateIcmpType(long icmpType) { public static boolean validateIcmpType(long icmpType) {
//Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
if(!(icmpType >=0 && icmpType <=255)) { if (!(icmpType >= 0 && icmpType <= 255)) {
s_logger.warn("impcType is not within 0-255 range"); s_logger.warn("impcType is not within 0-255 range");
return false; return false;
} }
@ -1191,7 +1196,7 @@ public class NetUtils {
public static boolean validateIcmpCode(long icmpCode) { public static boolean validateIcmpCode(long icmpCode) {
//Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
if(!(icmpCode >=0 && icmpCode <=15)) { if (!(icmpCode >= 0 && icmpCode <= 15)) {
s_logger.warn("Icmp code should be within 0-15 range"); s_logger.warn("Icmp code should be within 0-15 range");
return false; return false;
} }
@ -1199,172 +1204,172 @@ public class NetUtils {
return true; return true;
} }
public static boolean isValidIpv6(String ip) { public static boolean isValidIpv6(String ip) {
try { try {
IPv6Address address = IPv6Address.fromString(ip); IPv6Address address = IPv6Address.fromString(ip);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return false; return false;
} }
return true; return true;
} }
public static boolean isValidIp6Cidr(String ip6Cidr) { public static boolean isValidIp6Cidr(String ip6Cidr) {
try { try {
IPv6Network network = IPv6Network.fromString(ip6Cidr); IPv6Network network = IPv6Network.fromString(ip6Cidr);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return false; return false;
} }
return true; return true;
} }
public static int getIp6CidrSize(String ip6Cidr) { public static int getIp6CidrSize(String ip6Cidr) {
IPv6Network network = null; IPv6Network network = null;
try { try {
network = IPv6Network.fromString(ip6Cidr); network = IPv6Network.fromString(ip6Cidr);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return 0; return 0;
} }
return network.getNetmask().asPrefixLength(); return network.getNetmask().asPrefixLength();
} }
// Can cover 127 bits // Can cover 127 bits
public static String getIp6FromRange(String ip6Range) { public static String getIp6FromRange(String ip6Range) {
String[] ips = ip6Range.split("-"); String[] ips = ip6Range.split("-");
String startIp = ips[0]; String startIp = ips[0];
IPv6Address start = IPv6Address.fromString(startIp); IPv6Address start = IPv6Address.fromString(startIp);
BigInteger gap = countIp6InRange(ip6Range); BigInteger gap = countIp6InRange(ip6Range);
BigInteger next = new BigInteger(gap.bitLength(), _rand); BigInteger next = new BigInteger(gap.bitLength(), _rand);
while (next.compareTo(gap) >= 0) { while (next.compareTo(gap) >= 0) {
next = new BigInteger(gap.bitLength(), _rand); next = new BigInteger(gap.bitLength(), _rand);
} }
BigInteger startInt = convertIPv6AddressToBigInteger(start); BigInteger startInt = convertIPv6AddressToBigInteger(start);
BigInteger resultInt = startInt.add(next); BigInteger resultInt = startInt.add(next);
InetAddress resultAddr; InetAddress resultAddr;
try { try {
resultAddr = InetAddress.getByAddress(resultInt.toByteArray()); resultAddr = InetAddress.getByAddress(resultInt.toByteArray());
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
return null; return null;
} }
IPv6Address ip = IPv6Address.fromInetAddress(resultAddr); IPv6Address ip = IPv6Address.fromInetAddress(resultAddr);
return ip.toString(); return ip.toString();
} }
//RFC3315, section 9.4 //RFC3315, section 9.4
public static String getDuidLL(String macAddress) { public static String getDuidLL(String macAddress) {
String duid = "00:03:00:01:" + macAddress; String duid = "00:03:00:01:" + macAddress;
return duid; return duid;
} }
private static BigInteger convertIPv6AddressToBigInteger(IPv6Address addr) { private static BigInteger convertIPv6AddressToBigInteger(IPv6Address addr) {
InetAddress inetAddr; InetAddress inetAddr;
try { try {
inetAddr = addr.toInetAddress(); inetAddr = addr.toInetAddress();
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
return null; return null;
} }
return new BigInteger(inetAddr.getAddress()); return new BigInteger(inetAddr.getAddress());
} }
// Can cover 127 bits // Can cover 127 bits
public static BigInteger countIp6InRange(String ip6Range) { public static BigInteger countIp6InRange(String ip6Range) {
if (ip6Range == null) { if (ip6Range == null) {
return null; return null;
} }
String[] ips = ip6Range.split("-"); String[] ips = ip6Range.split("-");
String startIp = ips[0]; String startIp = ips[0];
String endIp = ips[0]; String endIp = ips[0];
if (ips.length > 1) { if (ips.length > 1) {
endIp = ips[1]; endIp = ips[1];
} }
IPv6Address start, end; IPv6Address start, end;
try { try {
start = IPv6Address.fromString(startIp); start = IPv6Address.fromString(startIp);
end = IPv6Address.fromString(endIp); end = IPv6Address.fromString(endIp);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return null; return null;
} }
BigInteger startInt = convertIPv6AddressToBigInteger(start); BigInteger startInt = convertIPv6AddressToBigInteger(start);
BigInteger endInt = convertIPv6AddressToBigInteger(end); BigInteger endInt = convertIPv6AddressToBigInteger(end);
if (startInt.compareTo(endInt) > 0) { if (startInt.compareTo(endInt) > 0) {
return null; return null;
} }
return endInt.subtract(startInt).add(BigInteger.ONE); return endInt.subtract(startInt).add(BigInteger.ONE);
} }
public static boolean isIp6InRange(String ip6, String ip6Range) { public static boolean isIp6InRange(String ip6, String ip6Range) {
if (ip6Range == null) { if (ip6Range == null) {
return false; return false;
} }
String[] ips = ip6Range.split("-"); String[] ips = ip6Range.split("-");
String startIp = ips[0]; String startIp = ips[0];
String endIp = null; String endIp = null;
if (ips.length > 1) { if (ips.length > 1) {
endIp = ips[1]; endIp = ips[1];
} }
IPv6Address start = IPv6Address.fromString(startIp); IPv6Address start = IPv6Address.fromString(startIp);
IPv6Address end = IPv6Address.fromString(endIp); IPv6Address end = IPv6Address.fromString(endIp);
IPv6Address ip = IPv6Address.fromString(ip6); IPv6Address ip = IPv6Address.fromString(ip6);
if (start.compareTo(ip) <= 0 && end.compareTo(ip) >= 0) { if (start.compareTo(ip) <= 0 && end.compareTo(ip) >= 0) {
return true; return true;
} }
return false; return false;
} }
public static boolean isIp6InNetwork(String ip6, String ip6Cidr) { public static boolean isIp6InNetwork(String ip6, String ip6Cidr) {
IPv6Network network = null; IPv6Network network = null;
try { try {
network = IPv6Network.fromString(ip6Cidr); network = IPv6Network.fromString(ip6Cidr);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return false; return false;
} }
IPv6Address ip = IPv6Address.fromString(ip6); IPv6Address ip = IPv6Address.fromString(ip6);
return network.contains(ip); return network.contains(ip);
} }
public static boolean isIp6RangeOverlap(String ipRange1, String ipRange2) { public static boolean isIp6RangeOverlap(String ipRange1, String ipRange2) {
String[] ips = ipRange1.split("-"); String[] ips = ipRange1.split("-");
String startIp1 = ips[0]; String startIp1 = ips[0];
String endIp1 = null; String endIp1 = null;
if (ips.length > 1) { if (ips.length > 1) {
endIp1 = ips[1]; endIp1 = ips[1];
} }
IPv6Address start1 = IPv6Address.fromString(startIp1); IPv6Address start1 = IPv6Address.fromString(startIp1);
IPv6Address end1 = IPv6Address.fromString(endIp1); IPv6Address end1 = IPv6Address.fromString(endIp1);
IPv6AddressRange range1 = IPv6AddressRange.fromFirstAndLast(start1, end1); IPv6AddressRange range1 = IPv6AddressRange.fromFirstAndLast(start1, end1);
ips = ipRange2.split("-"); ips = ipRange2.split("-");
String startIp2 = ips[0]; String startIp2 = ips[0];
String endIp2 = null; String endIp2 = null;
if (ips.length > 1) { if (ips.length > 1) {
endIp2 = ips[1]; endIp2 = ips[1];
} }
IPv6Address start2 = IPv6Address.fromString(startIp2); IPv6Address start2 = IPv6Address.fromString(startIp2);
IPv6Address end2 = IPv6Address.fromString(endIp2); IPv6Address end2 = IPv6Address.fromString(endIp2);
IPv6AddressRange range2 = IPv6AddressRange.fromFirstAndLast(start2, end2); IPv6AddressRange range2 = IPv6AddressRange.fromFirstAndLast(start2, end2);
return range1.overlaps(range2); return range1.overlaps(range2);
} }
public static String getNextIp6InRange(String currentIp, String ipRange) { public static String getNextIp6InRange(String currentIp, String ipRange) {
String[] ips = ipRange.split("-"); String[] ips = ipRange.split("-");
String startIp = ips[0]; String startIp = ips[0];
String endIp = null; String endIp = null;
if (ips.length > 1) { if (ips.length > 1) {
endIp = ips[1]; endIp = ips[1];
} }
IPv6Address start = IPv6Address.fromString(startIp); IPv6Address start = IPv6Address.fromString(startIp);
IPv6Address end = IPv6Address.fromString(endIp); IPv6Address end = IPv6Address.fromString(endIp);
IPv6Address current = IPv6Address.fromString(currentIp); IPv6Address current = IPv6Address.fromString(currentIp);
IPv6Address result = null; IPv6Address result = null;
if (current.equals(end)) { if (current.equals(end)) {
result = start; result = start;
} else{ } else {
result = current.add(1); result = current.add(1);
} }
String resultIp = null; String resultIp = null;
if (result != null) { if (result != null) {
resultIp = result.toString(); resultIp = result.toString();
} }
return resultIp; return resultIp;
} }
public static boolean isValidVlan(String vlan) { public static boolean isValidVlan(String vlan) {
try { try {
@ -1383,36 +1388,36 @@ public class NetUtils {
// types of BroadcastDomainTypes // types of BroadcastDomainTypes
public static URI generateUriForPvlan(String primaryVlan, String isolatedPvlan) { public static URI generateUriForPvlan(String primaryVlan, String isolatedPvlan) {
return URI.create("pvlan://" + primaryVlan + "-i" + isolatedPvlan); return URI.create("pvlan://" + primaryVlan + "-i" + isolatedPvlan);
} }
public static String getPrimaryPvlanFromUri(URI uri) { public static String getPrimaryPvlanFromUri(URI uri) {
String[] vlans = uri.getHost().split("-"); String[] vlans = uri.getHost().split("-");
if (vlans.length < 1) { if (vlans.length < 1) {
return null; return null;
} }
return vlans[0]; return vlans[0];
} }
public static String getIsolatedPvlanFromUri(URI uri) { public static String getIsolatedPvlanFromUri(URI uri) {
String[] vlans = uri.getHost().split("-"); String[] vlans = uri.getHost().split("-");
if (vlans.length < 2) { if (vlans.length < 2) {
return null; return null;
} }
for (String vlan : vlans) { for (String vlan : vlans) {
if (vlan.startsWith("i")) { if (vlan.startsWith("i")) {
return vlan.replace("i", " ").trim(); return vlan.replace("i", " ").trim();
} }
} }
return null; return null;
} }
public static String generateMacOnIncrease(String baseMac, long l) { public static String generateMacOnIncrease(String baseMac, long l) {
long mac = mac2Long(baseMac); long mac = mac2Long(baseMac);
if (l > 0xFFFFl) { if (l > 0xFFFFl) {
return null; return null;
} }
mac = mac + (l << 24); mac = mac + (l << 24);
mac = mac & 0x06FFFFFFFFFFl; mac = mac & 0x06FFFFFFFFFFl;
return long2Mac(mac); return long2Mac(mac);
} }
} }