Search in sources :

Example 56 with ResourceUnavailableException

use of com.cloud.exception.ResourceUnavailableException in project cloudstack by apache.

the class NetScalerVMManagerImpl method deployNsVpx.

@Override
public Map<String, Object> deployNsVpx(Account owner, DeployDestination dest, DeploymentPlan plan, long svcOffId, long templateId) throws InsufficientCapacityException {
    VMTemplateVO template = _templateDao.findById(templateId);
    long id = _vmDao.getNextInSequence(Long.class, "id");
    Account systemAcct = _accountMgr.getSystemAccount();
    if (template == null) {
        s_logger.error(" Unable to find the NS VPX template");
        throw new CloudRuntimeException("Unable to find the Template" + templateId);
    }
    long dataCenterId = dest.getDataCenter().getId();
    DataCenterVO dc = _dcDao.findById(dest.getDataCenter().getId());
    String nxVpxName = VirtualMachineName.getSystemVmName(id, "Vpx", NetScalerLbVmNamePrefix);
    // using 2GB and 2CPU  offering
    ServiceOfferingVO vpxOffering = _serviceOfferingDao.findById(svcOffId);
    if (vpxOffering.getRamSize() < 2048 && vpxOffering.getCpu() < 2) {
        throw new InvalidParameterValueException("Specified Service Offering :" + vpxOffering.getUuid() + " NS Vpx cannot be deployed. Min 2GB Ram and 2 CPU are required");
    }
    long userId = CallContext.current().getCallingUserId();
    // TODO change the os bits from 142  103 to the actual guest of bits
    if (template.getGuestOSId() != 103) {
        throw new InvalidParameterValueException("Specified Template " + template.getUuid() + " not suitable for NS VPX Deployment. Please register the template with guest os type as unknow(64-bit)");
    }
    NetworkVO defaultNetwork = null;
    NetworkVO defaultPublicNetwork = null;
    if (dc.getNetworkType() == NetworkType.Advanced && dc.isSecurityGroupEnabled()) {
        List<NetworkVO> networks = _networkDao.listByZoneSecurityGroup(dataCenterId);
        if (networks == null || networks.size() == 0) {
            throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc);
        }
        defaultNetwork = networks.get(0);
    } else {
        TrafficType defaultTrafficType = TrafficType.Management;
        List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, defaultTrafficType);
        TrafficType publicTrafficType = TrafficType.Public;
        List<NetworkVO> publicNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, publicTrafficType);
        // api should never allow this situation to happen
        if (defaultNetworks.size() != 1) {
            throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
        }
        if (publicNetworks.size() != 1) {
            throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
        }
        defaultPublicNetwork = publicNetworks.get(0);
        defaultNetwork = defaultNetworks.get(0);
    }
    LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(4);
    NicProfile defaultNic = new NicProfile();
    defaultNic.setDefaultNic(true);
    defaultNic.setDeviceId(0);
    networks.put(_networkMgr.setupNetwork(_accountMgr.getSystemAccount(), _networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0), new ArrayList<NicProfile>());
    NicProfile defaultNic1 = new NicProfile();
    defaultNic1.setDefaultNic(false);
    defaultNic1.setDeviceId(1);
    NicProfile defaultNic2 = new NicProfile();
    defaultNic2.setDefaultNic(false);
    defaultNic2.setDeviceId(2);
    defaultNic2.setIPv4Address("");
    defaultNic2.setIPv4Gateway("");
    defaultNic2.setIPv4Netmask("");
    String macAddress = _networkDao.getNextAvailableMacAddress(defaultPublicNetwork.getId(), null);
    defaultNic2.setMacAddress(macAddress);
    networks.put(_networkMgr.setupNetwork(_accountMgr.getSystemAccount(), _networkOfferingDao.findByUniqueName(NetworkOffering.SystemPublicNetwork), plan, null, null, false).get(0), new ArrayList<NicProfile>(Arrays.asList(defaultNic2)));
    networks.put(_networkMgr.setupNetwork(_accountMgr.getSystemAccount(), _networkOfferingDao.findByUniqueName(NetworkOffering.SystemControlNetwork), plan, null, null, false).get(0), new ArrayList<NicProfile>());
    long physicalNetworkId = _networkModel.findPhysicalNetworkId(dataCenterId, _networkOfferingDao.findById(defaultPublicNetwork.getNetworkOfferingId()).getTags(), TrafficType.Public);
    // Validate physical network
    PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + _networkOfferingDao.findById(defaultPublicNetwork.getNetworkOfferingId()).getTags());
    }
    String guestvnet = physicalNetwork.getVnetString();
    final List<VlanVO> vlans = _vlanDao.listByZone(dataCenterId);
    List<String> pvlan = new ArrayList<String>();
    for (final VlanVO vlan : vlans) {
        pvlan.add(vlan.getVlanTag());
    }
    long netScalerProvider = getNetScalerLbProviderId(physicalNetworkId);
    DomainRouterVO nsVpx = new DomainRouterVO(id, vpxOffering.getId(), netScalerProvider, nxVpxName, template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, false, false, VirtualMachine.Type.NetScalerVm, null);
    nsVpx.setRole(Role.NETSCALER_VM);
    nsVpx = _routerDao.persist(nsVpx);
    VMInstanceVO vmVO = _vmDao.findVMByHostName(nxVpxName);
    _itMgr.allocate(nxVpxName, template, vpxOffering, networks, plan, template.getHypervisorType());
    Map<Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(1);
    try {
        if (vmVO != null) {
            startNsVpx(vmVO, params);
        } else {
            throw new NullPointerException();
        }
    } catch (StorageUnavailableException e) {
        e.printStackTrace();
    } catch (ConcurrentOperationException e) {
        e.printStackTrace();
    } catch (ResourceUnavailableException e) {
        e.printStackTrace();
    }
    vmVO = _vmDao.findByUuid(nsVpx.getUuid());
    Map<String, Object> deployResponse = new HashMap<String, Object>();
    deployResponse.put("vm", vmVO);
    deployResponse.put("guestvlan", guestvnet);
    deployResponse.put("publicvlan", pvlan);
    return deployResponse;
}
Also used : Account(com.cloud.user.Account) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) List(java.util.List) ArrayList(java.util.ArrayList) VlanVO(com.cloud.dc.VlanVO) TrafficType(com.cloud.network.Networks.TrafficType) DataCenterVO(com.cloud.dc.DataCenterVO) NetworkVO(com.cloud.network.dao.NetworkVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) Param(com.cloud.vm.VirtualMachineProfile.Param) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 57 with ResourceUnavailableException

