use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.
the class VpcManagerImpl method startVpc.
@Override
public boolean startVpc(final long vpcId, final boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
final CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount();
final User callerUser = _accountMgr.getActiveUser(ctx.getCallingUserId());
// check if vpc exists
final Vpc vpc = getActiveVpc(vpcId);
if (vpc == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
ex.addProxyObject(String.valueOf(vpcId), "VPC");
throw ex;
}
// permission check
_accountMgr.checkAccess(caller, null, false, vpc);
final Zone zone = zoneRepository.findOne(vpc.getZoneId());
final DeployDestination dest = new DeployDestination(zone, null, null, null);
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, _accountMgr.getAccount(vpc.getAccountId()));
boolean result = true;
try {
if (!startVpc(vpc, dest, context)) {
s_logger.warn("Failed to start vpc " + vpc);
result = false;
}
} catch (final Exception ex) {
s_logger.warn("Failed to start vpc " + vpc + " due to ", ex);
result = false;
} finally {
// do cleanup
if (!result && destroyOnFailure) {
s_logger.debug("Destroying vpc " + vpc + " that failed to start");
if (destroyVpc(vpc, caller, callerUser.getId())) {
s_logger.warn("Successfully destroyed vpc " + vpc + " that failed to start");
} else {
s_logger.warn("Failed to destroy vpc " + vpc + " that failed to start");
}
}
}
return result;
}
use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.
the class VpcManagerImpl method deleteVpc.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_DELETE, eventDescription = "deleting VPC")
public boolean deleteVpc(final long vpcId) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext.current().setEventDetails(" Id: " + vpcId);
final CallContext ctx = CallContext.current();
// Verify vpc id
final Vpc vpc = _vpcDao.findById(vpcId);
if (vpc == null) {
throw new InvalidParameterValueException("unable to find VPC id=" + vpcId);
}
// verify permissions
_accountMgr.checkAccess(ctx.getCallingAccount(), null, false, vpc);
return destroyVpc(vpc, ctx.getCallingAccount(), ctx.getCallingUserId());
}
use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.
the class RemoteAccessVpnManagerImpl method createRemoteAccessVpn.
@Override
@DB
public RemoteAccessVpn createRemoteAccessVpn(final long publicIpId, String ipRange, boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
final CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount();
final Long networkId;
// make sure ip address exists
final PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
if (ipAddr == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
}
_accountMgr.checkAccess(caller, null, true, ipAddr);
if (!ipAddr.readyToUse()) {
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
}
final IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
networkId = ipAddress.getAssociatedWithNetworkId();
if (networkId != null) {
_networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
}
final Long vpcId = ipAddress.getVpcId();
/* IP Address used for VPC must be the source NAT IP of whole VPC */
if (vpcId != null && ipAddress.isSourceNat()) {
assert networkId == null;
// No firewall setting for VPC, it would be open internally
openFirewall = false;
}
final boolean openFirewallFinal = openFirewall;
if (networkId == null && vpcId == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress: " + ipAddr.getAddress().addr() + " as ip is not associated with any network or VPC");
}
RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
if (vpnVO != null) {
// if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
}
if (ipRange == null) {
ipRange = RemoteAccessVpnClientIpRange.valueIn(ipAddr.getAccountId());
}
final String[] range = ipRange.split("-");
if (range.length != 2) {
throw new InvalidParameterValueException("Invalid ip range");
}
if (!NetUtils.isValidIp4(range[0]) || !NetUtils.isValidIp4(range[1])) {
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
}
if (!NetUtils.validIpRange(range[0], range[1])) {
throw new InvalidParameterValueException("Invalid ip range " + ipRange);
}
final Pair<String, Integer> cidr;
// TODO: assumes one virtual network / domr per account per zone
if (networkId != null) {
vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddr.getAccountId(), networkId);
if (vpnVO != null) {
// if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
}
// Verify that vpn service is enabled for the network
final Network network = _networkMgr.getNetwork(networkId);
if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
}
cidr = NetUtils.getCidr(network.getCidr());
} else {
// Don't need to check VPC because there is only one IP(source NAT IP) available for VPN
final Vpc vpc = _vpcDao.findById(vpcId);
cidr = NetUtils.getCidr(vpc.getCidr());
}
// FIXME: This check won't work for the case where the guest ip range
// changes depending on the vlan allocated.
final String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
}
// TODO: check sufficient range
// TODO: check overlap with private and public ip ranges in datacenter
long startIp = NetUtils.ip2Long(range[0]);
final String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
final String sharedSecret = PasswordGenerator.generatePresharedKey(_pskLength);
return Transaction.execute(new TransactionCallbackWithException<RemoteAccessVpn, NetworkRuleConflictException>() {
@Override
public RemoteAccessVpn doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
if (vpcId == null) {
_rulesMgr.reservePorts(ipAddr, NetUtils.UDP_PROTO, Purpose.Vpn, openFirewallFinal, caller, NetUtils.VPN_PORT, NetUtils.VPN_L2TP_PORT, NetUtils.VPN_NATT_PORT);
}
final RemoteAccessVpnVO vpnVO = new RemoteAccessVpnVO(ipAddr.getAccountId(), ipAddr.getDomainId(), ipAddr.getAssociatedWithNetworkId(), publicIpId, vpcId, range[0], newIpRange, sharedSecret);
if (forDisplay != null) {
vpnVO.setDisplay(forDisplay);
}
return _remoteAccessVpnDao.persist(vpnVO);
}
});
}
use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.
the class RulesManagerImpl method enableStaticNat.
private boolean enableStaticNat(final long ipId, final long vmId, final long networkId, final boolean isSystemVm, final String vmGuestIp) throws NetworkRuleConflictException, ResourceUnavailableException {
final CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount();
CallContext.current().setEventDetails("Ip Id: " + ipId);
// Verify input parameters
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to find ip address by id " + ipId);
}
// Verify input parameters
boolean performedIpAssoc = false;
final boolean isOneToOneNat = ipAddress.isOneToOneNat();
final Long associatedWithVmId = ipAddress.getAssociatedWithVmId();
final Nic guestNic;
NicSecondaryIpVO nicSecIp = null;
String dstIp = null;
try {
final Network network = _networkModel.getNetwork(networkId);
if (network == null) {
throw new InvalidParameterValueException("Unable to find network by id");
}
// Check that vm has a nic in the network
guestNic = _networkModel.getNicInNetwork(vmId, networkId);
if (guestNic == null) {
throw new InvalidParameterValueException("Vm doesn't belong to the network with specified id");
}
dstIp = guestNic.getIPv4Address();
if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
throw new InvalidParameterValueException("Unable to create static nat rule; StaticNat service is not " + "supported in network with specified id");
}
if (!isSystemVm) {
final UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Can't enable static nat for the address id=" + ipId + ", invalid virtual machine id specified (" + vmId + ").");
}
// associate ip address to network (if needed)
if (ipAddress.getAssociatedWithNetworkId() == null) {
final boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
if (assignToVpcNtwk) {
_networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
try {
ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, false);
} catch (final Exception ex) {
s_logger.warn("Failed to associate ip id=" + ipId + " to VPC network id=" + networkId + " as " + "a part of enable static nat");
return false;
}
}
} else if (ipAddress.getAssociatedWithNetworkId() != networkId) {
throw new InvalidParameterValueException("Invalid network Id=" + networkId + ". IP is associated with" + " a different network than passed network id");
} else {
_networkModel.checkIpForService(ipAddress, Service.StaticNat, null);
}
if (ipAddress.getAssociatedWithNetworkId() == null) {
throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
}
// Check permissions
if (ipAddress.getSystem()) {
// when system is enabling static NAT on system IP's (for EIP) ignore VM state
checkIpAndUserVm(ipAddress, vm, caller, true);
} else {
checkIpAndUserVm(ipAddress, vm, caller, false);
}
// dstIp = guestNic.getIp4Address();
if (vmGuestIp != null) {
if (!dstIp.equals(vmGuestIp)) {
// check whether the secondary ip set to the vm or not
final boolean secondaryIpSet = _networkMgr.isSecondaryIpSetForNic(guestNic.getId());
if (!secondaryIpSet) {
throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
}
// check the ip belongs to the vm or not
nicSecIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp, guestNic.getId());
if (nicSecIp == null) {
throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
}
dstIp = nicSecIp.getIp4Address();
// Set public ip column with the vm ip
}
}
// Verify ip address parameter
// checking vm id is not sufficient, check for the vm ip
isIpReadyForStaticNat(vmId, ipAddress, dstIp, caller, ctx.getCallingUserId());
}
ipAddress.setOneToOneNat(true);
ipAddress.setAssociatedWithVmId(vmId);
ipAddress.setVmIp(dstIp);
if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) {
// enable static nat on the backend
s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend");
if (applyStaticNatForIp(ipId, false, caller, false)) {
// ignor unassignIPFromVpcNetwork in finally block
performedIpAssoc = false;
return true;
} else {
s_logger.warn("Failed to enable static nat rule for ip address " + ipId + " on the backend");
ipAddress.setOneToOneNat(isOneToOneNat);
ipAddress.setAssociatedWithVmId(associatedWithVmId);
ipAddress.setVmIp(null);
_ipAddressDao.update(ipAddress.getId(), ipAddress);
}
} else {
s_logger.warn("Failed to update ip address " + ipAddress + " in the DB as a part of enableStaticNat");
}
} finally {
if (performedIpAssoc) {
// if the rule is the last one for the ip address assigned to VPC, unassign it from the network
final IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
_vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
}
}
return false;
}
use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.
the class RulesManagerImpl method createPortForwardingRule.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true)
public PortForwardingRule createPortForwardingRule(final PortForwardingRule rule, final Long vmId, final Ip vmIp, final boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
final CallContext ctx = CallContext.current();
final Account caller = ctx.getCallingAccount();
final Long ipAddrId = rule.getSourceIpAddressId();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
}
final Long networkId = rule.getNetworkId();
final Network network = _networkModel.getNetwork(networkId);
// associate ip address to network (if needed)
boolean performedIpAssoc = false;
final Nic guestNic;
if (ipAddress.getAssociatedWithNetworkId() == null) {
final boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
if (assignToVpcNtwk) {
_networkModel.checkIpForService(ipAddress, Service.PortForwarding, networkId);
s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
try {
ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
performedIpAssoc = true;
} catch (final Exception ex) {
throw new CloudRuntimeException("Failed to associate ip to VPC network as " + "a part of port forwarding rule creation");
}
}
} else {
_networkModel.checkIpForService(ipAddress, Service.PortForwarding, null);
}
if (ipAddress.getAssociatedWithNetworkId() == null) {
throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
}
try {
_firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User, networkId, rule.getTrafficType());
final Long accountId = ipAddress.getAllocatedToAccountId();
final Long domainId = ipAddress.getAllocatedInDomainId();
// start port can't be bigger than end port
if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
throw new InvalidParameterValueException("Start port can't be bigger than end port");
}
// check that the port ranges are of equal size
if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
}
// validate user VM exists
final UserVm vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ").");
} else if (vm.getState() == VirtualMachine.State.Destroyed || vm.getState() == VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("Invalid user vm: " + vm.getId());
}
// Verify that vm has nic in the network
Ip dstIp = rule.getDestinationIpAddress();
guestNic = _networkModel.getNicInNetwork(vmId, networkId);
if (guestNic == null || guestNic.getIPv4Address() == null) {
throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
} else {
dstIp = new Ip(guestNic.getIPv4Address());
}
if (vmIp != null) {
// vm ip is passed so it can be primary or secondary ip addreess.
if (!dstIp.equals(vmIp)) {
// the vm ip is secondary ip to the nic.
// is vmIp is secondary ip or not
final NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmIp.toString(), guestNic.getId());
if (secondaryIp == null) {
throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
}
dstIp = vmIp;
}
}
// if start port and end port are passed in, and they are not equal to each other, perform the validation
boolean validatePortRange = false;
if (rule.getSourcePortStart().intValue() != rule.getSourcePortEnd().intValue() || rule.getDestinationPortStart() != rule.getDestinationPortEnd()) {
validatePortRange = true;
}
if (validatePortRange) {
// source start port and source dest port should be the same. The same applies to dest ports
if (rule.getSourcePortStart().intValue() != rule.getDestinationPortStart()) {
throw new InvalidParameterValueException("Private port start should be equal to public port start");
}
if (rule.getSourcePortEnd().intValue() != rule.getDestinationPortEnd()) {
throw new InvalidParameterValueException("Private port end should be equal to public port end");
}
}
final Ip dstIpFinal = dstIp;
final IPAddressVO ipAddressFinal = ipAddress;
return Transaction.execute(new TransactionCallbackWithException<PortForwardingRuleVO, NetworkRuleConflictException>() {
@Override
public PortForwardingRuleVO doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIpFinal, rule.getDestinationPortStart(), rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
if (forDisplay != null) {
newRule.setDisplay(forDisplay);
}
newRule = _portForwardingDao.persist(newRule);
// create firewallRule for 0.0.0.0/0 cidr
if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId(), networkId);
}
try {
_firewallMgr.detectRulesConflict(newRule);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
return newRule;
} catch (final Exception e) {
if (newRule != null) {
// no need to apply the rule as it wasn't programmed on the backend yet
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
removePFRule(newRule);
}
if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e;
}
throw new CloudRuntimeException("Unable to add rule for the ip id=" + ipAddrId, e);
}
}
});
} finally {
// release ip address if ipassoc was perfored
if (performedIpAssoc) {
// if the rule is the last one for the ip address assigned to VPC, unassign it from the network
final IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
_vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
}
}
}
Aggregations