Support for adding private network

Conflicts:

	server/src/com/cloud/network/NetworkManagerImpl.java
	server/src/com/cloud/upgrade/dao/Upgrade2214to30.java
This commit is contained in:
Alena Prokharchyk 2012-06-04 11:32:04 -07:00
parent 1a621a01f5
commit 0a7faa9838
50 changed files with 1478 additions and 483 deletions

View File

@ -12,8 +12,6 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.agent.api;
import java.util.Map;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
@ -21,14 +19,9 @@ import com.cloud.agent.api.to.VirtualMachineTO;
* @author Alena Prokharchyk
*/
public class PlugNicCommand extends Command {
public enum Param {
DhcpRange,
NetworkDomain
}
VirtualMachineTO vm;
NicTO nic;
Map<Param, String> params;
public VirtualMachineTO getVirtualMachine() {
return vm;
@ -46,9 +39,8 @@ public class PlugNicCommand extends Command {
protected PlugNicCommand() {
}
public PlugNicCommand(VirtualMachineTO vm, NicTO nic, Map<Param, String> params) {
public PlugNicCommand(VirtualMachineTO vm, NicTO nic) {
this.vm = vm;
this.nic = nic;
this.params = params;
}
}

View File

@ -0,0 +1,24 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.agent.api;
/**
* @author Alena Prokharchyk
*/
public class SetupGuestNetworkAnswer extends Answer{
public SetupGuestNetworkAnswer() {}
public SetupGuestNetworkAnswer(SetupGuestNetworkCommand cmd, boolean success, String result) {
super(cmd, success, result);
}
}

View File

@ -0,0 +1,48 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.agent.api;
import com.cloud.agent.api.routing.NetworkElementCommand;
/**
* @author Alena Prokharchyk
*/
public class SetupGuestNetworkCommand extends NetworkElementCommand{
String dhcpRange;
String networkDomain;
String defaultDns1 = null;
String defaultDns2 = null;
boolean isRedundant = false;
Integer priority;
boolean add = true;
@Override
public boolean executeInSequence() {
return true;
}
protected SetupGuestNetworkCommand() {
}
public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority,
String defaultDns1, String defaultDns2, boolean add) {
this.dhcpRange = dhcpRange;
this.networkDomain = networkDomain;
this.defaultDns1 = defaultDns1;
this.defaultDns2 = defaultDns2;
this.isRedundant = isRedundant;
this.priority = priority;
this.add = add;
}
}

View File

@ -31,6 +31,7 @@ public abstract class NetworkElementCommand extends Command {
public static final String ROUTER_IP = "router.ip";
public static final String ROUTER_GUEST_IP = "router.guest.ip";
public static final String ZONE_NETWORK_TYPE = "zone.network.type";
public static final String GUEST_BRIDGE = "guest.bridge";
protected NetworkElementCommand() {
super();

View File

@ -59,13 +59,15 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd {
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a physical network")
private Long domainId;
@Parameter(name=ApiConstants.BROADCAST_DOMAIN_RANGE, type=CommandType.STRING, description="the broadcast domain range for the physical network[Pod or Zone]. In Acton release it can be Zone only in Advance zone, and Pod in Basic")
@Parameter(name=ApiConstants.BROADCAST_DOMAIN_RANGE, type=CommandType.STRING, description="the broadcast domain " +
"range for the physical network[Pod or Zone]. In Acton release it can be Zone only in Advance zone, and Pod in Basic")
private String broadcastDomainRange;
@Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network")
private List<String> tags;
@Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]")
@Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING,
description="the isolation method for the physical network[VLAN/L3/GRE]")
private List<String> isolationMethods;
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the physical network")

View File

@ -0,0 +1,195 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCreateCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.NetworkResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.network.Network;
import com.cloud.user.UserContext;
@Implementation(description="Creates a private network", responseObject=NetworkResponse.class)
public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(CreatePrivateNetworkCmd.class.getName());
private static final String s_name = "createnetworkresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network")
private String name;
@Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network")
private String displayText;
@IdentityMapper(entityTableName="physical_network")
@Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID the network belongs to")
private Long physicalNetworkId;
@Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the network")
private String gateway;
@Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the network")
private String netmask;
@Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the network IP range")
private String startIp;
@Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" +
" range. If not specified, will be defaulted to startIP")
private String endIp;
@Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the ID or VID of the network")
private String vlan;
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network")
private String accountName;
@IdentityMapper(entityTableName="projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key")
private Long projectId;
@IdentityMapper(entityTableName="domain")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network")
private Long domainId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getGateway() {
return gateway;
}
public String getVlan() {
return vlan;
}
public String getAccountName() {
return accountName;
}
public Long getDomainId() {
return domainId;
}
public String getNetmask() {
return netmask;
}
public String getStartIp() {
return startIp;
}
public String getNetworkName() {
return name;
}
public String getDisplayText() {
return displayText;
}
public Long getProjectId() {
return projectId;
}
public long getPhysicalNetworkId() {
return physicalNetworkId;
}
public String getEndIp() {
return endIp;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public void create() throws ResourceAllocationException {
Network result = null;
try {
result = _networkService.createPrivateNetwork(getNetworkName(), getDisplayText(), getPhysicalNetworkId(), getVlan(),
getStartIp(), getEndIp(), getGateway(), getNetmask(), getEntityOwnerId());
} catch (InsufficientCapacityException ex){
s_logger.info(ex);
s_logger.trace(ex);
throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
} catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
if (result != null) {
this.setEntityId(result.getId());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network");
}
}
@Override
public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{
Network result = _networkService.getNetwork(getEntityId());
if (result != null) {
NetworkResponse response = _responseGenerator.createNetworkResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private network");
}
}
@Override
public long getEntityOwnerId() {
Long accountId = finalyzeAccountId(accountName, domainId, projectId, true);
if (accountId == null) {
return UserContext.current().getCaller().getId();
}
return accountId;
}
@Override
public String getEventType() {
return EventTypes.EVENT_NETWORK_CREATE;
}
@Override
public String getEventDescription() {
return "creating private network";
}
@Override
public String getEntityTable() {
return "networks";
}
}

View File

@ -150,4 +150,23 @@ public interface NetworkService {
IpAddress associateIP(long ipId, Long networkId, Long vpcId) throws InsufficientAddressCapacityException,
ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException;
/**
* @param networkName
* @param displayText
* @param physicalNetworkId
* @param vlan
* @param startIp
* @param endIP TODO
* @param gateway
* @param netmask
* @param networkOwnerId
* @return
* @throws InsufficientCapacityException
* @throws ConcurrentOperationException
* @throws ResourceAllocationException
*/
Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan,
String startIp, String endIP, String gateway, String netmask, long networkOwnerId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
}

View File

@ -61,4 +61,25 @@ public interface VirtualNetworkApplianceService {
VirtualRouter startRouter(long id) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException;
VirtualRouter destroyRouter(long routerId) throws ResourceUnavailableException, ConcurrentOperationException;
/**
* @param router
* @param network
* @param isRedundant TODO
* @return
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
* @throws InsufficientCapacityException
*/
boolean addRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
/**
* @param router
* @param network
* @param isRedundant TODO
* @return
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
*/
boolean removeRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException;
}

View File

@ -19,7 +19,8 @@ package com.cloud.network;
public interface VirtualRouterProvider {
public enum VirtualRouterProviderType {
VirtualRouter,
ElasticLoadBalancerVm
ElasticLoadBalancerVm,
VPCVirtualRouter
}
public VirtualRouterProviderType getType();

View File

@ -40,5 +40,11 @@ public interface VpcProvider extends NetworkElement{
*/
boolean shutdownVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException;
boolean createPrivateGateway();
boolean createVpnGateway();
boolean deletePrivateGateway();
boolean deleteVpnGateway();
}

View File

@ -34,7 +34,6 @@ public interface VirtualRouter extends VirtualMachine {
FAULT
}
RedundantState getRedundantState();
String getGuestIpAddress();
String getPublicIpAddress();
boolean isStopPending();
void setStopPending(boolean stopPending);

View File

@ -25,7 +25,7 @@ public interface Vpc extends ControlledEntity{
Disabled
}
public static final String _supportedProviders = Network.Provider.VirtualRouter.getName();
public static final String _supportedProviders = Network.Provider.VPCVirtualRouter.getName();
boolean readyToUse();

View File

@ -1,45 +0,0 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.router.VirtualRouter;
/**
* @author Alena Prokharchyk
*/
public interface VpcVirtualNetworkApplianceService {
/**
* @param router
* @param network
* @return
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
* @throws InsufficientCapacityException
*/
public boolean addVmToNetwork(VirtualRouter router, Network network) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException;
/**
* @param router
* @param network
* @return
* @throws ResourceUnavailableException
* @throws ConcurrentOperationException
*/
boolean removeVmFromNetwork(VirtualRouter router, Network network) throws ConcurrentOperationException, ResourceUnavailableException;
}

View File

@ -27,7 +27,8 @@ import com.cloud.network.VpnUser;
public interface RemoteAccessVpnService {
RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId) throws NetworkRuleConflictException;
RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId)
throws NetworkRuleConflictException;
void destroyRemoteAccessVpn(long vpnServerAddressId) throws ResourceUnavailableException;
RemoteAccessVpn startRemoteAccessVpn(long vpnServerAddressId, boolean openFirewall) throws ResourceUnavailableException;

View File

@ -39,7 +39,8 @@ public interface NetworkOffering {
public final static String SystemControlNetwork = "System-Control-Network";
public final static String SystemManagementNetwork = "System-Management-Network";
public final static String SystemStorageNetwork = "System-Storage-Network";
public final static String SystemPrivateGatewayNetworkOffering = "System-Private-Gateway-Network-Offering";
public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService";
public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService";
public final static String OvsIsolatedNetworkOfferingWithSourceNatService = "OvsIsolatedNetworkOfferingWithSourceNatService";

BIN
awsapi.log.2012-05-30.gz Normal file

Binary file not shown.

View File

@ -357,3 +357,7 @@ createVPCGateway=com.cloud.api.commands.CreateVPCGatewayCmd;15
listVPCGateways=com.cloud.api.commands.ListVPCGatewaysCmd;15
deleteVPCGateway=com.cloud.api.commands.DeleteVPCGatewayCmd;15
#### Private network command
createPrivateNetwork=com.cloud.api.commands.CreatePrivateNetworkCmd;1
deletePrivateNetwork=com.cloud.api.commands.CreatePrivateNetworkCmd;1

View File

@ -78,6 +78,7 @@
<adapter name="DirectNetworkGuru" class="com.cloud.network.guru.DirectNetworkGuru"/>
<adapter name="DirectPodBasedNetworkGuru" class="com.cloud.network.guru.DirectPodBasedNetworkGuru"/>
<adapter name="OvsGuestNetworkGuru" class="com.cloud.network.guru.OvsGuestNetworkGuru"/>
<adapter name="PrivateNetworkGuru" class="com.cloud.network.guru.PrivateNetworkGuru"/>
</adapters>
<adapters key="com.cloud.cluster.ClusterServiceAdapter">
<adapter name="ClusterService" class="com.cloud.cluster.ClusterServiceServletAdapter"/>

View File

@ -41,9 +41,6 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
@Column(name="public_netmask")
private String publicNetmask;
@Column(name="guest_ip_address")
private String guestIpAddress;
@Column(name="is_redundant_router")
boolean isRedundantRouter;
@ -140,10 +137,6 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
public void setPublicNetmask(String publicNetmask) {
this.publicNetmask = publicNetmask;
}
public void setGuestIpAddress(String routerIpAddress) {
this.guestIpAddress = routerIpAddress;
}
@Override
public long getDataCenterIdToDeployIn() {
@ -158,11 +151,6 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter {
return publicMacAddress;
}
@Override
public String getGuestIpAddress() {
return guestIpAddress;
}
protected DomainRouterVO() {
super();
}

View File

@ -1608,6 +1608,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
} else {
continue;
}
} else if (offering.getTrafficType() == TrafficType.Guest) {
continue;
}
userNetwork.setBroadcastDomainType(broadcastDomainType);

View File

@ -124,6 +124,7 @@ import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl;
import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl;
import com.cloud.network.security.dao.VmRulesetLogDaoImpl;
import com.cloud.network.vpc.VpcManagerImpl;
import com.cloud.network.vpc.Dao.PrivateIpDaoImpl;
import com.cloud.network.vpc.Dao.VpcDaoImpl;
import com.cloud.network.vpc.Dao.VpcOfferingDaoImpl;
import com.cloud.network.vpc.Dao.VpcOfferingServiceMapDaoImpl;
@ -337,6 +338,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com
addDao("VpcDao", VpcDaoImpl.class);
addDao("VpcOfferingDao", VpcOfferingDaoImpl.class);
addDao("VpcOfferingServiceMapDao", VpcOfferingServiceMapDaoImpl.class);
addDao("PrivateIpDao", PrivateIpDaoImpl.class);
}
@Override

