Search in sources :

Example 16 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method editZone.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ZONE_EDIT, eventDescription = "editing zone", async = false)
public DataCenter editZone(final UpdateZoneCmd cmd) {
    // Parameter validation as from execute() method in V1
    final Long zoneId = cmd.getId();
    String zoneName = cmd.getZoneName();
    String dns1 = cmd.getDns1();
    String dns2 = cmd.getDns2();
    String ip6Dns1 = cmd.getIp6Dns1();
    String ip6Dns2 = cmd.getIp6Dns2();
    String internalDns1 = cmd.getInternalDns1();
    String internalDns2 = cmd.getInternalDns2();
    String guestCidr = cmd.getGuestCidrAddress();
    final List<String> dnsSearchOrder = cmd.getDnsSearchOrder();
    final Boolean isPublic = cmd.isPublic();
    final String allocationStateStr = cmd.getAllocationState();
    final String dhcpProvider = cmd.getDhcpProvider();
    final Map<?, ?> detailsMap = cmd.getDetails();
    final String networkDomain = cmd.getDomain();
    final Boolean localStorageEnabled = cmd.getLocalStorageEnabled();
    final Map<String, String> newDetails = new HashMap<>();
    if (detailsMap != null) {
        final Collection<?> zoneDetailsCollection = detailsMap.values();
        final Iterator<?> iter = zoneDetailsCollection.iterator();
        while (iter.hasNext()) {
            final HashMap<?, ?> detail = (HashMap<?, ?>) iter.next();
            final String key = (String) detail.get("key");
            final String value = (String) detail.get("value");
            if (key == null || value == null) {
                throw new InvalidParameterValueException("Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form:  details[0].key=XXX&details[0].value=YYY");
            }
            newDetails.put(key, value);
        }
    }
    // add the domain prefix list to details if not null
    if (dnsSearchOrder != null) {
        for (final String dom : dnsSearchOrder) {
            if (!NetUtils.verifyDomainName(dom)) {
                throw new InvalidParameterValueException("Invalid network domain suffixes. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain " + "ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
            }
        }
        newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ","));
    }
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
    }
    if (zoneName == null) {
        zoneName = zone.getName();
    }
    if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) {
        throw new InvalidParameterValueException("Please enter a valid guest cidr");
    }
    // Make sure the zone exists
    if (!validZone(zoneId)) {
        throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist.");
    }
    final String oldZoneName = zone.getName();
    if (zoneName == null) {
        zoneName = oldZoneName;
    }
    if (dns1 == null) {
        dns1 = zone.getDns1();
    }
    if (dns2 == null) {
        dns2 = zone.getDns2();
    }
    if (ip6Dns1 == null) {
        ip6Dns1 = zone.getIp6Dns1();
    }
    if (ip6Dns2 == null) {
        ip6Dns2 = zone.getIp6Dns2();
    }
    if (internalDns1 == null) {
        internalDns1 = zone.getInternalDns1();
    }
    if (internalDns2 == null) {
        internalDns2 = zone.getInternalDns2();
    }
    if (guestCidr == null) {
        guestCidr = zone.getGuestNetworkCidr();
    }
    // validate network domain
    if (networkDomain != null && !networkDomain.isEmpty()) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
    }
    final boolean checkForDuplicates = !zoneName.equals(oldZoneName);
    // not allowing updating
    checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, checkForDuplicates, null, allocationStateStr, ip6Dns1, ip6Dns2);
    // domain associated with
    // a zone, once created
    zone.setName(zoneName);
    zone.setDns1(dns1);
    zone.setDns2(dns2);
    zone.setIp6Dns1(ip6Dns1);
    zone.setIp6Dns2(ip6Dns2);
    zone.setInternalDns1(internalDns1);
    zone.setInternalDns2(internalDns2);
    zone.setGuestNetworkCidr(guestCidr);
    if (localStorageEnabled != null) {
        zone.setLocalStorageEnabled(localStorageEnabled.booleanValue());
    }
    if (networkDomain != null) {
        if (networkDomain.isEmpty()) {
            zone.setDomain(null);
        } else {
            zone.setDomain(networkDomain);
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final Map<String, String> updatedDetails = new HashMap<>();
            _zoneDao.loadDetails(zone);
            if (zone.getDetails() != null) {
                updatedDetails.putAll(zone.getDetails());
            }
            updatedDetails.putAll(newDetails);
            zone.setDetails(updatedDetails);
            if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
                final AllocationState allocationState = AllocationState.valueOf(allocationStateStr);
                if (allocationState == AllocationState.Enabled) {
                    // check if zone has necessary trafficTypes before enabling
                    try {
                        final PhysicalNetwork mgmtPhyNetwork;
                        // zone should have a physical network with management
                        // traffiType
                        mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
                        if (NetworkType.Advanced == zone.getNetworkType()) {
                            // advanced zone should have a physical network with public type
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                        }
                        try {
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
                        } catch (final InvalidParameterValueException noStorage) {
                            final PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management);
                            _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), "vlan", mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVlan());
                            s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type");
                        }
                    } catch (final InvalidParameterValueException ex) {
                        throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage());
                    }
                }
                zone.setAllocationState(allocationState);
            }
            // update a private zone to public; not vice versa
            if (isPublic != null && isPublic) {
                zone.setDomainId(null);
                zone.setDomain(null);
                // release the dedication for this zone
                final DedicatedResourceVO resource = _dedicatedDao.findByZoneId(zoneId);
                final Long resourceId;
                if (resource != null) {
                    resourceId = resource.getId();
                    if (!_dedicatedDao.remove(resourceId)) {
                        throw new CloudRuntimeException("Failed to delete dedicated Zone Resource " + resourceId);
                    }
                    // find the group associated and check if there are any more
                    // resources under that group
                    final List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
                    if (resourcesInGroup.isEmpty()) {
                        // delete the group
                        _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null, null);
                    }
                }
            }
            if (!_zoneDao.update(zoneId, zone)) {
                throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support.");
            }
        }
    });
    return zone;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) AllocationState(com.cloud.model.enumeration.AllocationState) PhysicalNetwork(com.cloud.network.PhysicalNetwork) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) Map(java.util.Map) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 17 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method deleteVlanAndPublicIpRange.

