use of com.cloud.network.dao.RemoteAccessVpnVO in project cloudstack by apache.
the class NetworkOrchestrator method cleanupConfigForServicesInNetwork.
@Override
public void cleanupConfigForServicesInNetwork(List<String> services, final Network network) {
long networkId = network.getId();
Account caller = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
long userId = User.UID_SYSTEM;
//remove all PF/Static Nat rules for the network
s_logger.info("Services:" + services + " are no longer supported in network:" + network.getUuid() + " after applying new network offering:" + network.getNetworkOfferingId() + " removing the related configuration");
if (services.contains(Service.StaticNat.getName()) || services.contains(Service.PortForwarding.getName())) {
try {
if (_rulesMgr.revokeAllPFStaticNatRulesForNetwork(networkId, userId, caller)) {
s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId);
} else {
s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup");
}
if (services.contains(Service.StaticNat.getName())) {
//removing static nat configured on ips.
//optimizing the db operations using transaction.
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(network.getId());
for (IPAddressVO ip : ips) {
ip.setOneToOneNat(false);
ip.setAssociatedWithVmId(null);
ip.setVmIp(null);
_ipAddressDao.update(ip.getId(), ip);
}
}
});
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex);
}
}
if (services.contains(Service.SourceNat.getName())) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
List<IPAddressVO> ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true);
//removing static nat configured on ips.
for (IPAddressVO ip : ips) {
ip.setSourceNat(false);
_ipAddressDao.update(ip.getId(), ip);
}
}
});
}
if (services.contains(Service.Lb.getName())) {
//remove all LB rules for the network
if (_lbMgr.removeAllLoadBalanacersForNetwork(networkId, caller, userId)) {
s_logger.debug("Successfully cleaned up load balancing rules for network id=" + networkId);
} else {
s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup");
}
}
if (services.contains(Service.Firewall.getName())) {
//revoke all firewall rules for the network
try {
if (_firewallMgr.revokeAllFirewallRulesForNetwork(networkId, userId, caller)) {
s_logger.debug("Successfully cleaned up firewallRules rules for network id=" + networkId);
} else {
s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup");
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex);
}
}
//do not remove vpn service for vpc networks.
if (services.contains(Service.Vpn.getName()) && network.getVpcId() == null) {
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByAccountAndNetwork(network.getAccountId(), networkId);
try {
_vpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, true);
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup remote access vpn resources of network:" + network.getUuid() + " due to Exception: ", ex);
}
}
}
use of com.cloud.network.dao.RemoteAccessVpnVO 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 Map<String, String> vlanMacAddress = new HashMap<String, String>();
final List<? extends Nic> routerNics = _nicDao.listByVmId(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);
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());
}
}
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 = nicNtwk.first();
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 guest networks
for (final Pair<Nic, Network> nicNtwk : guestNics) {
final Nic guestNic = nicNtwk.first();
// plug guest nic
final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
cmds.addCommand(plugNicCmd);
if (!_networkModel.isPrivateGateway(guestNic.getNetworkId())) {
// 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);
} else {
// 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);
}
}
}
} 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());
}
for (final Pair<Nic, Network> nicNtwk : guestNics) {
final Nic guestNic = nicNtwk.first();
final AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
cmds.addCommand(startCmd);
if (reprogramGuestNtwks) {
finalizeIpAssocForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId(), vlanMacAddress);
finalizeNetworkRulesForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId());
}
finalizeUserDataAndDhcpOnStart(cmds, domainRouterVO, provider, guestNic.getNetworkId());
final AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
cmds.addCommand(finishCmd);
}
// Add network usage commands
cmds.addCommands(usageCmds);
}
return true;
}
use of com.cloud.network.dao.RemoteAccessVpnVO in project cloudstack by apache.
the class RemoteAccessVpnManagerImpl method startRemoteAccessVpn.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, eventDescription = "creating remote access vpn", async = true)
public RemoteAccessVpnVO startRemoteAccessVpn(long ipAddressId, boolean openFirewall) throws ResourceUnavailableException {
Account caller = CallContext.current().getCallingAccount();
final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByPublicIpAddress(ipAddressId);
if (vpn == null) {
throw new InvalidParameterValueException("Unable to find your vpn: " + ipAddressId);
}
if (vpn.getVpcId() != null) {
openFirewall = false;
}
_accountMgr.checkAccess(caller, null, true, vpn);
boolean started = false;
try {
boolean firewallOpened = true;
if (openFirewall) {
firewallOpened = _firewallMgr.applyIngressFirewallRules(vpn.getServerAddressId(), caller);
}
if (firewallOpened) {
for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
if (element.startVpn(vpn)) {
started = true;
break;
}
}
}
return vpn;
} finally {
if (started) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
vpn.setState(RemoteAccessVpn.State.Running);
_remoteAccessVpnDao.update(vpn.getId(), vpn);
// Start billing of existing VPN users in ADD and Active state
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for (VpnUserVO user : vpnUsers) {
if (user.getState() != VpnUser.State.Revoke) {
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
}
}
}
});
}
}
}
use of com.cloud.network.dao.RemoteAccessVpnVO in project cloudstack by apache.
the class RemoteAccessVpnManagerImpl method destroyRemoteAccessVpnForIp.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, eventDescription = "removing remote access vpn", async = true)
public boolean destroyRemoteAccessVpnForIp(long ipId, Account caller, final boolean forceCleanup) throws ResourceUnavailableException {
final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByPublicIpAddress(ipId);
if (vpn == null) {
s_logger.debug("there are no Remote access vpns for public ip address id=" + ipId);
return true;
}
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, vpn);
RemoteAccessVpn.State prevState = vpn.getState();
vpn.setState(RemoteAccessVpn.State.Removed);
_remoteAccessVpnDao.update(vpn.getId(), vpn);
boolean success = false;
try {
for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
if (element.stopVpn(vpn)) {
success = true;
break;
}
}
} catch (ResourceUnavailableException ex) {
vpn.setState(prevState);
_remoteAccessVpnDao.update(vpn.getId(), vpn);
s_logger.debug("Failed to stop the vpn " + vpn.getId() + " , so reverted state to " + RemoteAccessVpn.State.Running);
success = false;
} finally {
if (success || forceCleanup) {
//Cleanup corresponding ports
final List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
boolean applyFirewall = false;
final List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
//if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend
if (vpnFwRules.size() != 0 && _rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) {
applyFirewall = true;
}
if (applyFirewall) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (FirewallRule vpnFwRule : vpnFwRules) {
//don't apply on the backend yet; send all 3 rules in a banch
_firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false);
fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId()));
}
s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn");
}
});
//now apply vpn rules on the backend
s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn");
success = _firewallMgr.applyIngressFirewallRules(ipId, caller);
}
if (success || forceCleanup) {
try {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_remoteAccessVpnDao.remove(vpn.getId());
// Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for (VpnUserVO user : vpnUsers) {
// VPN_USER_REMOVE event is already generated for users in Revoke state
if (user.getState() != VpnUser.State.Revoke) {
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
}
}
if (vpnFwRules != null) {
for (FirewallRule vpnFwRule : vpnFwRules) {
_rulesDao.remove(vpnFwRule.getId());
s_logger.debug("Successfully removed firewall rule with ip id=" + vpnFwRule.getSourceIpAddressId() + " and port " + vpnFwRule.getSourcePortStart().intValue() + " as a part of vpn cleanup");
}
}
}
});
} catch (Exception ex) {
s_logger.warn("Unable to release the three vpn ports from the firewall rules", ex);
}
}
}
}
return success;
}
use of com.cloud.network.dao.RemoteAccessVpnVO in project cloudstack by apache.
the class RemoteAccessVpnManagerImpl method updateRemoteAccessVpn.
@Override
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_UPDATE, eventDescription = "updating remote access vpn", async = true)
public RemoteAccessVpn updateRemoteAccessVpn(long id, String customId, Boolean forDisplay) {
final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(id);
if (vpn == null) {
throw new InvalidParameterValueException("Can't find remote access vpn by id " + id);
}
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vpn);
if (customId != null) {
vpn.setUuid(customId);
}
if (forDisplay != null) {
vpn.setDisplay(forDisplay);
}
_remoteAccessVpnDao.update(vpn.getId(), vpn);
return _remoteAccessVpnDao.findById(id);
}
Aggregations