Search in sources :

Example 91 with TransactionCallbackNoReturn

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

the class RulesManagerImpl method reservePorts.

@Override
@DB
public FirewallRuleVO[] reservePorts(final IpAddress ip, final String protocol, final FirewallRule.Purpose purpose, final boolean openFirewall, final Account caller, final int... ports) throws NetworkRuleConflictException {
    final FirewallRuleVO[] rules = new FirewallRuleVO[ports.length];
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<NetworkRuleConflictException>() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) throws NetworkRuleConflictException {
            for (int i = 0; i < ports.length; i++) {
                rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null);
                rules[i] = _firewallDao.persist(rules[i]);
                if (openFirewall) {
                    _firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId(), ip.getAssociatedWithNetworkId());
                }
            }
        }
    });
    boolean success = false;
    try {
        for (FirewallRuleVO newRule : rules) {
            _firewallMgr.detectRulesConflict(newRule);
        }
        success = true;
        return rules;
    } finally {
        if (!success) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    for (FirewallRuleVO newRule : rules) {
                        _firewallMgr.removeRule(newRule);
                    }
                }
            });
        }
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) DB(com.cloud.utils.db.DB)

Example 92 with TransactionCallbackNoReturn

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

the class SecurityGroupManagerImpl method work.

@DB
public void work() {
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Checking the database");
    }
    final SecurityGroupWorkVO work = _workDao.take(_serverId);
    if (work == null) {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Security Group work: no work found");
        }
        return;
    }
    final Long userVmId = work.getInstanceId();
    if (work.getStep() == Step.Done) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Security Group work: found a job in done state, rescheduling for vm: " + userVmId);
        }
        ArrayList<Long> affectedVms = new ArrayList<Long>();
        affectedVms.add(userVmId);
        scheduleRulesetUpdateToHosts(affectedVms, false, _timeBetweenCleanups * 1000l);
        return;
    }
    s_logger.debug("Working on " + work);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            UserVm vm = null;
            Long seqnum = null;
            boolean locked = false;
            try {
                vm = _userVMDao.acquireInLockTable(work.getInstanceId());
                if (vm == null) {
                    vm = _userVMDao.findById(work.getInstanceId());
                    if (vm == null) {
                        s_logger.info("VM " + work.getInstanceId() + " is removed");
                        locked = true;
                        return;
                    }
                    s_logger.warn("Unable to acquire lock on vm id=" + userVmId);
                    return;
                }
                locked = true;
                Long agentId = null;
                VmRulesetLogVO log = _rulesetLogDao.findByVmId(userVmId);
                if (log == null) {
                    s_logger.warn("Cannot find log record for vm id=" + userVmId);
                    return;
                }
                seqnum = log.getLogsequence();
                if (vm != null && vm.getState() == State.Running) {
                    Map<PortAndProto, Set<String>> ingressRules = generateRulesForVM(userVmId, SecurityRuleType.IngressRule);
                    Map<PortAndProto, Set<String>> egressRules = generateRulesForVM(userVmId, SecurityRuleType.EgressRule);
                    agentId = vm.getHostId();
                    if (agentId != null) {
                        // get nic secondary ip address
                        String privateIp = vm.getPrivateIpAddress();
                        NicVO nic = _nicDao.findByIp4AddressAndVmId(privateIp, vm.getId());
                        List<String> nicSecIps = null;
                        if (nic != null) {
                            if (nic.getSecondaryIp()) {
                                //get secondary ips of the vm
                                long networkId = nic.getNetworkId();
                                nicSecIps = _nicSecIpDao.getSecondaryIpAddressesForNic(nic.getId());
                            }
                        }
                        SecurityGroupRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), nic.getIPv6Address(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(ingressRules, egressRules), seqnum, ingressRules, egressRules, nicSecIps);
                        Commands cmds = new Commands(cmd);
                        try {
                            _agentMgr.send(agentId, cmds, _answerListener);
                        } catch (AgentUnavailableException e) {
                            s_logger.debug("Unable to send ingress rules updates for vm: " + userVmId + "(agentid=" + agentId + ")");
                            _workDao.updateStep(work.getInstanceId(), seqnum, Step.Done);
                        }
                    }
                }
            } finally {
                if (locked) {
                    _userVMDao.releaseFromLockTable(userVmId);
                    _workDao.updateStep(work.getId(), Step.Done);
                }
            }
        }
    });
}
Also used : SecurityGroupRulesCmd(com.cloud.agent.api.SecurityGroupRulesCmd) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UserVm(com.cloud.uservm.UserVm) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) Commands(com.cloud.agent.manager.Commands) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) NicVO(com.cloud.vm.NicVO) DB(com.cloud.utils.db.DB)

Example 93 with TransactionCallbackNoReturn

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

the class UserVmManagerImpl method finalizeStart.