@Override
@DB
public boolean deleteVlanAndPublicIpRange(final long userId, final long vlanDbId, final Account caller) {
    VlanVO vlanRange = _vlanDao.findById(vlanDbId);
    if (vlanRange == null) {
        throw new InvalidParameterValueException("Please specify a valid IP range id.");
    }
    boolean isAccountSpecific = false;
    final List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanRange.getId());
    // account_vlan_map.
    if (acctVln != null && !acctVln.isEmpty()) {
        isAccountSpecific = true;
    }
    final List<DomainVlanMapVO> domainVln = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanRange.getId());
    // Check for domain wide pool. It will have an entry for domain_vlan_map.
    if (domainVln != null && !domainVln.isEmpty()) {
    }
    // Check if the VLAN has any allocated public IPs
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    if (isAccountSpecific) {
        int resourceCountToBeDecrement = 0;
        try {
            vlanRange = _vlanDao.acquireInLockTable(vlanDbId, 30);
            if (vlanRange == null) {
                throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("lock vlan " + vlanDbId + " is acquired");
            }
            for (final IPAddressVO ip : ips) {
                boolean success = true;
                if (ip.isOneToOneNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first");
                }
                if (ip.isSourceNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
                }
                if (_firewallDao.countRulesByIpId(ip.getId()) > 0) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first");
                }
                if (ip.getAllocatedTime() != null) {
                    // This means IP is allocated
                    // release public ip address here
                    success = _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                }
                if (!success) {
                    s_logger.warn("Some ip addresses failed to be released as a part of vlan " + vlanDbId + " removal");
                } else {
                    resourceCountToBeDecrement++;
                }
            }
        } finally {
            _vlanDao.releaseFromLockTable(vlanDbId);
            if (resourceCountToBeDecrement > 0) {
                // Making sure to decrement the count of only success operations above. For any reaason if disassociation fails then this
                // number will vary from original range length.
                _resourceLimitMgr.decrementResourceCount(acctVln.get(0).getAccountId(), ResourceType.public_ip, new Long(resourceCountToBeDecrement));
            }
        }
    } else {
        // !isAccountSpecific
        final long allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
        if (allocIpCount > 0) {
            throw new InvalidParameterValueException(allocIpCount + "  Ips are in use. Cannot delete this vlan");
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            _publicIpAddressDao.deletePublicIPRange(vlanDbId);
            _vlanDao.remove(vlanDbId);
        }
    });
    return true;
}
Also used : AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 18 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class PublicNetworkGuru method deallocate.