View File

@ -414,4 +414,12 @@ public interface NetworkManager extends NetworkService {
*/
void unassignIPFromVpcNetwork(long ipId);
/**
* @param vm
* @param networkId
* @return
*/
NicProfile getNicProfile(VirtualMachine vm, long networkId);
}

View File

@ -131,6 +131,7 @@ import com.cloud.network.element.SourceNatServiceProvider;
import com.cloud.network.element.StaticNatServiceProvider;
import com.cloud.network.element.UserDataServiceProvider;
import com.cloud.network.element.VirtualRouterElement;
import com.cloud.network.element.VpcVirtualRouterElement;
import com.cloud.network.guru.NetworkGuru;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
@ -147,8 +148,10 @@ import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.rules.StaticNatRuleImpl;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.Dao.PrivateIpDao;
import com.cloud.network.vpn.RemoteAccessVpnService;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability;
@ -300,6 +303,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
StorageNetworkManager _stnwMgr;
@Inject
VpcManager _vpcMgr;
@Inject
PrivateIpDao _privateIpDao;
private final HashMap<String, NetworkOfferingVO> _systemNetworks = new HashMap<String, NetworkOfferingVO>(5);
@ -1327,6 +1332,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true);
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
_systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering);
NetworkOfferingVO privateGatewayNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering,
GuestType.Isolated);
privateGatewayNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(privateGatewayNetworkOffering);
_systemNetworks.put(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering, privateGatewayNetworkOffering);
// populate providers
Map<Network.Service, Set<Network.Provider>> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Set<Network.Provider>>();
@ -1347,7 +1357,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
sgProviders.add(Provider.SecurityGroupProvider);
defaultSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders);
Map<Network.Service, Set<Network.Provider>> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Set<Network.Provider>>();
Map<Network.Service, Set<Network.Provider>> defaultIsolatedSourceNatEnabledNetworkOfferingProviders =
new HashMap<Network.Service, Set<Network.Provider>>();
defaultProviders.clear();
defaultProviders.add(Network.Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, defaultProviders);
@ -2267,6 +2278,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
return profiles;
}
@Override
public NicProfile getNicProfile(VirtualMachine vm, long networkId) {
NicVO nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
NetworkVO network = _networksDao.findById(networkId);
Integer networkRate = getNetworkRate(network.getId(), vm.getId());
NetworkGuru guru = _networkGurus.get(network.getGuruName());
NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(),
networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network));
guru.updateNicProfile(profile, network);
return profile;
}
@Override
@DB
@ -3512,14 +3537,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return success;
}
private boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) {
List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(networkId);
protected boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) {
//cleanup Public vlans
List<VlanVO> publicVlans = _vlanDao.listVlansByNetworkId(networkId);
boolean result = true;
for (VlanVO vlan : vlans) {
for (VlanVO vlan : publicVlans) {
if (!_configMgr.deleteVlanAndPublicIpRange(_accountMgr.getSystemUser().getId(), vlan.getId(), callerAccount)) {
s_logger.warn("Failed to delete vlan " + vlan.getId() + ");");
result = false;
}
}
//cleanup private vlans
int privateIpAllocCount = _privateIpDao.countAllocatedByNetworkId(networkId);
if (privateIpAllocCount > 0) {
s_logger.warn("Can't delete Private ip range for network " + networkId + " as it has allocated ip addresses");
result = false;
} else {
_privateIpDao.deleteByNetworkId(networkId);
s_logger.debug("Deleted ip range for private network id=" + networkId);
}
return result;
}
@ -4999,7 +5036,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List<String> isolationMethods, String broadcastDomainRangeStr, Long domainId, List<String> tags, String name) {
public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List<String>
isolationMethods, String broadcastDomainRangeStr, Long domainId, List<String> tags, String name) {
// Check if zone exists
if (zoneId == null) {
@ -6495,6 +6533,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId,
Network.Provider.VPCVirtualRouter.getName(), null, null);
// add instance of the provider
VpcVirtualRouterElement element = (VpcVirtualRouterElement) getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
if (element == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
}
element.addElement(nsp.getId());
return nsp;
}
@ -6955,7 +6999,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
public boolean isVmPartOfNetwork(long vmId, long ntwkId) {
if (_nicDao.findByInstanceIdAndNetworkId(ntwkId, vmId) != null) {
if (_nicDao.findNonReleasedByInstanceIdAndNetworkId(ntwkId, vmId) != null) {
return true;
}
return false;
@ -6990,5 +7034,63 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
_ipAddressDao.update(ipId, ip);
s_logger.debug("IP address " + ip + " is no longer associated with the network inside vpc id=" + vpcId);
}
@Override @DB
public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId,
String vlan, String startIp, String endIp, String gateway, String netmask, long networkOwnerId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offeirng
NetworkOfferingVO ntwkOff = _systemNetworks.get(NetworkOffering.SystemPrivateGatewayNetworkOffering);
// Validate physical network
PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" +
" having the given id");
ex.addProxyObject("physical_network", physicalNetworkId, "physicalNetworkId");
throw ex;
}
// VALIDATE IP INFO
// if end ip is not specified, default it to startIp
if (!NetUtils.isValidIp(startIp)) {
throw new InvalidParameterValueException("Invalid format for the startIp parameter");
}
if (endIp == null) {
endIp = startIp;
} else if (!NetUtils.isValidIp(endIp)) {
throw new InvalidParameterValueException("Invalid format for the endIp parameter");
}
String cidr = null;
if (!NetUtils.isValidIp(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
Transaction txn = Transaction.currentTxn();
txn.start();
//create Guest network
Network privateNetwork = createGuestNetwork(ntwkOff.getId(), networkName, displayText, gateway, cidr, vlan,
null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, null);
//add entry to private_ip_address table
PrivateIpVO privateIp = new PrivateIpVO(startIp, privateNetwork.getId());
_privateIpDao.persist(privateIp);
txn.commit();
s_logger.debug("Private network " + privateNetwork + " is created");
return privateNetwork;
}
}

View File

@ -54,6 +54,7 @@ import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LbStickinessMethod;
@ -161,10 +162,26 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(1);
params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true);
_routerMgr.deployVirtualRouterInGuestNetwork(network, dest, _accountMgr.getAccount(network.getAccountId()), params,
List<DomainRouterVO> routers = _routerMgr.deployVirtualRouterInGuestNetwork(network, dest,
_accountMgr.getAccount(network.getAccountId()), params,
offering.getRedundantRouter());
return true;
if ((routers == null) || (routers.size() == 0)) {
throw new ResourceUnavailableException("Can't find at least one running router!",
DataCenter.class, network.getDataCenterId());
}
boolean success = true;
for (VirtualRouter router : routers) {
//Add router to guest network
success = success && _routerMgr.addRouterToGuestNetwork(router, network, false);
if (!success) {
s_logger.warn("Failed to plug nic in network " + network + " for virtual router router " + router);
} else {
s_logger.debug("Successfully plugged nic in network " + network + " for virtual router " + router);
}
}
return success;
}
@Override
@ -196,7 +213,19 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
throw new ResourceUnavailableException("Can't find at least one running router!",
DataCenter.class, network.getDataCenterId());
}
return true;
boolean success = true;
for (VirtualRouter router : routers) {
//Add router to guest network
success = success && _routerMgr.addRouterToGuestNetwork(router, network, false);
if (!success) {
s_logger.warn("Failed to plug nic in network " + network + " for virtual router " + router);
} else {
s_logger.debug("Successfully plugged nic in network " + network + " for virtual router " + router);
}
}
return success;
}
@Override

View File

