Search in sources :

Example 36 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class NiciraNvpElement method addNiciraNvpDevice.

@Override
@DB
public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) {
    ServerResource resource = new NiciraNvpResource();
    final String deviceName = Network.Provider.NiciraNvp.getName();
    NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
    if (networkDevice == null) {
        throw new CloudRuntimeException("No network device found for " + deviceName);
    }
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
    }
    long zoneId = physicalNetwork.getDataCenterId();
    final PhysicalNetworkServiceProviderVO ntwkSvcProvider = physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
    if (ntwkSvcProvider == null) {
        throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
    } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
        throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
    }
    if (niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
        throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network");
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("guid", UUID.randomUUID().toString());
    params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
    params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
    params.put("name", "Nicira Controller - " + cmd.getHost());
    params.put("ip", cmd.getHost());
    params.put("adminuser", cmd.getUsername());
    params.put("adminpass", cmd.getPassword());
    params.put("transportzoneuuid", cmd.getTransportzoneUuid());
    // FIXME What to do with multiple isolation types
    params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase());
    if (cmd.getL3GatewayServiceUuid() != null) {
        params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid());
    }
    if (cmd.getL2GatewayServiceUuid() != null) {
        params.put("l2gatewayserviceuuid", cmd.getL2GatewayServiceUuid());
    }
    Map<String, Object> hostdetails = new HashMap<String, Object>();
    hostdetails.putAll(params);
    try {
        resource.configure(cmd.getHost(), hostdetails);
        final Host host = resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
        if (host != null) {
            return Transaction.execute(new TransactionCallback<NiciraNvpDeviceVO>() {

                @Override
                public NiciraNvpDeviceVO doInTransaction(TransactionStatus status) {
                    NiciraNvpDeviceVO niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
                    niciraNvpDao.persist(niciraNvpDevice);
                    DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId()));
                    hostDetailsDao.persist(detail);
                    return niciraNvpDevice;
                }
            });
        } else {
            throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error.");
        }
    } catch (ConfigurationException e) {
        throw new CloudRuntimeException(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) NetworkDevice(org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice) NiciraNvpDeviceVO(com.cloud.network.NiciraNvpDeviceVO) ServerResource(com.cloud.resource.ServerResource) NiciraNvpResource(com.cloud.network.resource.NiciraNvpResource) TransactionStatus(com.cloud.utils.db.TransactionStatus) Host(com.cloud.host.Host) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DetailVO(com.cloud.host.DetailVO) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) DB(com.cloud.utils.db.DB)

Example 37 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class NetscalerElement method registerNetscalerControlCenter.

@Override
@DB
public NetScalerControlCenterVO registerNetscalerControlCenter(RegisterNetscalerControlCenterCmd cmd) {
    if (_netscalerControlCenterDao.listAll() != null && _netscalerControlCenterDao.listAll().size() != 0) {
        throw new CloudRuntimeException("One Netscaler Control Center already exist in the DataBase. At a time only one Netscaler Control Center is allowed");
    }
    final RegisterNetscalerControlCenterCmd cmdinfo = cmd;
    String ipAddress = cmd.getIpaddress();
    Map hostDetails = new HashMap<String, String>();
    String hostName = "NetscalerControlCenter";
    hostDetails.put("name", hostName);
    hostDetails.put("guid", UUID.randomUUID().toString());
    List<DataCenterVO> dcVO = _dcDao.listEnabledZones();
    if (dcVO.size() == 0) {
        throw new CloudRuntimeException("There is no single enabled zone. Please add a zone, enable it and then add Netscaler ControlCenter");
    }
    hostDetails.put("zoneId", "1");
    hostDetails.put("ip", ipAddress);
    hostDetails.put("username", cmd.getUsername());
    hostDetails.put("password", cmd.getPassword());
    hostDetails.put("deviceName", "Netscaler ControlCenter");
    ServerResource resource = new NetScalerControlCenterResource();
    try {
        resource.configure(hostName, hostDetails);
        return Transaction.execute(new TransactionCallback<NetScalerControlCenterVO>() {

            @Override
            public NetScalerControlCenterVO doInTransaction(TransactionStatus status) {
                NetScalerControlCenterVO nccVO = new NetScalerControlCenterVO(cmdinfo.getUsername(), DBEncryptionUtil.encrypt(cmdinfo.getPassword()), cmdinfo.getIpaddress(), cmdinfo.getNumretries());
                _netscalerControlCenterDao.persist(nccVO);
                return nccVO;
            }
        });
    } catch (ConfigurationException e) {
        resource = null;
        throw new CloudRuntimeException(e.getMessage());
    }
}
Also used : RegisterNetscalerControlCenterCmd(com.cloud.api.commands.RegisterNetscalerControlCenterCmd) DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) NetScalerControlCenterVO(com.cloud.network.NetScalerControlCenterVO) ServerResource(com.cloud.resource.ServerResource) TransactionStatus(com.cloud.utils.db.TransactionStatus) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Map(java.util.Map) HashMap(java.util.HashMap) NetScalerControlCenterResource(com.cloud.network.resource.NetScalerControlCenterResource) DB(com.cloud.utils.db.DB)