@Override
@DB
public void deallocate(final Network network, final NicProfile nic, final VirtualMachineProfile vm) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("public network deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIPv4Address());
    }
    final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIPv4Address());
    if (ip != null && nic.getReservationStrategy() != ReservationStrategy.Managed) {
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                _ipAddrMgr.markIpAsUnavailable(ip.getId());
                _ipAddressDao.unassignIpAddress(ip.getId());
            }
        });
    }
    nic.deallocate();
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Deallocated nic: " + nic);
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 19 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method deleteLBHealthCheckPolicy.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_HEALTHCHECKPOLICY_DELETE, eventDescription = "revoking LB HealthCheck policy ", async = true)
public boolean deleteLBHealthCheckPolicy(final long healthCheckPolicyId, final boolean apply) {
    boolean success = true;
    final CallContext caller = CallContext.current();
    final LBHealthCheckPolicyVO healthCheckPolicy = _lb2healthcheckDao.findById(healthCheckPolicyId);
    if (healthCheckPolicy == null) {
        throw new InvalidParameterException("Invalid HealthCheck policy id value: " + healthCheckPolicyId);
    }
    final LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(healthCheckPolicy.getLoadBalancerId()));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid Load balancer : " + healthCheckPolicy.getLoadBalancerId() + " for HealthCheck policy id: " + healthCheckPolicyId);
    }
    final long loadBalancerId = loadBalancer.getId();
    final FirewallRule.State backupState = loadBalancer.getState();
    _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
    if (apply) {
        if (loadBalancer.getState() == FirewallRule.State.Active) {
            loadBalancer.setState(FirewallRule.State.Add);
            _lbDao.persist(loadBalancer);
        }
        final boolean backupStickyState = healthCheckPolicy.isRevoke();
        healthCheckPolicy.setRevoke(true);
        _lb2healthcheckDao.persist(healthCheckPolicy);
        s_logger.debug("Set health check policy to revoke for loadbalancing rule id : " + loadBalancerId + ", healthCheckpolicyID " + healthCheckPolicyId);
        // removing the state of services set by the monitor.
        final List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
        if (maps != null) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    s_logger.debug("Resetting health state policy for services in loadbalancing rule id : " + loadBalancerId);
                    for (final LoadBalancerVMMapVO map : maps) {
                        map.setState(null);
                        _lb2VmMapDao.persist(map);
                    }
                }
            });
        }
        try {
            if (!applyLoadBalancerConfig(loadBalancerId)) {
                s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
                throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
            }
        } catch (final ResourceUnavailableException e) {
            if (isRollBackAllowedForProvider(loadBalancer)) {
                healthCheckPolicy.setRevoke(backupStickyState);
                _lb2healthcheckDao.persist(healthCheckPolicy);
                loadBalancer.setState(backupState);
                _lbDao.persist(loadBalancer);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while deleting healthcheck policy: " + healthCheckPolicyId);
            }
            s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
            success = false;
        }
    } else {
        _lb2healthcheckDao.remove(healthCheckPolicy.getLoadBalancerId());
    }
    return success;
}
Also used : LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) LBHealthCheckPolicyVO(com.cloud.network.LBHealthCheckPolicyVO) CallContext(com.cloud.context.CallContext) InvalidParameterException(java.security.InvalidParameterException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 20 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class FirewallManagerImpl method revokeRule.

@Override
@DB
public void revokeRule(final FirewallRuleVO rule, final Account caller, final long userId, final boolean needUsageEvent) {
    if (caller != null) {
        _accountMgr.checkAccess(caller, null, true, rule);
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            if (rule.getState() == State.Staged) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
                }
                removeRule(rule);
            } else if (rule.getState() == State.Add || rule.getState() == State.Active) {
                rule.setState(State.Revoke);
                _firewallDao.update(rule.getId(), rule);
            }
        }
    });
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Aggregations

TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 TransactionStatus (com.cloud.utils.db.TransactionStatus)172 DB (com.cloud.utils.db.DB)133 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)71 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)60 ArrayList (java.util.ArrayList)57 ActionEvent (com.cloud.event.ActionEvent)42 List (java.util.List)42 Account (com.cloud.user.Account)39 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)38 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)36 ConfigurationException (javax.naming.ConfigurationException)32 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)26 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)24 IPAddressVO (com.cloud.network.dao.IPAddressVO)24 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)23 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)18 HostVO (com.cloud.host.HostVO)18 HashMap (java.util.HashMap)18 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)17