@ -35,7 +35,6 @@ import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VpcVirtualNetworkApplianceManager;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcService;
import com.cloud.network.vpc.VpcVirtualNetworkApplianceService;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.component.Inject;
import com.cloud.vm.DomainRouterVO;
@ -53,8 +52,6 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
@Inject
NetworkService _ntwkService;
@Inject
VpcVirtualNetworkApplianceService _vpcElementService;
@Inject
VpcService _vpcService;
@ -116,13 +113,8 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
boolean success = true;
for (VirtualRouter router : routers) {
//1) Check if router is already a part of the network
if (_ntwkService.isVmPartOfNetwork(router.getId(), network.getId())) {
s_logger.debug("Router " + router + " is already part of the network " + network);
continue;
}
//2) Call plugNics in the network service
success = success && _vpcElementService.addVmToNetwork(router, network);
//Add router to guest network
success = success && _routerMgr.addRouterToGuestNetwork(router, network, false);
}
if (!success) {
@ -131,7 +123,6 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
s_logger.debug("Successfully plugged nic in network " + network + " for virtual router in vpc id=" + vpcId);
}
return success;
}
@ -155,7 +146,8 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(1);
params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true);
List<DomainRouterVO> routers = _vpcRouterMgr.deployVirtualRouterInVpc(vpc, dest, _accountMgr.getAccount(vpc.getAccountId()), params);
List<DomainRouterVO> routers = _vpcRouterMgr.deployVirtualRouterInVpc(vpc, dest,
_accountMgr.getAccount(vpc.getAccountId()), params);
if ((routers == null) || (routers.size() == 0)) {
throw new ResourceUnavailableException("Can't find at least one running router!",
DataCenter.class, network.getDataCenterId());
@ -163,21 +155,14 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
boolean success = true;
for (VirtualRouter router : routers) {
//1) Check if router is already a part of the network
if (_ntwkService.isVmPartOfNetwork(router.getId(), network.getId())) {
s_logger.debug("Router " + router + " is already part of the network " + network);
continue;
//2) Add router to guest network
success = success && _routerMgr.addRouterToGuestNetwork(router, network, false);
if (!success) {
s_logger.warn("Failed to plug nic in network " + network + " for virtual router " + router);
} else {
s_logger.debug("Successfully plugged nic in network " + network + " for virtual router " + router);
}
//2) Call plugNics in the network service
success = success && _vpcElementService.addVmToNetwork(router, network);
}
if (!success) {
s_logger.warn("Failed to plug nic in network " + network + " for virtual router in vpc id=" + vpcId);
} else {
s_logger.debug("Successfully plugged nic in network " + network + " for virtual router in vpc id=" + vpcId);
}
return success;
}
@ -200,13 +185,12 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
continue;
}
//2) Call unplugNics in the network service
success = success && _vpcElementService.removeVmFromNetwork(router, network);
}
if (!success) {
s_logger.warn("Failed to unplug nic in network " + network + " for virtual router in vpc id=" + vpcId);
} else {
s_logger.debug("Successfully unplugged nic in network " + network + " for virtual router in vpc id=" + vpcId);
success = success && _vpcRouterMgr.removeRouterFromGuestNetwork(router, network, false);
if (!success) {
s_logger.warn("Failed to unplug nic in network " + network + " for virtual router " + router);
} else {
s_logger.debug("Successfully unplugged nic in network " + network + " for virtual router " + router);
}
}
return success;
@ -229,13 +213,12 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
continue;
}
//2) Call unplugNics in the network service
success = success && _vpcElementService.removeVmFromNetwork(router, config);
}
if (!success) {
s_logger.warn("Failed to unplug nic in network " + config + " for virtual router in vpc id=" + vpcId);
} else {
s_logger.debug("Successfully unplugged nic in network " + config + " for virtual router in vpc id=" + vpcId);
success = success && _vpcRouterMgr.removeRouterFromGuestNetwork(router, config, false);
if (!success) {
s_logger.warn("Failed to unplug nic in network " + config + " for virtual router " + router);
} else {
s_logger.debug("Successfully unplugged nic in network " + config + " for virtual router " + router);
}
}
return success;
@ -260,5 +243,29 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
public Map<Service, Map<Capability, String>> getCapabilities() {
return capabilities;
}
@Override
public boolean createPrivateGateway() {
//TODO - add implementation here
return true;
}
@Override
public boolean createVpnGateway() {
//TODO - add implementation here
return true;
}
@Override
public boolean deletePrivateGateway() {
//TODO - add implementation here
return true;
}
@Override
public boolean deleteVpnGateway() {
//TODO - add implementation here
return true;
}
}

View File

@ -115,10 +115,11 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
protected boolean canHandle(NetworkOffering offering, DataCenter dc) {
// This guru handles only Guest Isolated network that supports Source nat service
if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated) {
&& offering.getGuestType() == Network.GuestType.Isolated && !offering.isSystemOnly()) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
s_logger.trace("We only take care of non-system Guest networks of type " + GuestType.Isolated + " in zone of type "
+ NetworkType.Advanced);
return false;
}
}

View File

@ -0,0 +1,215 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.guru;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkProfile;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.network.vpc.Dao.PrivateIpDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic.ReservationStrategy;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@Local(value = NetworkGuru.class)
public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru {
private static final Logger s_logger = Logger.getLogger(PrivateNetworkGuru.class);
@Inject
protected ConfigurationManager _configMgr;
@Inject
protected PrivateIpDao _privateIpDao;
private static final TrafficType[] _trafficTypes = {TrafficType.Guest};
protected PrivateNetworkGuru() {
super();
}
@Override
public boolean isMyTrafficType(TrafficType type) {
for (TrafficType t : _trafficTypes) {
if (t == type) {
return true;
}
}
return false;
}
@Override
public TrafficType[] getSupportedTrafficType() {
return _trafficTypes;
}
protected boolean canHandle(NetworkOffering offering, DataCenter dc) {
// This guru handles only system Guest network
if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated && offering.isSystemOnly()) {
return true;
} else {
s_logger.trace("We only take care of system Guest networks of type " + GuestType.Isolated + " in zone of type "
+ NetworkType.Advanced);
return false;
}
}
@Override
public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {
DataCenter dc = _configMgr.getZone(plan.getDataCenterId());
if (!canHandle(offering, dc)) {
return null;
}
NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(),
State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId());
if (userSpecified != null) {
if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) ||
(userSpecified.getCidr() != null && userSpecified.getGateway() == null)) {
throw new InvalidParameterValueException("cidr and gateway must be specified together.");
}
if (userSpecified.getCidr() != null) {
network.setCidr(userSpecified.getCidr());
network.setGateway(userSpecified.getGateway());
} else {
String guestNetworkCidr = dc.getGuestNetworkCidr();
if (guestNetworkCidr != null) {
String[] cidrTuple = guestNetworkCidr.split("\\/");
network.setGateway(NetUtils.getIpRangeStartIpFromCidr(cidrTuple[0], Long.parseLong(cidrTuple[1])));
network.setCidr(guestNetworkCidr);
} else if (dc.getNetworkType() == NetworkType.Advanced) {
throw new CloudRuntimeException("Can't design network " + network + "; guest CIDR is not configured per zone " + dc);
}
}
if (offering.getSpecifyVlan()) {
network.setBroadcastUri(userSpecified.getBroadcastUri());
network.setState(State.Setup);
}
} else {
throw new CloudRuntimeException("Can't design network " + network + "; netmask/gateway must be passed in");
}
return network;
}
@Override
public void deallocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address());
}
PrivateIpVO ip = _privateIpDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
if (ip != null) {
_privateIpDao.releaseIpAddress(nic.getIp4Address(), nic.getNetworkId());
}
nic.deallocate();
}
@Override
public Network implement(Network network, NetworkOffering offering, DeployDestination dest,
ReservationContext context) throws InsufficientVirtualNetworkCapcityException {
return network;
}
@Override
public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
DataCenter dc = _configMgr.getZone(network.getDataCenterId());
NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
if (!canHandle(offering, dc)) {
return null;
}
if (nic == null) {
nic = new NicProfile(ReservationStrategy.Create, null, null, null, null);
} else if (nic.getIp4Address() == null) {
nic.setStrategy(ReservationStrategy.Start);
} else {
nic.setStrategy(ReservationStrategy.Create);
}
_privateIpDao.allocateIpAddress(network.getDataCenterId(), network.getId());
nic.setStrategy(ReservationStrategy.Create);
return nic;
}
@Override
public void updateNicProfile(NicProfile profile, Network network) {
DataCenter dc = _configMgr.getZone(network.getDataCenterId());
if (profile != null) {
profile.setDns1(dc.getDns1());
profile.setDns2(dc.getDns2());
}
}
@Override
public void reserve(NicProfile nic, Network network, VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest, ReservationContext context)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
if (nic.getIp4Address() == null) {
_privateIpDao.allocateIpAddress(network.getDataCenterId(), network.getId());
nic.setStrategy(ReservationStrategy.Create);
}
}
@Override
public boolean release(NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String reservationId) {
return true;
}
@Override
public void shutdown(NetworkProfile profile, NetworkOffering offering) {
}
@Override
public boolean trash(Network network, NetworkOffering offering, Account owner) {
return true;
}
@Override
public void updateNetworkProfile(NetworkProfile networkProfile) {
DataCenter dc = _configMgr.getZone(networkProfile.getDataCenterId());
networkProfile.setDns1(dc.getDns1());
networkProfile.setDns2(dc.getDns2());
}
}

View File