Example 38 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class VpcManagerImpl method configure.

@Override
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
    // configure default vpc offering
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCOfferingName) == null) {
                s_logger.debug("Creating default VPC offering " + VpcOffering.defaultVPCOfferingName);
                final Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
                final Set<Provider> defaultProviders = new HashSet<Provider>();
                defaultProviders.add(Provider.VPCVirtualRouter);
                for (final Service svc : getSupportedServices()) {
                    if (svc == Service.Lb) {
                        final Set<Provider> lbProviders = new HashSet<Provider>();
                        lbProviders.add(Provider.VPCVirtualRouter);
                        lbProviders.add(Provider.InternalLbVm);
                        svcProviderMap.put(svc, lbProviders);
                    } else {
                        svcProviderMap.put(svc, defaultProviders);
                    }
                }
                createVpcOffering(VpcOffering.defaultVPCOfferingName, VpcOffering.defaultVPCOfferingName, svcProviderMap, true, State.Enabled, null, false, false, false);
            }
            // configure default vpc offering with Netscaler as LB Provider
            if (_vpcOffDao.findByUniqueName(VpcOffering.defaultVPCNSOfferingName) == null) {
                s_logger.debug("Creating default VPC offering with Netscaler as LB Provider" + VpcOffering.defaultVPCNSOfferingName);
                final Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
                final Set<Provider> defaultProviders = new HashSet<Provider>();
                defaultProviders.add(Provider.VPCVirtualRouter);
                for (final Service svc : getSupportedServices()) {
                    if (svc == Service.Lb) {
                        final Set<Provider> lbProviders = new HashSet<Provider>();
                        lbProviders.add(Provider.Netscaler);
                        lbProviders.add(Provider.InternalLbVm);
                        svcProviderMap.put(svc, lbProviders);
                    } else {
                        svcProviderMap.put(svc, defaultProviders);
                    }
                }
                createVpcOffering(VpcOffering.defaultVPCNSOfferingName, VpcOffering.defaultVPCNSOfferingName, svcProviderMap, false, State.Enabled, null, false, false, false);
            }
            if (_vpcOffDao.findByUniqueName(VpcOffering.redundantVPCOfferingName) == null) {
                s_logger.debug("Creating Redundant VPC offering " + VpcOffering.redundantVPCOfferingName);
                final Map<Service, Set<Provider>> svcProviderMap = new HashMap<Service, Set<Provider>>();
                final Set<Provider> defaultProviders = new HashSet<Provider>();
                defaultProviders.add(Provider.VPCVirtualRouter);
                for (final Service svc : getSupportedServices()) {
                    if (svc == Service.Lb) {
                        final Set<Provider> lbProviders = new HashSet<Provider>();
                        lbProviders.add(Provider.VPCVirtualRouter);
                        lbProviders.add(Provider.InternalLbVm);
                        svcProviderMap.put(svc, lbProviders);
                    } else {
                        svcProviderMap.put(svc, defaultProviders);
                    }
                }
                createVpcOffering(VpcOffering.redundantVPCOfferingName, VpcOffering.redundantVPCOfferingName, svcProviderMap, true, State.Enabled, null, false, false, true);
            }
        }
    });
    final Map<String, String> configs = _configDao.getConfiguration(params);
    final String value = configs.get(Config.VpcCleanupInterval.key());
    // 1 hour
    _cleanupInterval = NumbersUtil.parseInt(value, 60 * 60);
    final String maxNtwks = configs.get(Config.VpcMaxNetworks.key());
    // max=3 is default
    _maxNetworks = NumbersUtil.parseInt(maxNtwks, 3);
    IpAddressSearch = _ipAddressDao.createSearchBuilder();
    IpAddressSearch.and("accountId", IpAddressSearch.entity().getAllocatedToAccountId(), Op.EQ);
    IpAddressSearch.and("dataCenterId", IpAddressSearch.entity().getDataCenterId(), Op.EQ);
    IpAddressSearch.and("vpcId", IpAddressSearch.entity().getVpcId(), Op.EQ);
    IpAddressSearch.and("associatedWithNetworkId", IpAddressSearch.entity().getAssociatedWithNetworkId(), Op.EQ);
    final SearchBuilder<VlanVO> virtualNetworkVlanSB = _vlanDao.createSearchBuilder();
    virtualNetworkVlanSB.and("vlanType", virtualNetworkVlanSB.entity().getVlanType(), Op.EQ);
    IpAddressSearch.join("virtualNetworkVlanSB", virtualNetworkVlanSB, IpAddressSearch.entity().getVlanId(), virtualNetworkVlanSB.entity().getId(), JoinBuilder.JoinType.INNER);
    IpAddressSearch.done();
    return true;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) TransactionStatus(com.cloud.utils.db.TransactionStatus) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) QueryService(org.apache.cloudstack.query.QueryService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NetworkService(com.cloud.network.NetworkService) ResourceLimitService(com.cloud.user.ResourceLimitService) ExecutorService(java.util.concurrent.ExecutorService) AnnotationService(org.apache.cloudstack.annotation.AnnotationService) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) VpcProvider(com.cloud.network.element.VpcProvider) Provider(com.cloud.network.Network.Provider) VlanVO(com.cloud.dc.VlanVO) Map(java.util.Map) HashMap(java.util.HashMap) DB(com.cloud.utils.db.DB)

