use of com.cloud.legacymodel.network.Ip in project cosmic by MissionCriticalCloud.
the class GenericDaoBase method prepareAttribute.
@DB()
protected void prepareAttribute(final int j, final PreparedStatement pstmt, final Attribute attr, Object value) throws SQLException {
if (attr.is(Attribute.Flag.DaoGenerated) && value == null) {
value = generateValue(attr);
if (attr.field == null) {
pstmt.setObject(j, value);
return;
}
}
if (attr.field.getType() == String.class) {
final String str = (String) value;
if (str == null) {
pstmt.setString(j, null);
return;
}
final Column column = attr.field.getAnnotation(Column.class);
final int length = column != null ? column.length() : 255;
// to support generic localization, utilize MySql UTF-8 support
if (length < str.length()) {
try {
if (attr.is(Attribute.Flag.Encrypted)) {
pstmt.setBytes(j, DBEncryptionUtil.encrypt(str.substring(0, length)).getBytes("UTF-8"));
} else {
pstmt.setBytes(j, str.substring(0, length).getBytes("UTF-8"));
}
} catch (final UnsupportedEncodingException e) {
// no-way it can't support UTF-8 encoding
assert (false);
throw new CloudRuntimeException("UnsupportedEncodingException when saving string as UTF-8 data");
}
} else {
try {
if (attr.is(Attribute.Flag.Encrypted)) {
pstmt.setBytes(j, DBEncryptionUtil.encrypt(str).getBytes("UTF-8"));
} else {
pstmt.setBytes(j, str.getBytes("UTF-8"));
}
} catch (final UnsupportedEncodingException e) {
// no-way it can't support UTF-8 encoding
assert (false);
throw new CloudRuntimeException("UnsupportedEncodingException when saving string as UTF-8 data");
}
}
} else if (attr.field.getType() == Date.class) {
final Date date = (Date) value;
if (date == null) {
pstmt.setObject(j, null);
return;
}
if (attr.is(Attribute.Flag.Date)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, date));
} else if (attr.is(Attribute.Flag.TimeStamp)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, date));
} else if (attr.is(Attribute.Flag.Time)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, date));
}
} else if (attr.field.getType() == Calendar.class) {
final Calendar cal = (Calendar) value;
if (cal == null) {
pstmt.setObject(j, null);
return;
}
if (attr.is(Attribute.Flag.Date)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, cal.getTime()));
} else if (attr.is(Attribute.Flag.TimeStamp)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, cal.getTime()));
} else if (attr.is(Attribute.Flag.Time)) {
pstmt.setString(j, DateUtil.getDateDisplayString(s_gmtTimeZone, cal.getTime()));
}
} else if (attr.field.getType().isEnum()) {
final Enumerated enumerated = attr.field.getAnnotation(Enumerated.class);
final EnumType type = (enumerated == null) ? EnumType.STRING : enumerated.value();
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
if (value == null) {
pstmt.setObject(j, null);
} else {
pstmt.setInt(j, ((Enum<?>) value).ordinal());
}
}
} else if (attr.field.getType() == URI.class) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (attr.field.getType() == URL.class) {
pstmt.setURL(j, (URL) value);
} else if (attr.field.getType() == byte[].class) {
pstmt.setBytes(j, (byte[]) value);
} else if (attr.field.getType() == Ip.class) {
final Enumerated enumerated = attr.field.getAnnotation(Enumerated.class);
final EnumType type = (enumerated == null) ? EnumType.ORDINAL : enumerated.value();
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
if (value == null) {
pstmt.setObject(j, null);
} else {
pstmt.setLong(j, (value instanceof Ip) ? ((Ip) value).longValue() : NetUtils.ip2Long((String) value));
}
}
} else {
pstmt.setObject(j, value);
}
}
use of com.cloud.legacymodel.network.Ip in project cosmic by MissionCriticalCloud.
the class IpAddressManagerImpl method allocateIp.
@DB
@Override
public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, final Account caller, final long callerUserId, final DataCenter zone, final Boolean displayIp) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
final VlanType vlanType = VlanType.VirtualNetwork;
final boolean assign = false;
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
// zone is of type DataCenter. See DataCenterVO.java.
final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, " + "Zone is currently disabled");
ex.addProxyObject(zone.getUuid(), "zoneId");
throw ex;
}
PublicIp ip = null;
Account accountToLock = null;
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
}
accountToLock = _accountDao.acquireInLockTable(ipOwner.getId());
if (accountToLock == null) {
s_logger.warn("Unable to lock account: " + ipOwner.getId());
throw new ConcurrentOperationException("Unable to acquire account lock");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address lock acquired");
}
ip = Transaction.execute(new TransactionCallbackWithException<PublicIp, InsufficientAddressCapacityException>() {
@Override
public PublicIp doInTransaction(final TransactionStatus status) throws InsufficientAddressCapacityException {
final PublicIp ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null, displayIp);
if (ip == null) {
final InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone.getId());
ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid());
throw ex;
}
CallContext.current().setEventDetails("Ip Id: " + ip.getId());
final Ip ipAddress = ip.getAddress();
s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + zone.getId());
return ip;
}
});
} finally {
if (accountToLock != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing lock account " + ipOwner);
}
_accountDao.releaseFromLockTable(ipOwner.getId());
s_logger.debug("Associate IP address lock released");
}
}
return ip;
}
use of com.cloud.legacymodel.network.Ip in project cosmic by MissionCriticalCloud.
the class RulesManagerImpl method updatePortForwardingRule.
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_MODIFY, eventDescription = "updating forwarding rule", async = true)
public PortForwardingRule updatePortForwardingRule(final long id, final Integer privatePort, final Long virtualMachineId, final Ip vmGuestIp, final String customId, final Boolean forDisplay) {
final Account caller = CallContext.current().getCallingAccount();
PortForwardingRuleVO rule = _portForwardingDao.findById(id);
if (rule == null) {
throw new InvalidParameterValueException("Unable to find " + id);
}
_accountMgr.checkAccess(caller, null, true, rule);
if (customId != null) {
rule.setUuid(customId);
}
if (forDisplay != null) {
rule.setDisplay(forDisplay);
}
if (!rule.getSourcePortStart().equals(rule.getSourcePortEnd()) && privatePort != null) {
throw new InvalidParameterValueException("Unable to update the private port of port forwarding rule as the rule has port range : " + rule.getSourcePortStart() + " " + "to " + rule.getSourcePortEnd());
}
if (virtualMachineId == null && vmGuestIp != null) {
throw new InvalidParameterValueException("vmguestip should be set along with virtualmachineid");
}
Ip dstIp = rule.getDestinationIpAddress();
if (virtualMachineId != null) {
// Verify that vm has nic in the network
final Nic guestNic = _networkModel.getNicInNetwork(virtualMachineId, rule.getNetworkId());
if (guestNic == null || guestNic.getIPv4Address() == null) {
throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
} else {
dstIp = new Ip(NetUtils.ip2Long(guestNic.getIPv4Address()));
}
if (vmGuestIp != null) {
// vm ip is passed so it can be primary or secondary ip addreess.
if (!dstIp.equals(vmGuestIp)) {
// the vm ip is secondary ip to the nic.
// is vmIp is secondary ip or not
final NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp.toString(), guestNic.getId());
if (secondaryIp == null) {
throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
}
dstIp = vmGuestIp;
}
}
}
// revoke old rules at first
final List<PortForwardingRuleVO> rules = new ArrayList<>();
rule.setState(State.Revoke);
_portForwardingDao.update(id, rule);
rules.add(rule);
try {
if (!_firewallMgr.applyRules(rules, true, false)) {
throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id);
}
} catch (final ResourceUnavailableException ex) {
throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id + " due to ", ex);
}
rule = _portForwardingDao.findById(id);
rule.setState(State.Add);
if (privatePort != null) {
rule.setDestinationPortStart(privatePort.intValue());
rule.setDestinationPortEnd(privatePort.intValue());
}
if (virtualMachineId != null) {
rule.setVirtualMachineId(virtualMachineId);
rule.setDestinationIpAddress(dstIp);
}
_portForwardingDao.update(id, rule);
// apply new rules
if (!applyPortForwardingRules(rule.getSourceIpAddressId(), false, caller)) {
throw new CloudRuntimeException("Failed to apply the new port forwarding rule:" + id);
}
return _portForwardingDao.findById(id);
}
use of com.cloud.legacymodel.network.Ip 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(NetUtils.ip2Long(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);
}
}
}
use of com.cloud.legacymodel.network.Ip in project cosmic by MissionCriticalCloud.
the class AdvancedNetworkVisitor method visit.
@Override
public boolean visit(final PrivateGatewayRules privateGW) throws ResourceUnavailableException {
final VirtualRouter router = privateGW.getRouter();
final NicProfile nicProfile = privateGW.getNicProfile();
final boolean add = privateGW.isAddOperation();
if (router.getState() == State.Running) {
final PrivateIpVO ipVO = privateGW.retrivePrivateIP(this);
final Network network = privateGW.retrievePrivateNetwork(this);
final String netmask = NetUtils.getCidrNetmask(network.getCidr());
final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, nicProfile.getMacAddress());
final Commands cmds = new Commands(Command.OnError.Stop);
final List<Ip> ipsToExclude = new ArrayList<>();
if (!add) {
ipsToExclude.add(new Ip(NetUtils.ip2Long(ip.getIpAddress())));
}
final NetworkOverviewTO networkOverview = _commandSetupHelper.createNetworkOverviewFromRouter(router, new ArrayList<>(), ipsToExclude, new ArrayList<>(), null, null, null);
final UpdateNetworkOverviewCommand updateNetworkOverviewCommand = _commandSetupHelper.createUpdateNetworkOverviewCommand(router, networkOverview);
cmds.addCommand(updateNetworkOverviewCommand);
try {
if (_networkGeneralHelper.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;
}
Aggregations