@ -132,7 +132,8 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru {
}
@Override
public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws InsufficientVirtualNetworkCapcityException,
public NicProfile allocate(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
throws InsufficientVirtualNetworkCapcityException,
InsufficientAddressCapacityException, ConcurrentOperationException {
DataCenter dc = _dcDao.findById(network.getDataCenterId());
@ -172,7 +173,8 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru {
}
@Override
public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) throws InsufficientVirtualNetworkCapcityException {
public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context)
throws InsufficientVirtualNetworkCapcityException {
return network;
}

View File

@ -130,6 +130,7 @@ import com.cloud.vm.VirtualMachineName;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VirtualMachineProfile.Param;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
@Local(value = { ElasticLoadBalancerManager.class })
public class ElasticLoadBalancerManagerImpl implements
@ -187,6 +188,8 @@ public class ElasticLoadBalancerManagerImpl implements
PhysicalNetworkServiceProviderDao _physicalProviderDao;
@Inject
VirtualRouterProviderDao _vrProviderDao;
@Inject
NicDao _nicDao;
String _name;
@ -276,7 +279,7 @@ public class ElasticLoadBalancerManagerImpl implements
}
private void createApplyLoadBalancingRulesCommands(
List<LoadBalancingRule> rules, DomainRouterVO elbVm, Commands cmds) {
List<LoadBalancingRule> rules, DomainRouterVO elbVm, Commands cmds, long guestNetworkId) {
LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
@ -295,7 +298,8 @@ public class ElasticLoadBalancerManagerImpl implements
lbs[i++] = lb;
}
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs,elbVm.getPublicIpAddress(),elbVm.getGuestIpAddress(),elbVm.getPrivateIpAddress());
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs,elbVm.getPublicIpAddress(),
_nicDao.getIpAddress(guestNetworkId, elbVm.getId()),elbVm.getPrivateIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP,
elbVm.getPrivateIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME,
@ -312,9 +316,9 @@ public class ElasticLoadBalancerManagerImpl implements
}
protected boolean applyLBRules(DomainRouterVO elbVm,
List<LoadBalancingRule> rules) throws ResourceUnavailableException {
List<LoadBalancingRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyLoadBalancingRulesCommands(rules, elbVm, cmds);
createApplyLoadBalancingRulesCommands(rules, elbVm, cmds, guestNetworkId);
// Send commands to elbVm
return sendCommandsToRouter(elbVm, cmds);
}
@ -359,7 +363,7 @@ public class ElasticLoadBalancerManagerImpl implements
lb, dstList, policyList);
lbRules.add(loadBalancing);
}
return applyLBRules(elbVm, lbRules);
return applyLBRules(elbVm, lbRules, network.getId());
} else if (elbVm.getState() == State.Stopped
|| elbVm.getState() == State.Stopping) {
s_logger.debug("ELB VM is in "
@ -889,8 +893,6 @@ public class ElasticLoadBalancerManagerImpl implements
elbVm.setPublicIpAddress(nic.getIp4Address());
elbVm.setPublicNetmask(nic.getNetmask());
elbVm.setPublicMacAddress(nic.getMacAddress());
} else if (nic.getTrafficType() == TrafficType.Guest) {
elbVm.setGuestIpAddress(nic.getIp4Address());
} else if (nic.getTrafficType() == TrafficType.Control) {
elbVm.setPrivateIpAddress(nic.getIp4Address());
elbVm.setPrivateMacAddress(nic.getMacAddress());
@ -921,6 +923,7 @@ public class ElasticLoadBalancerManagerImpl implements
DataCenterVO dcVo = _dcDao.findById(elbVm.getDataCenterIdToDeployIn());
NicProfile controlNic = null;
Long guestNetworkId = null;
if(profile.getHypervisorType() == HypervisorType.VMware && dcVo.getNetworkType() == NetworkType.Basic) {
// TODO this is a ugly to test hypervisor type here
@ -928,12 +931,15 @@ public class ElasticLoadBalancerManagerImpl implements
for (NicProfile nic : profile.getNics()) {
if (nic.getTrafficType() == TrafficType.Guest && nic.getIp4Address() != null) {
controlNic = nic;
guestNetworkId = nic.getNetworkId();
}
}
} else {
for (NicProfile nic : profile.getNics()) {
if (nic.getTrafficType() == TrafficType.Control && nic.getIp4Address() != null) {
controlNic = nic;
} else if (nic.getTrafficType() == TrafficType.Guest) {
guestNetworkId = nic.getNetworkId();
}
}
}
@ -957,7 +963,7 @@ public class ElasticLoadBalancerManagerImpl implements
s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of ELB vm " + elbVm + " start.");
if (!lbRules.isEmpty()) {
createApplyLoadBalancingRulesCommands(lbRules, elbVm, cmds);
createApplyLoadBalancingRulesCommands(lbRules, elbVm, cmds, guestNetworkId);
}
return true;

View File

@ -48,9 +48,15 @@ import com.cloud.agent.api.GetDomRVersionCmd;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.PlugNicAnswer;
import com.cloud.agent.api.PlugNicCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.SetupGuestNetworkAnswer;
import com.cloud.agent.api.SetupGuestNetworkCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.UnPlugNicAnswer;
import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.routing.DhcpEntryCommand;
@ -121,8 +127,6 @@ import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PublicIpAddress;
@ -196,6 +200,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.MacAddress;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
@ -709,11 +714,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
private VmDataCommand generateVmDataCommand(VirtualRouter router, String vmPrivateIpAddress, String userData,
String serviceOffering, String zoneName, String guestIpAddress, String vmName,
String vmInstanceName, long vmId, String publicKey) {
String vmInstanceName, long vmId, String publicKey, long guestNetworkId) {
VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
@ -1256,10 +1261,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
//3) Deploy Virtual Router(s)
try {
int count = routerCount - routers.size();
PublicIp sourceNatIp = _networkMgr.assignSourceNatIpAddressToGuestNetwork(owner, guestNetwork);
for (int i = 0; i < count; i++) {
DomainRouterVO router = deployRouter(owner, dest, plan, params, publicNetwork, controlNetwork, guestNetwork, isRedundant,
vrProvider, offeringId, sourceNatIp, null);
DomainRouterVO router = deployRouter(owner, dest, plan, params, isRedundant, vrProvider, offeringId,
null);
routers.add(router);
}
} finally {
@ -1271,8 +1275,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
protected DomainRouterVO deployRouter(Account owner, DeployDestination dest, DeploymentPlan plan, Map<Param, Object> params,
boolean setupPublicNetwork, boolean setupControlNetwork, Network guestNetwork, boolean isRedundant,
VirtualRouterProvider vrProvider, long svcOffId, PublicIp sourceNatIp, Long vpcId) throws ConcurrentOperationException,
boolean isRedundant, VirtualRouterProvider vrProvider, long svcOffId,
Long vpcId) throws ConcurrentOperationException,
InsufficientAddressCapacityException, InsufficientServerCapacityException, InsufficientCapacityException,
StorageUnavailableException, ResourceUnavailableException {
@ -1280,9 +1284,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating the router " + id + " in datacenter " + dest.getDataCenter());
}
List<Pair<NetworkVO, NicProfile>> networks = createRouterNetworks(owner, setupPublicNetwork, setupControlNetwork, guestNetwork,
isRedundant, plan, sourceNatIp);
//1) Create router control network
List<Pair<NetworkVO, NicProfile>> networks = createRouterControlNetwork(owner, isRedundant, plan);
ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(svcOffId);
@ -1357,7 +1361,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
break;
} catch (InsufficientCapacityException ex) {
if (startRetry < 2 && iter.hasNext()) {
s_logger.debug("Failed to start the domR " + router + " with hypervisor type " + hType + ", destroying it and recreating one more time");
s_logger.debug("Failed to start the domR " + router + " with hypervisor type " + hType + ", " +
"destroying it and recreating one more time");
//destroy the router
destroyRouter(router.getId());
continue;
@ -1367,82 +1372,24 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} finally {
startRetry++;
}
}
}
//3) Plug public nic
return router;
}
protected List<Pair<NetworkVO, NicProfile>> createRouterNetworks(Account owner, boolean setupPublicNetwork, boolean setupControlNetwork,
Network guestNetwork, boolean isRedundant, DeploymentPlan plan, PublicIp sourceNatIp) throws ConcurrentOperationException,
protected List<Pair<NetworkVO, NicProfile>> createRouterControlNetwork(Account owner, boolean isRedundant,
DeploymentPlan plan) throws ConcurrentOperationException,
InsufficientAddressCapacityException {
//Form networks
List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>(3);
//Form control network
List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>(1);
//1) Control network
if (setupControlNetwork) {
s_logger.debug("Adding nic for Virtual Router in Control network ");
List<NetworkOfferingVO> offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork);
NetworkOfferingVO controlOffering = offerings.get(0);
NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null));
}
//2) Guest network
boolean hasGuestNetwork = false;
if (guestNetwork != null) {
s_logger.debug("Adding nic for Virtual Router in Guest network " + guestNetwork);
String defaultNetworkStartIp = null;
if (guestNetwork.getCidr() != null && !setupPublicNetwork) {
String startIp = _networkMgr.getStartIpAddress(guestNetwork.getId());
if (startIp != null && _ipAddressDao.findByIpAndSourceNetworkId(guestNetwork.getId(), startIp).getAllocatedTime() == null) {
defaultNetworkStartIp = startIp;
} else if (s_logger.isDebugEnabled()){
s_logger.debug("First ip " + startIp + " in network id=" + guestNetwork.getId() +
" is already allocated, can't use it for domain router; will get random ip address from the range");
}
}
NicProfile gatewayNic = new NicProfile(defaultNetworkStartIp);
if (setupPublicNetwork) {
if (isRedundant) {
gatewayNic.setIp4Address(_networkMgr.acquireGuestIpAddress(guestNetwork, null));
} else {
gatewayNic.setIp4Address(guestNetwork.getGateway());
}
gatewayNic.setBroadcastUri(guestNetwork.getBroadcastUri());
gatewayNic.setBroadcastType(guestNetwork.getBroadcastDomainType());
gatewayNic.setIsolationUri(guestNetwork.getBroadcastUri());
gatewayNic.setMode(guestNetwork.getMode());
String gatewayCidr = guestNetwork.getCidr();
gatewayNic.setNetmask(NetUtils.getCidrNetmask(gatewayCidr));
} else {
gatewayNic.setDefaultNic(true);
}
networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, gatewayNic));
hasGuestNetwork = true;
}
//3) Public network
if (setupPublicNetwork) {
s_logger.debug("Adding nic for Virtual Router in Public network ");
//if source nat service is supported by the network, get the source nat ip address
NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
defaultNic.setIp4Address(sourceNatIp.getAddress().addr());
defaultNic.setGateway(sourceNatIp.getGateway());
defaultNic.setNetmask(sourceNatIp.getNetmask());
defaultNic.setMacAddress(sourceNatIp.getMacAddress());
defaultNic.setBroadcastType(BroadcastDomainType.Vlan);
defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(sourceNatIp.getVlanTag()));
defaultNic.setIsolationUri(IsolationType.Vlan.toUri(sourceNatIp.getVlanTag()));
if (hasGuestNetwork) {
defaultNic.setDeviceId(2);
}
NetworkOfferingVO publicOffering = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemPublicNetwork).get(0);
List<NetworkVO> publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false);
networks.add(new Pair<NetworkVO, NicProfile>(publicNetworks.get(0), defaultNic));
}
List<NetworkOfferingVO> offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork);
NetworkOfferingVO controlOffering = offerings.get(0);
NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
s_logger.debug("Adding nic for Virtual Router in Control network ");
networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null));
return networks;
}
@ -1543,7 +1490,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Map<Param, Object> params, boolean isRedundant) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
List<DomainRouterVO> routers = findOrDeployVirtualRouterInGuestNetwork(guestNetwork, dest, owner, isRedundant, params);
List<DomainRouterVO> routers = findOrDeployVirtualRouterInGuestNetwork
(guestNetwork, dest, owner, isRedundant, params);
return startRouters(params, routers);
}
@ -1581,8 +1529,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
public boolean finalizeVirtualMachineProfile(VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest,
ReservationContext context) {
boolean dnsProvided = true;
boolean dhcpProvided = true;
DataCenterVO dc = _dcDao.findById(dest.getDataCenter().getId());
_dcDao.loadDetails(dc);
@ -1591,7 +1537,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Map<String, String> details = _vmDetailsDao.findDetails(router.getId());
router.setDetails(details);
//2) Prepare boot loader elements related with Public/Control networks
//2) Prepare boot loader elements related with Control network
StringBuilder buf = profile.getBootArgsBuilder();
buf.append(" template=domP");
@ -1604,7 +1550,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
NicProfile controlNic = null;
String defaultDns1 = null;
String defaultDns2 = null;
boolean publicNetwork = false;
for (NicProfile nic : profile.getNics()) {
int deviceId = nic.getDeviceId();
@ -1641,13 +1586,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
buf.append(" localgw=").append(dest.getPod().getGateway());
}
}
} else if (nic.getTrafficType() == TrafficType.Guest) {
dnsProvided = _networkMgr.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dns, Provider.VirtualRouter);
dhcpProvided = _networkMgr.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dhcp, Provider.VirtualRouter);
//build bootloader parameter for the guest
buf.append(createGuestBootLoadArgs(nic, defaultDns1, defaultDns2, router));
} else if (nic.getTrafficType() == TrafficType.Public) {
publicNetwork = true;
}
}
@ -1663,14 +1601,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
String rpFilter = " ";
String type = null;
if (!publicNetwork) {
type = "dhcpsrvr";
} else {
type = "router";
if (_disable_rp_filter) {
rpFilter=" disable_rp_filter=true";
}
String type = "router";
if (_disable_rp_filter) {
rpFilter=" disable_rp_filter=true";
}
buf.append(" type=" + type + rpFilter);
@ -1684,26 +1617,23 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
buf.append(" extra_pubnics=" + _routerExtraPublicNics);
}
/* If virtual router didn't provide DNS service but provide DHCP service, we need to override the DHCP response
* to return DNS server rather than
* virtual router itself. */
if (dnsProvided || dhcpProvided) {
if (defaultDns1 != null) {
buf.append(" dns1=").append(defaultDns1);
if (defaultDns2 != null) {
buf.append(" dns2=").append(defaultDns2);
}
}
if (defaultDns2 != null) {
buf.append(" dns2=").append(defaultDns2);
}
boolean useExtDns = !dnsProvided;
/* For backward compatibility */
String use_external_dns = _configDao.getValue(Config.UseExternalDnsServers.key());
if (use_external_dns != null && use_external_dns.equals("true")) {
useExtDns = true;
}
boolean useExtDns = false;
/* For backward compatibility */
String use_external_dns = _configDao.getValue(Config.UseExternalDnsServers.key());
if (use_external_dns != null && use_external_dns.equals("true")) {
useExtDns = true;
}
if (useExtDns) {
buf.append(" useextdns=true");
}
if (useExtDns) {
buf.append(" useextdns=true");
}
if (s_logger.isDebugEnabled()) {
@ -1712,66 +1642,28 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return true;
}
protected StringBuilder createGuestBootLoadArgs(NicProfile guestNic, String defaultDns1,
String defaultDns2, DomainRouterVO router) {
long guestNetworkId = guestNic.getNetworkId();
NetworkVO guestNetwork = _networkDao.findById(guestNetworkId);
protected String getGuestDhcpRange(NicProfile guestNic, Network guestNetwork, DataCenter dc) {
String dhcpRange = null;
DataCenterVO dc = _dcDao.findById(guestNetwork.getDataCenterId());
StringBuilder buf = new StringBuilder();
boolean isRedundant = router.getIsRedundantRouter();
if (isRedundant) {
buf.append(" redundant_router=1");
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(guestNetwork.getId(), Role.VIRTUAL_ROUTER);
try {
int priority = getUpdatedPriority(guestNetwork, routers, router);
router.setPriority(priority);
} catch (InsufficientVirtualNetworkCapcityException e) {
s_logger.error("Failed to get update priority!", e);
throw new CloudRuntimeException("Failed to get update priority!");
}
Network net = _networkMgr.getNetwork(guestNic.getNetworkId());
buf.append(" guestgw=").append(net.getGateway());
String brd = NetUtils.long2Ip(NetUtils.ip2Long(guestNic.getIp4Address()) | ~NetUtils.ip2Long(guestNic.getNetmask()));
buf.append(" guestbrd=").append(brd);
buf.append(" guestcidrsize=").append(NetUtils.getCidrSize(guestNic.getNetmask()));
buf.append(" router_pr=").append(router.getPriority());
}
//setup network domain
String domain = guestNetwork.getNetworkDomain();
if (domain != null) {
buf.append(" domain=" + domain);
}
//setup dhcp range
if (dc.getNetworkType() == NetworkType.Basic) {
if (guestNic.isDefaultNic()) {
long cidrSize = NetUtils.getCidrSize(guestNic.getNetmask());
String cidr = NetUtils.getCidrSubNet(guestNic.getGateway(), cidrSize);
if (cidr != null) {
dhcpRange = NetUtils.getIpRangeStartIpFromCidr(cidr, cidrSize);
}
}
long cidrSize = NetUtils.getCidrSize(guestNic.getNetmask());
String cidr = NetUtils.getCidrSubNet(guestNic.getGateway(), cidrSize);
if (cidr != null) {
dhcpRange = NetUtils.getIpRangeStartIpFromCidr(cidr, cidrSize);
}
} else if (dc.getNetworkType() == NetworkType.Advanced) {
String cidr = guestNetwork.getCidr();
if (cidr != null) {
dhcpRange = NetUtils.getDhcpRange(cidr);
}
}
if (dhcpRange != null) {
buf.append(" dhcprange=" + dhcpRange);
}
return buf;
return dhcpRange;
}
@Override
public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException {
public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile,
DeployDestination dest, ReservationContext context) throws ResourceUnavailableException {
DomainRouterVO router = profile.getVirtualMachine();
List<NicProfile> nics = profile.getNics();
@ -1780,8 +1672,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
router.setPublicIpAddress(nic.getIp4Address());
router.setPublicNetmask(nic.getNetmask());
router.setPublicMacAddress(nic.getMacAddress());
} else if (nic.getTrafficType() == TrafficType.Guest) {
router.setGuestIpAddress(nic.getIp4Address());
} else if (nic.getTrafficType() == TrafficType.Control) {
router.setPrivateIpAddress(nic.getIp4Address());
router.setPrivateMacAddress(nic.getMacAddress());
@ -1915,19 +1805,19 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
//Re-apply static nats
s_logger.debug("Found " + staticNats.size() + " static nat(s) to apply as a part of domR " + router + " start.");
if (!staticNats.isEmpty()) {
createApplyStaticNatCommands(staticNats, router, cmds);
createApplyStaticNatCommands(staticNats, router, cmds, guestNetworkId);
}
//Re-apply firewall rules
s_logger.debug("Found " + staticNats.size() + " firewall rule(s) to apply as a part of domR " + router + " start.");
if (!firewallRules.isEmpty()) {
createFirewallRulesCommands(firewallRules, router, cmds);
createFirewallRulesCommands(firewallRules, router, cmds, guestNetworkId);
}
// Re-apply port forwarding rules
s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start.");
if (!pfRules.isEmpty()) {
createApplyPortForwardingRulesCommands(pfRules, router, cmds);
createApplyPortForwardingRulesCommands(pfRules, router, cmds, guestNetworkId);
}
// Re-apply static nat rules
@ -1937,7 +1827,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
for (FirewallRule rule : staticNatFirewallRules) {
staticNatRules.add(_rulesMgr.buildStaticNatRule(rule, false));
}
createApplyStaticNatRulesCommands(staticNatRules, router, cmds);
createApplyStaticNatRulesCommands(staticNatRules, router, cmds, guestNetworkId);
}
// Re-apply vpn rules
@ -1962,7 +1852,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of domR " + router + " start.");
if (!lbRules.isEmpty()) {
createApplyLoadBalancingRulesCommands(lbRules, router, cmds);
createApplyLoadBalancingRulesCommands(lbRules, router, cmds, guestNetworkId);
}
}
@ -2111,7 +2001,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
RemoteAccessVpnCfgCommand removeVpnCmd = new RemoteAccessVpnCfgCommand(false, ip.getAddress().addr(),
vpn.getLocalIp(), vpn.getIpRange(), vpn.getIpsecPresharedKey());
removeVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
removeVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
removeVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(network.getId(), router.getId()));
removeVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
@ -2284,7 +2174,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(router.getAccountId()));
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(network.getId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2443,7 +2333,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
IpAssocCommand cmd = new IpAssocCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(ipAddrList.get(0).getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2452,7 +2342,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
}
private void createApplyPortForwardingRulesCommands(List<? extends PortForwardingRule> rules, VirtualRouter router, Commands cmds) {
private void createApplyPortForwardingRulesCommands(List<? extends PortForwardingRule> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
List<PortForwardingRuleTO> rulesTO = null;
if (rules != null) {
rulesTO = new ArrayList<PortForwardingRuleTO>();
@ -2465,7 +2355,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2473,7 +2363,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmds.addCommand(cmd);
}
private void createApplyStaticNatRulesCommands(List<? extends StaticNatRule> rules, VirtualRouter router, Commands cmds) {
private void createApplyStaticNatRulesCommands(List<? extends StaticNatRule> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
List<StaticNatRuleTO> rulesTO = null;
if (rules != null) {
rulesTO = new ArrayList<StaticNatRuleTO>();
@ -2486,14 +2376,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
private void createApplyLoadBalancingRulesCommands(List<LoadBalancingRule> rules, VirtualRouter router, Commands cmds) {
private void createApplyLoadBalancingRulesCommands(List<LoadBalancingRule> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
int i = 0;
@ -2516,7 +2406,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
RouterPublicIp = domr.getPublicIpAddress();
}
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs,RouterPublicIp, router.getGuestIpAddress(),router.getPrivateIpAddress());
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs,RouterPublicIp, getRouterIpInNetwork(guestNetworkId, router.getId()),router.getPrivateIpAddress());
cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
@ -2525,7 +2415,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2547,7 +2437,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers);
addUsersCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
addUsersCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
addUsersCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(vpn.getNetworkId(), router.getId()));
addUsersCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId());
@ -2555,7 +2445,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
RemoteAccessVpnCfgCommand startVpnCmd = new RemoteAccessVpnCfgCommand(true, ip.getAddress().addr(),
vpn.getLocalIp(), vpn.getIpRange(), vpn.getIpsecPresharedKey());
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(vpn.getNetworkId(), router.getId()));
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
startVpnCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2573,7 +2463,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
final String encodedPassword = PasswordGenerator.rot13(password);
SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), profile.getVirtualMachine().getHostName());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(nic.getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2587,7 +2477,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
String zoneName = _dcDao.findById(router.getDataCenterIdToDeployIn()).getName();
cmds.addCommand("vmdata",
generateVmDataCommand(router, nic.getIp4Address(), vm.getUserData(), serviceOffering, zoneName, nic.getIp4Address(),
vm.getHostName(), vm.getInstanceName(), vm.getId(), publicKey));
vm.getHostName(), vm.getInstanceName(), vm.getId(), publicKey, nic.getNetworkId()));
}
@ -2627,7 +2517,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(nic.getNetworkId(), router.getId()));
dhcpCommand.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("dhcp", dhcpCommand);
@ -2652,7 +2542,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
}
private boolean sendCommandsToRouter(final VirtualRouter router, Commands cmds) throws AgentUnavailableException {
protected boolean sendCommandsToRouter(final VirtualRouter router, Commands cmds) throws AgentUnavailableException {
Answer[] answers = null;
try {
answers = _agentMgr.send(router.getHostId(), cmds);
@ -2768,13 +2658,13 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList,policyList);
lbRules.add(loadBalancing);
}
return sendLBRules(router, lbRules);
return sendLBRules(router, lbRules, network.getId());
} else if (rules.get(0).getPurpose() == Purpose.PortForwarding) {
return sendPortForwardingRules(router, (List<PortForwardingRule>) rules);
return sendPortForwardingRules(router, (List<PortForwardingRule>) rules, network.getId());
} else if (rules.get(0).getPurpose() == Purpose.StaticNat) {
return sendStaticNatRules(router, (List<StaticNatRule>) rules);
return sendStaticNatRules(router, (List<StaticNatRule>) rules, network.getId());
} else if (rules.get(0).getPurpose() == Purpose.Firewall) {
return sendFirewallRules(router, (List<FirewallRule>) rules);
return sendFirewallRules(router, (List<FirewallRule>) rules, network.getId());
} else {
s_logger.warn("Unable to apply rules of purpose: " + rules.get(0).getPurpose());
return false;
@ -2783,21 +2673,21 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
});
}
protected boolean sendLBRules(VirtualRouter router, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
protected boolean sendLBRules(VirtualRouter router, List<LoadBalancingRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyLoadBalancingRulesCommands(rules, router, cmds);
createApplyLoadBalancingRulesCommands(rules, router, cmds, guestNetworkId);
return sendCommandsToRouter(router, cmds);
}
protected boolean sendPortForwardingRules(VirtualRouter router, List<PortForwardingRule> rules) throws ResourceUnavailableException {
protected boolean sendPortForwardingRules(VirtualRouter router, List<PortForwardingRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyPortForwardingRulesCommands(rules, router, cmds);
createApplyPortForwardingRulesCommands(rules, router, cmds, guestNetworkId);
return sendCommandsToRouter(router, cmds);
}
protected boolean sendStaticNatRules(VirtualRouter router, List<StaticNatRule> rules) throws ResourceUnavailableException {
protected boolean sendStaticNatRules(VirtualRouter router, List<StaticNatRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyStaticNatRulesCommands(rules, router, cmds);
createApplyStaticNatRulesCommands(rules, router, cmds, guestNetworkId);
return sendCommandsToRouter(router, cmds);
}
@ -2811,7 +2701,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return vrs;
}
private void createFirewallRulesCommands(List<? extends FirewallRule> rules, VirtualRouter router, Commands cmds) {
private void createFirewallRulesCommands(List<? extends FirewallRule> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
List<FirewallRuleTO> rulesTO = null;
if (rules != null) {
rulesTO = new ArrayList<FirewallRuleTO>();
@ -2824,7 +2714,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -2832,9 +2722,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
protected boolean sendFirewallRules(VirtualRouter router, List<FirewallRule> rules) throws ResourceUnavailableException {
protected boolean sendFirewallRules(VirtualRouter router, List<FirewallRule> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createFirewallRulesCommands(rules, router, cmds);
createFirewallRulesCommands(rules, router, cmds, guestNetworkId);
return sendCommandsToRouter(router, cmds);
}
@ -2942,19 +2832,19 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return applyRules(network, routers, "static nat rules", false, null, false, new RuleApplier() {
@Override
public boolean execute(Network network, VirtualRouter router) throws ResourceUnavailableException {
return applyStaticNat(router, rules);
return applyStaticNat(router, rules, network.getId());
}
});
}
protected boolean applyStaticNat(VirtualRouter router, List<? extends StaticNat> rules) throws ResourceUnavailableException {
protected boolean applyStaticNat(VirtualRouter router, List<? extends StaticNat> rules, long guestNetworkId) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyStaticNatCommands(rules, router, cmds);
createApplyStaticNatCommands(rules, router, cmds, guestNetworkId);
return sendCommandsToRouter(router, cmds);
}
private void createApplyStaticNatCommands(List<? extends StaticNat> rules, VirtualRouter router, Commands cmds) {
private void createApplyStaticNatCommands(List<? extends StaticNat> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
List<StaticNatRuleTO> rulesTO = null;
if (rules != null) {
rulesTO = new ArrayList<StaticNatRuleTO>();
@ -2968,7 +2858,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, router.getGuestIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
@ -3026,6 +2916,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return false;
}
@ -3035,7 +2926,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return false;
}
private String getRouterControlIp(long routerId) {
protected String getRouterControlIp(long routerId) {
String routerControlIpAddress = null;
List<NicVO> nics = _nicDao.listByVmId(routerId);
for (NicVO n : nics) {
@ -3054,19 +2945,190 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return routerControlIpAddress;
}
@Override
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
//not supported
throw new UnsupportedOperationException("Plug nic is not supported for vm of type " + vm.getType());
protected String getRouterIpInNetwork(long networkId, long instanceId) {
return _nicDao.getIpAddress(networkId, instanceId);
}
@Override
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
boolean result = true;
//FIXME - Anthony, here I send plug nic command on xen side
try {
PlugNicCommand plugNicCmd = new PlugNicCommand(vm, nic);
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand("plugnic", plugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class);
if (!(plugNicAnswer != null && plugNicAnswer.getResult())) {
s_logger.warn("Unable to plug nic for vm " + vm.getHostName());
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to plug nic for router " + vm.getHostName() + " in network " + network,
dest.getHost().getId(), e);
}
return result;
}
@Override
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException {
//not supported
throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
//FIXME - Anthony, add unplug nic agent command on xen side
boolean result = true;
DomainRouterVO router = _routerDao.findById(vm.getId());
try {
UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(vm, nic);
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand("unplugnic", unplugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class);
if (!(unplugNicAnswer != null && unplugNicAnswer.getResult())) {
s_logger.warn("Unable to unplug nic from router " + router);
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network,
dest.getHost().getId(), e);
}
return result;
}
protected boolean setupGuestNetwork(Network network, VirtualRouter router, boolean add, boolean isRedundant,
NicProfile guestNic)
throws ConcurrentOperationException, ResourceUnavailableException{
String networkDomain = network.getNetworkDomain();
String dhcpRange = getGuestDhcpRange(guestNic, network, _configMgr.getZone(network.getDataCenterId()));
//FIXME - Anthony, add setup guest network command logic on Xen side
boolean result = true;
long guestVlanTag = Long.parseLong(network.getBroadcastUri().getHost());
String brd = NetUtils.long2Ip(NetUtils.ip2Long(guestNic.getIp4Address()) | ~NetUtils.ip2Long(guestNic.getNetmask()));
Integer priority = null;
if (isRedundant) {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
try {
getUpdatedPriority(network, routers, _routerDao.findById(router.getId()));
} catch (InsufficientVirtualNetworkCapcityException e) {
s_logger.error("Failed to get update priority!", e);
throw new CloudRuntimeException("Failed to get update priority!");
}
}
String defaultDns1 = null;
String defaultDns2 = null;
boolean dnsProvided = _networkMgr.isProviderSupportServiceInNetwork(guestNic.getNetworkId(), Service.Dns, Provider.VirtualRouter);
boolean dhcpProvided = _networkMgr.isProviderSupportServiceInNetwork(guestNic.getNetworkId(), Service.Dhcp, Provider.VirtualRouter);
if (guestNic.isDefaultNic() && (dnsProvided || dhcpProvided)) {
defaultDns1 = guestNic.getDns1();
defaultDns2 = guestNic.getDns2();
}
SetupGuestNetworkCommand setupCmd = new SetupGuestNetworkCommand(dhcpRange, networkDomain, isRedundant, priority,
defaultDns1, defaultDns2, add);
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(network.getId(), router.getId()));
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, network.getGateway());
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_BRIDGE, brd);
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand("setupguestnetwork", setupCmd);
sendCommandsToRouter(router, cmds);
SetupGuestNetworkAnswer setupAnswer = cmds.getAnswer(SetupGuestNetworkAnswer.class);
String setup = add ? "set" : "unset";
if (!(setupAnswer != null && setupAnswer.getResult())) {
s_logger.warn("Unable to " + setup + " guest network on router " + router);
result = false;
}
return result;
}
@Override
public boolean addRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
//Check if router is already a part of the network
if (_networkMgr.isVmPartOfNetwork(router.getId(), network.getId())) {
s_logger.debug("Router " + router + " is already part of the network " + network);
return true;
}
//Add router to network
boolean result = false;
try {
DomainRouterVO routerVO = _routerDao.findById(router.getId());
s_logger.debug("Plugging nic for vpc virtual router " + router + " in network " + network);
_routerDao.addRouterToGuestNetwork(routerVO, network);
NicProfile guestNic = _itMgr.addVmToNetwork(router, network);
//setup guest network
if (guestNic != null) {
result = setupGuestNetwork(network, router, true, isRedundant, guestNic);
} else {
s_logger.warn("Failed to add router " + router + " to guest network " + network);
}
} catch (Exception ex) {
s_logger.warn("Failed to add router " + router + " to network " + network);
} finally {
if (!result) {
s_logger.debug("Removing the router " + router + " from network " + network + " as a part of cleanup");
if (removeRouterFromGuestNetwork(router, network, isRedundant)) {
s_logger.debug("Removed the router " + router + " from network " + network + " as a part of cleanup");
} else {
s_logger.warn("Failed to remove the router " + router + " from network " + network + " as a part of cleanup");
}
}
}
return result;
}
@Override
public boolean removeRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant)
throws ConcurrentOperationException, ResourceUnavailableException {
//Check if router is a part of the network
if (!_networkMgr.isVmPartOfNetwork(router.getId(), network.getId())) {
s_logger.debug("Router " + router + " is not a part of the network " + network);
return true;
}
boolean result = setupGuestNetwork(network, router, false, isRedundant, _networkMgr.getNicProfile(router, network.getId()));
if (!result) {
s_logger.warn("Failed to reset guest network config " + network + " on router " + router);
return false;
}
result = result && _itMgr.removeVmFromNetwork(router, network);
if (result) {
if (result) {
s_logger.debug("Removing router " + router + " from network " + network);
_routerDao.removeRouterFromNetwork(router.getId(), network.getId());
}
}
return result;
}
}

View File

@ -20,7 +20,6 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcVirtualNetworkApplianceService;
import com.cloud.user.Account;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.VirtualMachineProfile.Param;
@ -28,7 +27,7 @@ import com.cloud.vm.VirtualMachineProfile.Param;
/**
* @author Alena Prokharchyk
*/
public interface VpcVirtualNetworkApplianceManager extends VirtualNetworkApplianceManager, VpcVirtualNetworkApplianceService{
public interface VpcVirtualNetworkApplianceManager extends VirtualNetworkApplianceManager{
/**
* @param vpc

View File

@ -19,15 +19,12 @@ import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.NetworkService;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.VirtualRouterProvider;
@ -35,25 +32,21 @@ import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcVirtualNetworkApplianceService;
import com.cloud.network.vpc.Dao.VpcDao;
import com.cloud.network.vpc.Dao.VpcOfferingDao;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachineProfile.Param;
/**
* @author Alena Prokharchyk
*/
@Local(value = { VpcVirtualNetworkApplianceManager.class, VpcVirtualNetworkApplianceService.class,})
public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplianceManagerImpl implements
VpcVirtualNetworkApplianceManager{
@Local(value = {VpcVirtualNetworkApplianceManager.class})
public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplianceManagerImpl implements VpcVirtualNetworkApplianceManager{
private static final Logger s_logger = Logger.getLogger(VpcVirtualNetworkApplianceManagerImpl.class);
@Inject
@ -103,15 +96,19 @@ VpcVirtualNetworkApplianceManager{
//3) Deploy Virtual Router
try {
//FIXME - remove hardcoded provider type when decide if we want cross physical networks vpcs
List<? extends PhysicalNetwork> pNtwks = _pNtwkDao.listByZone(vpc.getZoneId());
VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(pNtwks.get(0).getId(),
VirtualRouterProviderType.VirtualRouter);
VirtualRouterProvider vpcVrProvider = null;
for (PhysicalNetwork pNtwk : pNtwks) {
vpcVrProvider = _vrProviderDao.findByNspIdAndType(pNtwk.getId(),
VirtualRouterProviderType.VPCVirtualRouter);
if (vpcVrProvider != null) {
break;
}
}
PublicIp sourceNatIp = _networkMgr.assignSourceNatIpAddressToVpc(owner, vpc);
DomainRouterVO router = deployRouter(owner, dest, plan, params, true, true, null, false,
vrProvider, offeringId, sourceNatIp, vpc.getId());
DomainRouterVO router = deployRouter(owner, dest, plan, params, false, vpcVrProvider, offeringId,
vpc.getId());
routers.add(router);
} finally {
@ -131,93 +128,4 @@ VpcVirtualNetworkApplianceManager{
return new Pair<DeploymentPlan, List<DomainRouterVO>>(plan, routers);
}
@Override
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
String networkDomain = network.getNetworkDomain();
String cidr = network.getCidr();
String dhcpRange = null;
if (cidr != null) {
dhcpRange = NetUtils.getDhcpRange(cidr);
}
boolean result = true;
//add router to network
DomainRouterVO router = _routerDao.findById(vm.getId());
s_logger.debug("Adding router " + router + " to network " + network);
_routerDao.addRouterToNetwork(router, network);
//FIXME - Anthony, here I send plug nic command
// try {
// Map<PlugNicCommand.Param, String> params = new HashMap<PlugNicCommand.Param, String>();
// params.put(PlugNicCommand.Param.NetworkDomain, networkDomain);
// params.put(PlugNicCommand.Param.DhcpRange, dhcpRange);
//
// PlugNicCommand plugNicCmd = new PlugNicCommand(vm, nic, params);
//
// Commands cmds = new Commands(OnError.Stop);
// cmds.addCommand("plugnic", plugNicCmd);
// _agentMgr.send(dest.getHost().getId(), cmds);
//
// PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class);
// if (!(plugNicAnswer != null && plugNicAnswer.getResult())) {
// s_logger.warn("Unable to plug nic for vm " + vm.getHostName());
// result = false;
// }
//
// } catch (OperationTimedoutException e) {
// throw new AgentUnavailableException("Unable to plug nic for vm " + vm.getHostName() + " in network " + network,
// dest.getHost().getId(), e);
// }
return result;
}
@Override
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException {
//FIXME - Anthony, add unplug nic agent command
boolean result = true;
// try {
// UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(vm, nic);
// Commands cmds = new Commands(OnError.Stop);
// cmds.addCommand("unplugnic", unplugNicCmd);
// _agentMgr.send(dest.getHost().getId(), cmds);
//
// UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class);
// if (!(unplugNicAnswer != null && unplugNicAnswer.getResult())) {
// s_logger.warn("Unable to unplug nic from vm " + vm.getHostName());
// result = false;
// }
//
// } catch (OperationTimedoutException e) {
// throw new AgentUnavailableException("Unable to unplug nic from vm " + vm.getHostName() + " from network " + network,
// dest.getHost().getId(), e);
// }
//
if (result) {
s_logger.debug("Removing router " + vm.getHostName() + " from network " + network);
_routerDao.removeRouterFromNetwork(vm.getId(), network.getId());
}
return result;
}
@Override
public boolean addVmToNetwork(VirtualRouter router, Network network) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
return _itMgr.addVmToNetwork(router, network);
}
@Override
public boolean removeVmFromNetwork(VirtualRouter router, Network network)
throws ConcurrentOperationException, ResourceUnavailableException {
return _itMgr.removeVmFromNetwork(router, network);
}
}

View File

@ -0,0 +1,62 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc.Dao;
import java.util.List;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.utils.db.GenericDao;
/**
* @author Alena Prokharchyk
*/
public interface PrivateIpDao extends GenericDao<PrivateIpVO, Long>{
/**
* @param dcId
* @param networkId
* @return
*/
PrivateIpVO allocateIpAddress(long dcId, long networkId);
/**
* @param ipAddress
* @param networkId
*/
void releaseIpAddress(String ipAddress, long networkId);
/**
* @param networkId
* @param ip4Address
* @return
*/
PrivateIpVO findByIpAndSourceNetworkId(long networkId, String ip4Address);
/**
* @param networkId
* @return
*/
List<PrivateIpVO> listByNetworkId(long networkId);
/**
* @param ntwkId
* @return
*/
int countAllocatedByNetworkId(long ntwkId);
/**
* @param networkId
*/
void deleteByNetworkId(long networkId);
}

View File

@ -0,0 +1,129 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc.Dao;
import java.util.Date;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
/**
* @author Alena Prokharchyk
*/
@Local(value = PrivateIpDao.class)
@DB(txn = false)
public class PrivateIpDaoImpl extends GenericDaoBase<PrivateIpVO, Long> implements PrivateIpDao {
private static final Logger s_logger = Logger.getLogger(PrivateIpDaoImpl.class);
private final SearchBuilder<PrivateIpVO> AllFieldsSearch;
private final GenericSearchBuilder<PrivateIpVO, Integer> CountAllocatedByNetworkId;
protected PrivateIpDaoImpl() {
super();
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("ip", AllFieldsSearch.entity().getIpAddress(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("networkId", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("ipAddress", AllFieldsSearch.entity().getIpAddress(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("taken", AllFieldsSearch.entity().getTakenAt(), SearchCriteria.Op.EQ);
AllFieldsSearch.done();
CountAllocatedByNetworkId = createSearchBuilder(Integer.class);
CountAllocatedByNetworkId.select(null, Func.COUNT, CountAllocatedByNetworkId.entity().getId());
CountAllocatedByNetworkId.and("networkId", CountAllocatedByNetworkId.entity().getNetworkId(), Op.EQ);
CountAllocatedByNetworkId.and("taken", CountAllocatedByNetworkId.entity().getTakenAt(), Op.NNULL);
CountAllocatedByNetworkId.done();
}
@Override
public PrivateIpVO allocateIpAddress(long dcId, long networkId) {
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("networkId", networkId);
sc.setParameters("taken", (Date)null);
Transaction txn = Transaction.currentTxn();
txn.start();
PrivateIpVO vo = lockOneRandomRow(sc, true);
if (vo == null) {
txn.rollback();
return null;
}
vo.setTakenAt(new Date());
update(vo.getId(), vo);
txn.commit();
return vo;
}
@Override
public void releaseIpAddress(String ipAddress, long networkId) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing private ip address: " + ipAddress + " network id " + networkId);
}
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("ip", ipAddress);
sc.setParameters("networkId", networkId);
PrivateIpVO vo = createForUpdate();
vo.setTakenAt(null);
update(vo, sc);
}
/* (non-Javadoc)
* @see com.cloud.network.vpc.Dao.PrivateIpDao#findByIpAndSourceNetworkId(long, java.lang.String)
*/
@Override
public PrivateIpVO findByIpAndSourceNetworkId(long networkId, String ip4Address) {
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("ip", ip4Address);
sc.setParameters("networkId", networkId);
return findOneBy(sc);
}
@Override
public List<PrivateIpVO> listByNetworkId(long networkId) {
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("networkId", networkId);
return listBy(sc);
}
@Override
public int countAllocatedByNetworkId(long ntwkId) {
SearchCriteria<Integer> sc = CountAllocatedByNetworkId.create();
sc.setParameters("networkId", ntwkId);
List<Integer> results = customSearch(sc, null);
return results.get(0);
}
@Override
public void deleteByNetworkId(long networkId) {
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("networkId", networkId);
remove(sc);
}
}

View File

@ -0,0 +1,23 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc.Dao;
import com.cloud.network.vpc.VpcGatewayVO;
import com.cloud.utils.db.GenericDao;
/**
* @author Alena Prokharchyk
*/
public interface VpcGatewayDao extends GenericDao<VpcGatewayVO, Long>{
}

View File

@ -0,0 +1,76 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Alena Prokharchyk
*/
@Entity
@Table(name="private_ip_address")
public class PrivateIpVO {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
long id;
@Column(name="ip_address", updatable=false, nullable=false)
String ipAddress;
@Column(name="taken")
@Temporal(value=TemporalType.TIMESTAMP)
private Date takenAt;
@Column(name="network_id", updatable=false, nullable=false)
private long networkId;
public PrivateIpVO() {
}
public PrivateIpVO(String ipAddress, long networkId) {
this.ipAddress = ipAddress;
this.networkId = networkId;
}
public void setTakenAt(Date takenDate) {
this.takenAt = takenDate;
}
public String getIpAddress() {
return ipAddress;
}
public long getNetworkId() {
return networkId;
}
public Date getTakenAt() {
return takenAt;
}
public long getId() {
return id;
}
}

View File

@ -0,0 +1,22 @@
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.vpc;
/**
* @author Alena Prokharchyk
*/
public class VpcGatewayVO {
public VpcGatewayVO() {
}
}

View File

@ -307,6 +307,12 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges);
this.state = State.Enabled;
}
public NetworkOfferingVO(String name, Network.GuestType guestType) {
this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional,
null, Network.GuestType.Isolated, true, false);
this.state = State.Enabled;
}
@Override
public String toString() {

View File

@ -61,6 +61,7 @@ import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.Network.State;
@ -94,7 +95,6 @@ import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
@ -874,16 +874,22 @@ public class ConfigurationServerImpl implements ConfigurationServer {
@DB
protected void createDefaultNetworkOfferings() {
NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public, true);
NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork,
TrafficType.Public, true);
publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering);
NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, TrafficType.Management, false);
NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork,
TrafficType.Management, false);
managementNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(managementNetworkOffering);
NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, TrafficType.Control, false);
NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork,
TrafficType.Control, false);
controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true);
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork,
TrafficType.Storage, true);
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
NetworkOfferingVO privateGatewayNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering, GuestType.Isolated);
privateGatewayNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(privateGatewayNetworkOffering);
// populate providers
//populate providers
Map<Network.Service, Network.Provider> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);

