use of com.cloud.network.vpc.PrivateIpVO in project cloudstack by apache.
the class VpcVirtualNetworkApplianceManagerImpl method finalizeCommandsOnStart.
@Override
public boolean finalizeCommandsOnStart(final Commands cmds, final VirtualMachineProfile profile) {
final DomainRouterVO domainRouterVO = _routerDao.findById(profile.getId());
Map<String, String> details = new HashMap<String, String>();
if (profile.getHypervisorType() == Hypervisor.HypervisorType.VMware) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(profile);
if (vmTO.getDetails() != null) {
details = vmTO.getDetails();
}
}
final boolean isVpc = domainRouterVO.getVpcId() != null;
if (!isVpc) {
return super.finalizeCommandsOnStart(cmds, profile);
}
if (domainRouterVO.getState() == State.Starting || domainRouterVO.getState() == State.Running) {
// 1) FORM SSH CHECK COMMAND
final NicProfile controlNic = getControlNic(profile);
if (controlNic == null) {
s_logger.error("Control network doesn't exist for the router " + domainRouterVO);
return false;
}
finalizeSshAndVersionAndNetworkUsageOnStart(cmds, profile, domainRouterVO, controlNic);
// 2) FORM PLUG NIC COMMANDS
final List<Pair<Nic, Network>> guestNics = new ArrayList<Pair<Nic, Network>>();
final List<Pair<Nic, Network>> publicNics = new ArrayList<Pair<Nic, Network>>();
final List<Pair<Nic, Network>> privateGatewayNics = new ArrayList<Pair<Nic, Network>>();
final Map<String, String> vlanMacAddress = new HashMap<String, String>();
final List<? extends Nic> routerNics = _nicDao.listByVmIdOrderByDeviceId(profile.getId());
for (final Nic routerNic : routerNics) {
final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
if (network.getTrafficType() == TrafficType.Guest) {
final Pair<Nic, Network> guestNic = new Pair<Nic, Network>(routerNic, network);
if (_networkModel.isPrivateGateway(routerNic.getNetworkId())) {
privateGatewayNics.add(guestNic);
} else {
guestNics.add(guestNic);
}
} else if (network.getTrafficType() == TrafficType.Public) {
final Pair<Nic, Network> publicNic = new Pair<Nic, Network>(routerNic, network);
publicNics.add(publicNic);
final String vlanTag = BroadcastDomainType.getValue(routerNic.getBroadcastUri());
vlanMacAddress.put(vlanTag, routerNic.getMacAddress());
}
}
// Public and Guest networks start from device_id = 1
int deviceId = 1;
final List<Command> usageCmds = new ArrayList<Command>();
// 3) PREPARE PLUG NIC COMMANDS
try {
// add VPC router to public networks
final List<PublicIp> sourceNat = new ArrayList<PublicIp>(1);
for (final Pair<Nic, Network> nicNtwk : publicNics) {
final Nic publicNic = updateNicWithDeviceId(nicNtwk.first().getId(), deviceId);
deviceId++;
final Network publicNtwk = nicNtwk.second();
final IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(publicNtwk.getId(), publicNic.getIPv4Address());
if (userIp.isSourceNat()) {
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
sourceNat.add(publicIp);
if (domainRouterVO.getPublicIpAddress() == null) {
final DomainRouterVO routerVO = _routerDao.findById(domainRouterVO.getId());
routerVO.setPublicIpAddress(publicNic.getIPv4Address());
routerVO.setPublicNetmask(publicNic.getIPv4Netmask());
routerVO.setPublicMacAddress(publicNic.getMacAddress());
_routerDao.update(routerVO.getId(), routerVO);
}
}
final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, publicNic.getNetworkId(), publicNic.getBroadcastUri().toString()), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
cmds.addCommand(plugNicCmd);
final VpcVO vpc = _vpcDao.findById(domainRouterVO.getVpcId());
final NetworkUsageCommand netUsageCmd = new NetworkUsageCommand(domainRouterVO.getPrivateIpAddress(), domainRouterVO.getInstanceName(), true, publicNic.getIPv4Address(), vpc.getCidr());
usageCmds.add(netUsageCmd);
UserStatisticsVO stats = _userStatsDao.findBy(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString());
if (stats == null) {
stats = new UserStatisticsVO(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString(), publicNtwk.getId());
_userStatsDao.persist(stats);
}
}
// create ip assoc for source nat
if (!sourceNat.isEmpty()) {
_commandSetupHelper.createVpcAssociatePublicIPCommands(domainRouterVO, sourceNat, cmds, vlanMacAddress);
}
// add VPC router to private gateway networks
for (final Pair<Nic, Network> nicNtwk : privateGatewayNics) {
final Nic guestNic = updateNicWithDeviceId(nicNtwk.first().getId(), deviceId);
deviceId++;
// plug guest nic
final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
cmds.addCommand(plugNicCmd);
// set private network
final PrivateIpVO ipVO = _privateIpDao.findByIpAndSourceNetworkId(guestNic.getNetworkId(), guestNic.getIPv4Address());
final Network network = _networkDao.findById(guestNic.getNetworkId());
BroadcastDomainType.getValue(network.getBroadcastUri());
final String netmask = NetUtils.getCidrNetmask(network.getCidr());
final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, guestNic.getMacAddress());
final List<PrivateIpAddress> privateIps = new ArrayList<PrivateIpAddress>(1);
privateIps.add(ip);
_commandSetupHelper.createVpcAssociatePrivateIPCommands(domainRouterVO, privateIps, cmds, true);
final Long privateGwAclId = _vpcGatewayDao.getNetworkAclIdForPrivateIp(ipVO.getVpcId(), ipVO.getNetworkId(), ipVO.getIpAddress());
if (privateGwAclId != null) {
// set network acl on private gateway
final List<NetworkACLItemVO> networkACLs = _networkACLItemDao.listByACL(privateGwAclId);
s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + domainRouterVO + " start for private gateway ip = " + ipVO.getIpAddress());
_commandSetupHelper.createNetworkACLsCommands(networkACLs, domainRouterVO, cmds, ipVO.getNetworkId(), true);
}
}
// add VPC router to guest networks
for (final Pair<Nic, Network> nicNtwk : guestNics) {
final Nic guestNic = updateNicWithDeviceId(nicNtwk.first().getId(), deviceId);
deviceId++;
// plug guest nic
final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
cmds.addCommand(plugNicCmd);
// set guest network
final VirtualMachine vm = _vmDao.findById(domainRouterVO.getId());
final NicProfile nicProfile = _networkModel.getNicProfile(vm, guestNic.getNetworkId(), null);
final SetupGuestNetworkCommand setupCmd = _commandSetupHelper.createSetupGuestNetworkCommand(domainRouterVO, true, nicProfile);
cmds.addCommand(setupCmd);
}
} catch (final Exception ex) {
s_logger.warn("Failed to add router " + domainRouterVO + " to network due to exception ", ex);
return false;
}
// 4) RE-APPLY ALL STATIC ROUTE RULES
final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcId(domainRouterVO.getVpcId());
final List<StaticRouteProfile> staticRouteProfiles = new ArrayList<StaticRouteProfile>(routes.size());
final Map<Long, VpcGateway> gatewayMap = new HashMap<Long, VpcGateway>();
for (final StaticRoute route : routes) {
VpcGateway gateway = gatewayMap.get(route.getVpcGatewayId());
if (gateway == null) {
gateway = _entityMgr.findById(VpcGateway.class, route.getVpcGatewayId());
gatewayMap.put(gateway.getId(), gateway);
}
staticRouteProfiles.add(new StaticRouteProfile(route, gateway));
}
s_logger.debug("Found " + staticRouteProfiles.size() + " static routes to apply as a part of vpc route " + domainRouterVO + " start");
if (!staticRouteProfiles.isEmpty()) {
_commandSetupHelper.createStaticRouteCommands(staticRouteProfiles, domainRouterVO, cmds);
}
// 5) RE-APPLY ALL REMOTE ACCESS VPNs
final RemoteAccessVpnVO vpn = _vpnDao.findByAccountAndVpc(domainRouterVO.getAccountId(), domainRouterVO.getVpcId());
if (vpn != null) {
_commandSetupHelper.createApplyVpnCommands(true, vpn, domainRouterVO, cmds);
}
// 6) REPROGRAM GUEST NETWORK
boolean reprogramGuestNtwks = true;
if (profile.getParameter(Param.ReProgramGuestNetworks) != null && (Boolean) profile.getParameter(Param.ReProgramGuestNetworks) == false) {
reprogramGuestNtwks = false;
}
final VirtualRouterProvider vrProvider = _vrProviderDao.findById(domainRouterVO.getElementId());
if (vrProvider == null) {
throw new CloudRuntimeException("Cannot find related virtual router provider of router: " + domainRouterVO.getHostName());
}
final Provider provider = Network.Provider.getProvider(vrProvider.getType().toString());
if (provider == null) {
throw new CloudRuntimeException("Cannot find related provider of virtual router provider: " + vrProvider.getType().toString());
}
if (reprogramGuestNtwks && publicNics.size() > 0) {
finalizeMonitorService(cmds, profile, domainRouterVO, provider, publicNics.get(0).second().getId(), true);
}
for (final Pair<Nic, Network> nicNtwk : guestNics) {
final Nic guestNic = nicNtwk.first();
final long guestNetworkId = guestNic.getNetworkId();
final AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNetworkId, domainRouterVO.getId()));
cmds.addCommand(startCmd);
if (reprogramGuestNtwks) {
finalizeIpAssocForNetwork(cmds, domainRouterVO, provider, guestNetworkId, vlanMacAddress);
finalizeNetworkRulesForNetwork(cmds, domainRouterVO, provider, guestNetworkId);
finalizeMonitorService(cmds, profile, domainRouterVO, provider, guestNetworkId, true);
}
finalizeUserDataAndDhcpOnStart(cmds, domainRouterVO, provider, guestNetworkId);
final AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNetworkId, domainRouterVO.getId()));
cmds.addCommand(finishCmd);
}
// Add network usage commands
cmds.addCommands(usageCmds);
}
return true;
}
use of com.cloud.network.vpc.PrivateIpVO in project cloudstack by apache.
the class VpcVirtualNetworkApplianceManagerImpl method setupVpcPrivateNetwork.
/**
* @param router
* @param add
* @param privateNic
* @return
* @throws ResourceUnavailableException
*/
protected boolean setupVpcPrivateNetwork(final VirtualRouter router, final boolean add, final NicProfile privateNic) throws ResourceUnavailableException {
if (router.getState() == State.Running) {
final PrivateIpVO ipVO = _privateIpDao.findByIpAndSourceNetworkId(privateNic.getNetworkId(), privateNic.getIPv4Address());
final Network network = _networkDao.findById(privateNic.getNetworkId());
final String netmask = NetUtils.getCidrNetmask(network.getCidr());
final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, privateNic.getMacAddress());
final List<PrivateIpAddress> privateIps = new ArrayList<PrivateIpAddress>(1);
privateIps.add(ip);
final Commands cmds = new Commands(Command.OnError.Stop);
_commandSetupHelper.createVpcAssociatePrivateIPCommands(router, privateIps, cmds, add);
try {
if (_nwHelper.sendCommandsToRouter(router, cmds)) {
s_logger.debug("Successfully applied ip association for ip " + ip + " in vpc network " + network);
return true;
} else {
s_logger.warn("Failed to associate ip address " + ip + " in vpc network " + network);
return false;
}
} catch (final Exception ex) {
s_logger.warn("Failed to send " + (add ? "add " : "delete ") + " private network " + network + " commands to rotuer ");
return false;
}
} else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
s_logger.debug("Router " + router.getInstanceName() + " is in " + router.getState() + ", so not sending setup private network command to the backend");
} else {
s_logger.warn("Unable to setup private gateway, virtual router " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to setup Private gateway on the backend," + " virtual router " + router + " is not in the right state", DataCenter.class, router.getDataCenterId());
}
return true;
}
use of com.cloud.network.vpc.PrivateIpVO in project cloudstack by apache.
the class NetworkServiceImpl method createPrivateNetwork.
@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId, final Boolean bypassVlanOverlapCheck) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
final Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offering
NetworkOfferingVO ntwkOff = null;
if (networkOfferingId != null) {
ntwkOff = _networkOfferingDao.findById(networkOfferingId);
}
if (ntwkOff == null) {
ntwkOff = findSystemNetworkOffering(NetworkOffering.SystemPrivateGatewayNetworkOffering);
}
// Validate physical network
final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throwInvalidIdException("Unable to find a physical network" + " having the given id", String.valueOf(physicalNetworkId), "physicalNetworkId");
}
// if end ip is not specified, default it to startIp
if (!NetUtils.isValidIp4(startIp)) {
throw new InvalidParameterValueException("Invalid format for the ip address parameter");
}
if (endIp == null) {
endIp = startIp;
} else if (!NetUtils.isValidIp4(endIp)) {
throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
URI uri = BroadcastDomainType.fromString(broadcastUriString);
final String uriString = uri.toString();
BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
// TODO make a test for any supported scheme
if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
}
final NetworkOfferingVO ntwkOffFinal = ntwkOff;
try {
return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
// lock datacenter as we need to get mac address seq from there
DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
// check if we need to create guest network
Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId, vpcId);
if (privateNetwork == null) {
// create Guest network
privateNetwork = _networkMgr.createPrivateNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, bypassVlanOverlapCheck, owner, pNtwk, vpcId);
if (privateNetwork != null) {
s_logger.debug("Successfully created guest network " + privateNetwork);
} else {
throw new CloudRuntimeException("Creating guest network failed");
}
} else {
s_logger.debug("Private network already exists: " + privateNetwork);
// Do not allow multiple private gateways with same Vlan within a VPC
throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
if (vpcId != null) {
// add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
Long mac = dc.getMacAddress();
Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
_privateIpDao.persist(privateIp);
_dcDao.update(dc.getId(), dc);
}
s_logger.debug("Private network " + privateNetwork + " is created");
return privateNetwork;
}
});
} catch (Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
throw new IllegalStateException(e);
}
}
use of com.cloud.network.vpc.PrivateIpVO in project cloudstack by apache.
the class PrivateNetworkGuru method deallocate.
@Override
public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIPv4Address());
}
PrivateIpVO ip = _privateIpDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIPv4Address());
if (ip != null) {
_privateIpDao.releaseIpAddress(nic.getIPv4Address(), nic.getNetworkId());
}
nic.deallocate();
}
use of com.cloud.network.vpc.PrivateIpVO in project cloudstack by apache.
the class PrivateIpDaoImpl method allocateIpAddress.
@Override
public PrivateIpVO allocateIpAddress(long dcId, long networkId, String requestedIp) {
SearchCriteria<PrivateIpVO> sc = AllFieldsSearch.create();
sc.setParameters("networkId", networkId);
sc.setParameters("taken", (Date) null);
if (requestedIp != null) {
sc.setParameters("ipAddress", requestedIp);
}
TransactionLegacy txn = TransactionLegacy.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;
}
Aggregations