use of com.cloud.exception.ResourceUnavailableException in project cloudstack by apache.

the class VpcManagerImpl method unassignIPFromVpcNetwork.

@Override
public void unassignIPFromVpcNetwork(final long ipId, final long networkId) {
    final IPAddressVO ip = _ipAddressDao.findById(ipId);
    if (isIpAllocatedToVpc(ip)) {
        return;
    }
    if (ip == null || ip.getVpcId() == null) {
        return;
    }
    s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId);
    final long vpcId = ip.getVpcId();
    boolean success = false;
    try {
        // unassign ip from the VPC router
        success = _ipAddrMgr.applyIpAssociations(_ntwkModel.getNetwork(networkId), true);
    } catch (final ResourceUnavailableException ex) {
        throw new CloudRuntimeException("Failed to apply ip associations for network id=" + networkId + " as a part of unassigning ip " + ipId + " from vpc", ex);
    }
    if (success) {
        ip.setAssociatedWithNetworkId(null);
        _ipAddressDao.update(ipId, ip);
        s_logger.debug("IP address " + ip + " is no longer associated with the network inside vpc id=" + vpcId);
    } else {
        throw new CloudRuntimeException("Failed to apply ip associations for network id=" + networkId + " as a part of unassigning ip " + ipId + " from vpc");
    }
    s_logger.debug("Successfully released VPC ip address " + ip + " back to VPC pool ");
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 58 with ResourceUnavailableException