View File

@ -381,7 +381,8 @@ public class PodZoneConfig {
String defaultXenStorageNetworkLabel = getDefaultXenNetworkLabel(TrafficType.Storage);
String defaultXenGuestNetworkLabel = getDefaultXenNetworkLabel(TrafficType.Guest);
String insertTraficType = "INSERT INTO `cloud`.`physical_network_traffic_types` (physical_network_id, traffic_type, xen_network_label) VALUES ( ?, ?, ?)";
String insertTraficType = "INSERT INTO `cloud`.`physical_network_traffic_types` " +
"(physical_network_id, traffic_type, xen_network_label) VALUES ( ?, ?, ?)";
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertTraficType);

View File

@ -425,7 +425,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork), _networkMgr.getNetworkTag(template.getHypervisorType(), defaultNetwork));
NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null,
_networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork), _networkMgr.getNetworkTag(template.getHypervisorType(), defaultNetwork));
VirtualMachineProfile<VMInstanceVO> vmProfile = new VirtualMachineProfileImpl<VMInstanceVO>(vmInstance);
vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password);

View File

@ -142,7 +142,7 @@ public interface VirtualMachineManager extends Manager {
* @throws ResourceUnavailableException
* @throws InsufficientCapacityException
*/
boolean addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException,
NicProfile addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException;
/**

View File

@ -2432,7 +2432,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene
@Override
@DB
public boolean addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException,
public NicProfile addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
@ -2476,10 +2476,10 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene
if (vmGuru.plugNic(network, nicTO, vmTO, context, dest)) {
s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now");
return true;
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
return false;
return null;
}
}
@ -2501,18 +2501,16 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene
//1) Release the nic
NicProfile nic = _networkMgr.releaseNic(vmProfile, networkVO);
//2) TODO - unplug the nic
//2) Convert vmProfile to vmTO
VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vmVO);
//3) Convert vmProfile to vmTO
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
//4) Convert nicProfile to NicTO
//3) Convert nicProfile to NicTO
NicTO nicTO = hvGuru.toNicTO(nic);
boolean result = vmGuru.unplugNic(network, nicTO, vmTO, context, dest);
//5) Unplug the nic
//4) Unplug the nic
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network );
} else {

View File

@ -116,11 +116,12 @@ public interface DomainRouterDao extends GenericDao<DomainRouterVO, Long> {
* @param routerId
* @param guestNetwork
*/
void addRouterToNetwork(DomainRouterVO router, Network guestNetwork);
void addRouterToGuestNetwork(DomainRouterVO router, Network guestNetwork);
/**
* @param routerId
* @param guestNetworkId
*/
void removeRouterFromNetwork(long routerId, long guestNetworkId);
}