@Override
public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Commands cmds, ReservationContext context) {
    UserVmVO vm = _vmDao.findById(profile.getId());
    Answer[] answersToCmds = cmds.getAnswers();
    if (answersToCmds == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Returning from finalizeStart() since there are no answers to read");
        }
        return true;
    }
    Answer startAnswer = cmds.getAnswer(StartAnswer.class);
    String returnedIp = null;
    String originalIp = null;
    if (startAnswer != null) {
        StartAnswer startAns = (StartAnswer) startAnswer;
        VirtualMachineTO vmTO = startAns.getVirtualMachine();
        for (NicTO nicTO : vmTO.getNics()) {
            if (nicTO.getType() == TrafficType.Guest) {
                returnedIp = nicTO.getIp();
            }
        }
    }
    List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    NicVO guestNic = null;
    NetworkVO guestNetwork = null;
    for (NicVO nic : nics) {
        NetworkVO network = _networkDao.findById(nic.getNetworkId());
        long isDefault = (nic.isDefaultNic()) ? 1 : 0;
        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
        if (network.getTrafficType() == TrafficType.Guest) {
            originalIp = nic.getIPv4Address();
            guestNic = nic;
            guestNetwork = network;
            // In vmware, we will be effecting pvlan settings in portgroups in StartCommand.
            if (profile.getHypervisorType() != HypervisorType.VMware) {
                if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
                    NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
                    if (!setupVmForPvlan(true, hostId, nicProfile)) {
                        return false;
                    }
                }
            }
        }
    }
    boolean ipChanged = false;
    if (originalIp != null && !originalIp.equalsIgnoreCase(returnedIp)) {
        if (returnedIp != null && guestNic != null) {
            guestNic.setIPv4Address(returnedIp);
            ipChanged = true;
        }
    }
    if (returnedIp != null && !returnedIp.equalsIgnoreCase(originalIp)) {
        if (guestNic != null) {
            guestNic.setIPv4Address(returnedIp);
            ipChanged = true;
        }
    }
    if (ipChanged) {
        _dcDao.findById(vm.getDataCenterId());
        UserVmVO userVm = _vmDao.findById(profile.getId());
        // dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())
        if (_ntwkSrvcDao.canProviderSupportServiceInNetwork(guestNetwork.getId(), Service.Dhcp, Provider.ExternalDhcpServer)) {
            _nicDao.update(guestNic.getId(), guestNic);
            userVm.setPrivateIpAddress(guestNic.getIPv4Address());
            _vmDao.update(userVm.getId(), userVm);
            s_logger.info("Detected that ip changed in the answer, updated nic in the db with new ip " + returnedIp);
        }
    }
    // get system ip and create static nat rule for the vm
    try {
        _rulesMgr.getSystemIpAndEnableStaticNatForVm(profile.getVirtualMachine(), false);
    } catch (Exception ex) {
        s_logger.warn("Failed to get system ip and enable static nat for the vm " + profile.getVirtualMachine() + " due to exception ", ex);
        return false;
    }
    Answer answer = cmds.getAnswer("restoreVMSnapshot");
    if (answer != null && answer instanceof RestoreVMSnapshotAnswer) {
        RestoreVMSnapshotAnswer restoreVMSnapshotAnswer = (RestoreVMSnapshotAnswer) answer;
        if (restoreVMSnapshotAnswer == null || !restoreVMSnapshotAnswer.getResult()) {
            s_logger.warn("Unable to restore the vm snapshot from image file to the VM: " + restoreVMSnapshotAnswer.getDetails());
        }
    }
    final VirtualMachineProfile vmProfile = profile;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            final UserVmVO vm = _vmDao.findById(vmProfile.getId());
            final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
            for (NicVO nic : nics) {
                Network network = _networkModel.getNetwork(nic.getNetworkId());
                if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
                    vmIdCountMap.put(nic.getId(), new VmAndCountDetails(nic.getInstanceId(), VmIpFetchTrialMax.value()));
                }
            }
        }
    });
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) StartAnswer(com.cloud.agent.api.StartAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) GetVmStatsAnswer(com.cloud.agent.api.GetVmStatsAnswer) Answer(com.cloud.agent.api.Answer) StartAnswer(com.cloud.agent.api.StartAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) NicTO(com.cloud.agent.api.to.NicTO)

Aggregations

TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)93 TransactionStatus (com.cloud.utils.db.TransactionStatus)93 DB (com.cloud.utils.db.DB)73 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)50 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)34 ArrayList (java.util.ArrayList)30 List (java.util.List)21 ActionEvent (com.cloud.event.ActionEvent)20 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 Account (com.cloud.user.Account)18 ConfigurationException (javax.naming.ConfigurationException)15 IPAddressVO (com.cloud.network.dao.IPAddressVO)14 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)11 Network (com.cloud.network.Network)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)9 HostVO (com.cloud.host.HostVO)9 HashMap (java.util.HashMap)9 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)8 DataCenter (com.cloud.dc.DataCenter)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7