use of com.cloud.exception.ResourceUnavailableException in project cloudstack by apache.

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 DataCenter dc = _entityMgr.findById(DataCenter.class, vpc.getZoneId());
    final DeployDestination dest = new DeployDestination(dc, 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;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CallContext(org.apache.cloudstack.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ReservationContext(com.cloud.vm.ReservationContext)

Example 59 with ResourceUnavailableException

use of com.cloud.exception.ResourceUnavailableException 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) {
            final List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
            boolean applyFirewall = false;
            final List<FirewallRuleVO> fwRules = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(vpnFwRules) && _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) {
                            _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");
                    }
                });
                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());
                            List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
                            for (VpnUserVO user : vpnUsers) {
                                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() + " as a part of vpn cleanup");
                                }
                            }
                        }
                    });
                } catch (Exception ex) {
                    s_logger.warn(String.format("Unable to release the VPN ports from the firewall rules [%s] due to [%s]", fwRules.stream().map(rule -> String.format("{\"ipId\": %s, \"port\": %s}", rule.getSourceIpAddressId(), rule.getSourcePortStart())).collect(Collectors.joining(", ")), ex.getMessage()), ex);
                }
            }
        }
    }
    return success;
}
Also used : RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) VpnUserVO(com.cloud.network.VpnUserVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) AccountLimitException(com.cloud.exception.AccountLimitException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 60 with ResourceUnavailableException

use of com.cloud.exception.ResourceUnavailableException in project cloudstack by apache.

the class RulesManagerImpl method enableStaticNat.

private boolean enableStaticNat(long ipId, long vmId, long networkId, boolean isSystemVm, String vmGuestIp) throws NetworkRuleConflictException, ResourceUnavailableException {
    CallContext ctx = CallContext.current();
    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;
    boolean isOneToOneNat = ipAddress.isOneToOneNat();
    Long associatedWithVmId = ipAddress.getAssociatedWithVmId();
    Nic guestNic;
    NicSecondaryIpVO nicSecIp = null;
    String dstIp = null;
    try {
        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) {
            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) {
                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);
                        performedIpAssoc = true;
                    } catch (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.isPortable()) {
                    s_logger.info("Portable IP " + ipAddress.getUuid() + " is not associated with the network yet " + " so associate IP with the network " + networkId);
                    try {
                        // check if StaticNat service is enabled in the network
                        _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                        // associate portable IP to vpc, if network is part of VPC
                        if (network.getVpcId() != null) {
                            _vpcSvc.associateIPToVpc(ipId, network.getVpcId());
                        }
                        // associate portable IP with guest network
                        ipAddress = _ipAddrMgr.associatePortableIPToGuestNetwork(ipId, networkId, false);
                    } catch (Exception e) {
                        s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " + "a part of enable static nat");
                        return false;
                    }
                }
            } else if (ipAddress.getAssociatedWithNetworkId() != networkId) {
                if (ipAddress.isPortable()) {
                    // check if destination network has StaticNat service enabled
                    _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                    // check if portable IP can be transferred across the networks
                    if (_ipAddrMgr.isPortableIpTransferableFromNetwork(ipId, ipAddress.getAssociatedWithNetworkId())) {
                        try {
                            // transfer the portable IP and refresh IP details
                            _ipAddrMgr.transferPortableIP(ipId, ipAddress.getAssociatedWithNetworkId(), networkId);
                            ipAddress = _ipAddressDao.findById(ipId);
                        } catch (Exception e) {
                            s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " + "a part of enable static nat");
                            return false;
                        }
                    } else {
                        throw new InvalidParameterValueException("Portable IP: " + ipId + " has associated services " + "in network " + ipAddress.getAssociatedWithNetworkId() + " so can not be transferred to " + " network " + networkId);
                    }
                } else {
                    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
                    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)) {
                applyUserDataIfNeeded(vmId, network, guestNic);
                // 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
            IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
        }
    }
    return false;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) Nic(com.cloud.vm.Nic) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress)

Aggregations

ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)446 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)191 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)175 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)153 ArrayList (java.util.ArrayList)99 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)91 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)74 Account (com.cloud.user.Account)62 DomainRouterVO (com.cloud.vm.DomainRouterVO)60 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)59 ConfigurationException (javax.naming.ConfigurationException)53 DB (com.cloud.utils.db.DB)52 ServerApiException (org.apache.cloudstack.api.ServerApiException)51 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)47 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)47 ActionEvent (com.cloud.event.ActionEvent)46 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)46 DataCenter (com.cloud.dc.DataCenter)45 ServerApiException (com.cloud.api.ServerApiException)43 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)42