View File

@ -264,7 +264,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase<DomainRouterVO, Long> im
if (guestNetworks != null && !guestNetworks.isEmpty()) {
// 2) add router to the network
for (Network guestNetwork : guestNetworks) {
addRouterToNetwork(router, guestNetwork);
addRouterToGuestNetwork(router, guestNetwork);
}
}
@ -274,7 +274,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase<DomainRouterVO, Long> im
@Override
@DB
public void addRouterToNetwork(DomainRouterVO router, Network guestNetwork) {
public void addRouterToGuestNetwork(DomainRouterVO router, Network guestNetwork) {
Transaction txn = Transaction.currentTxn();
txn.start();
//1) add router to network
@ -309,5 +309,5 @@ public class DomainRouterDaoImpl extends GenericDaoBase<DomainRouterVO, Long> im
sc.setParameters("role", Role.VIRTUAL_ROUTER);
return listBy(sc);
}
}

View File

@ -37,4 +37,13 @@ public interface NicDao extends GenericDao<NicVO, Long> {
NicVO findByIp4AddressAndNetworkId(String ip4Address, long networkId);
NicVO findDefaultNicForVM(long instanceId);
/**
* @param networkId
* @param instanceId
* @return
*/
NicVO findNonReleasedByInstanceIdAndNetworkId(long networkId, long instanceId);
String getIpAddress(long networkId, long instanceId);
}