Example 39 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class VpcManagerImpl method associateIPToVpc.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true)
public IpAddress associateIPToVpc(final long ipId, final long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
    final Account caller = CallContext.current().getCallingAccount();
    Account owner = null;
    final IpAddress ipToAssoc = _ntwkModel.getIp(ipId);
    if (ipToAssoc != null) {
        _accountMgr.checkAccess(caller, null, true, ipToAssoc);
        owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId());
    } else {
        s_logger.debug("Unable to find ip address by id: " + ipId);
        return null;
    }
    final Vpc vpc = _vpcDao.findById(vpcId);
    if (vpc == null) {
        throw new InvalidParameterValueException("Invalid VPC id provided");
    }
    // check permissions
    _accountMgr.checkAccess(caller, null, true, owner, vpc);
    s_logger.debug("Associating ip " + ipToAssoc + " to vpc " + vpc);
    final boolean isSourceNatFinal = isSrcNatIpRequired(vpc.getVpcOfferingId()) && getExistingSourceNatInVpc(owner.getId(), vpcId) == null;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final IPAddressVO ip = _ipAddressDao.findById(ipId);
            // update ip address with networkId
            ip.setVpcId(vpcId);
            ip.setSourceNat(isSourceNatFinal);
            _ipAddressDao.update(ipId, ip);
            // mark ip as allocated
            _ipAddrMgr.markPublicIpAsAllocated(ip);
        }
    });
    s_logger.debug("Successfully assigned ip " + ipToAssoc + " to vpc " + vpc);
    return _ipAddressDao.findById(ipId);
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) IpAddress(com.cloud.network.IpAddress) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 40 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus 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)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)323 DB (com.cloud.utils.db.DB)257 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)150 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)117 ArrayList (java.util.ArrayList)104 Account (com.cloud.user.Account)93 List (java.util.List)89 ActionEvent (com.cloud.event.ActionEvent)88 ConfigurationException (javax.naming.ConfigurationException)71 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)64 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)64 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)50 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)49 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)47 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)45 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)45 IPAddressVO (com.cloud.network.dao.IPAddressVO)43 HashMap (java.util.HashMap)38 Network (com.cloud.network.Network)37