View File

@ -22,6 +22,8 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.vm.Nic.State;
import com.cloud.vm.Nic;
import com.cloud.vm.NicVO;
import com.cloud.vm.VirtualMachine;
@ -29,6 +31,7 @@ import com.cloud.vm.VirtualMachine;
public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
private final SearchBuilder<NicVO> AllFieldsSearch;
private final GenericSearchBuilder<NicVO, String> IpSearch;
private final SearchBuilder<NicVO> NonReleasedSearch;
protected NicDaoImpl() {
super();
@ -46,6 +49,12 @@ public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
IpSearch.and("network", IpSearch.entity().getNetworkId(), Op.EQ);
IpSearch.and("address", IpSearch.entity().getIp4Address(), Op.NNULL);
IpSearch.done();
NonReleasedSearch = createSearchBuilder();
NonReleasedSearch.and("instance", NonReleasedSearch.entity().getInstanceId(), Op.EQ);
NonReleasedSearch.and("network", NonReleasedSearch.entity().getNetworkId(), Op.EQ);
NonReleasedSearch.and("state", NonReleasedSearch.entity().getState(), Op.NOTIN);
NonReleasedSearch.done();
}
@Override
@ -123,4 +132,22 @@ public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
sc.setParameters("isDefault", 1);
return findOneBy(sc);
}
@Override
public NicVO findNonReleasedByInstanceIdAndNetworkId(long networkId, long instanceId) {
SearchCriteria<NicVO> sc = NonReleasedSearch.create();
sc.setParameters("network", networkId);
sc.setParameters("instance", instanceId);
sc.setParameters("state", State.Releasing, Nic.State.Deallocating);
return findOneBy(sc);
}
@Override
public String getIpAddress(long networkId, long instanceId) {
SearchCriteria<NicVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId);
sc.setParameters("instance", instanceId);
return findOneBy(sc).getIp4Address();
}
}

View File

@ -240,7 +240,7 @@ public class MockVirtualMachineManagerImpl implements VirtualMachineManager {
* @see com.cloud.vm.VirtualMachineManager#addVmToNetwork(com.cloud.vm.VirtualMachine, com.cloud.network.Network)
*/
@Override
public boolean addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
public NicProfile addVmToNetwork(VirtualMachine vm, Network network) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
// TODO Auto-generated method stub
return false;
}

View File

@ -2201,5 +2201,34 @@ CREATE TABLE `cloud`.`router_network_ref` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`vpc_gateways` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id',
`uuid` varchar(40),
`ip4_address` char(40) COMMENT 'ip4 address of the gateway',
`type` varchar(32) COMMENT 'type of gateway; can be Public/Private/Vpn',
`network_id` bigint unsigned NOT NULL COMMENT 'network id vpc gateway belongs to',
`vpc_id` bigint unsigned NOT NULL COMMENT 'id of the vpc the gateway belongs to',
`zone_id` bigint unsigned NOT NULL COMMENT 'id of the zone the gateway belongs to',
`created` datetime NOT NULL COMMENT 'date created',
`removed` datetime COMMENT 'date removed if not null',
PRIMARY KEY (`id`),
CONSTRAINT `fk_vpc_gateways__network_id` FOREIGN KEY `fk_vpc_gateways__network_id`(`network_id`) REFERENCES `networks`(`id`),
CONSTRAINT `fk_vpc_gateways__vpc_id` FOREIGN KEY `fk_vpc_gateways__vpc_id`(`vpc_id`) REFERENCES `vpc`(`id`),
CONSTRAINT `fk_vpc_gateways__zone_id` FOREIGN KEY `fk_vpc_gateways__zone_id`(`zone_id`) REFERENCES `data_center`(`id`),
CONSTRAINT `uc_vpc_gateways__uuid` UNIQUE (`uuid`),
INDEX `i_vpc_gateways__removed`(`removed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`private_ip_address` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
`ip_address` char(40) NOT NULL COMMENT 'ip address',
`network_id` bigint unsigned NOT NULL COMMENT 'id of the network ip belongs to',
`reservation_id` char(40) COMMENT 'reservation id',
`taken` datetime COMMENT 'Date taken',
PRIMARY KEY (`id`),
CONSTRAINT `fk_private_ip_address__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET foreign_key_checks = 1;

View File

@ -3,7 +3,11 @@
# the following two variables are used by the target "waf dist"
# if you change 'em here, you need to change it also in cloud.spec, add a %changelog entry there, and add an entry in debian/changelog
<<<<<<< HEAD
VERSION = '3.0.3.2012-06-04T23:35:51Z'
=======
VERSION = '3.0.3.2012-06-04T21:10:12Z'
>>>>>>> Support for adding private network
APPNAME = 'cloud'
import shutil,os