Search in sources :

Example 16 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class ActionEventUtils method publishOnEventBus.

private static void publishOnEventBus(long userId, long accountId, String eventCategory, String eventType, Event.State state, String description) {
    String configKey = Config.PublishActionEvent.key();
    String value = s_configDao.getValue(configKey);
    boolean configValue = Boolean.parseBoolean(value);
    if (!configValue)
        return;
    try {
        s_eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    // get the entity details for which ActionEvent is generated
    String entityType = null;
    String entityUuid = null;
    CallContext context = CallContext.current();
    //Get entity Class(Example - VirtualMachine.class) from the event Type eg. - VM.CREATE
    Class<?> entityClass = EventTypes.getEntityClassForEvent(eventType);
    if (entityClass != null) {
        //Get uuid from id
        Object param = context.getContextParameter(entityClass);
        if (param != null) {
            try {
                entityUuid = getEntityUuid(entityClass, param);
                entityType = entityClass.getName();
            } catch (Exception e) {
                s_logger.debug("Caught exception while finding entityUUID, moving on");
            }
        }
    }
    org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, EventTypes.getEntityForEvent(eventType), entityUuid);
    Map<String, String> eventDescription = new HashMap<String, String>();
    Project project = s_projectDao.findByProjectAccountId(accountId);
    Account account = s_accountDao.findById(accountId);
    User user = s_userDao.findById(userId);
    // if account has been deleted, this might be called during cleanup of resources and results in null pointer
    if (account == null)
        return;
    if (user == null)
        return;
    if (project != null)
        eventDescription.put("project", project.getUuid());
    eventDescription.put("user", user.getUuid());
    eventDescription.put("account", account.getUuid());
    eventDescription.put("event", eventType);
    eventDescription.put("status", state.toString());
    eventDescription.put("entity", entityType);
    eventDescription.put("entityuuid", entityUuid);
    //Put all the first class entities that are touched during the action. For now atleast put in the vmid.
    populateFirstClassEntities(eventDescription);
    eventDescription.put("description", description);
    String eventDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    eventDescription.put("eventDateTime", eventDate);
    event.setDescription(eventDescription);
    try {
        s_eventBus.publish(event);
    } catch (EventBusException e) {
        s_logger.warn("Failed to publish action event on the the event bus.");
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) HashMap(java.util.HashMap) EventBus(org.apache.cloudstack.framework.events.EventBus) CallContext(org.apache.cloudstack.context.CallContext) EventBusException(org.apache.cloudstack.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Date(java.util.Date) Project(com.cloud.projects.Project) EventBusException(org.apache.cloudstack.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 17 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class RulesManagerImpl method revokePortForwardingRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true)
public boolean revokePortForwardingRule(long ruleId, boolean apply) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    PortForwardingRuleVO rule = _portForwardingDao.findById(ruleId);
    if (rule == null) {
        throw new InvalidParameterValueException("Unable to find " + ruleId);
    }
    _accountMgr.checkAccess(caller, null, true, rule);
    if (!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallingUserId(), apply)) {
        throw new CloudRuntimeException("Failed to delete port forwarding rule");
    }
    return true;
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CallContext(org.apache.cloudstack.context.CallContext) ActionEvent(com.cloud.event.ActionEvent)

Example 18 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class RulesManagerImpl method revokeStaticNatRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true)
public boolean revokeStaticNatRule(long ruleId, boolean apply) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    FirewallRuleVO rule = _firewallDao.findById(ruleId);
    if (rule == null) {
        throw new InvalidParameterValueException("Unable to find " + ruleId);
    }
    _accountMgr.checkAccess(caller, null, true, rule);
    if (!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallingUserId(), apply)) {
        throw new CloudRuntimeException("Failed to revoke forwarding rule");
    }
    return true;
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CallContext(org.apache.cloudstack.context.CallContext) ActionEvent(com.cloud.event.ActionEvent)

Example 19 with CallContext

use of org.apache.cloudstack.context.CallContext 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);
                    } 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)) {
                // 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) 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)

Example 20 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method removeVmFromNetworkThroughJobQueue.

public Outcome<VirtualMachine> removeVmFromNetworkThroughJobQueue(final VirtualMachine vm, final Network network, final URI broadcastUri) {
    final CallContext context = CallContext.current();
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkRemoveVmFromNetwork.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, broadcastUri);
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vm.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Aggregations

CallContext (org.apache.cloudstack.context.CallContext)76 Account (com.cloud.user.Account)45 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)29 User (com.cloud.user.User)26 ActionEvent (com.cloud.event.ActionEvent)22 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)22 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)21 DB (com.cloud.utils.db.DB)13 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)12 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 FirewallRule (com.cloud.network.rules.FirewallRule)8 ArrayList (java.util.ArrayList)8 ServerApiException (org.apache.cloudstack.api.ServerApiException)8 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)7 Network (com.cloud.network.Network)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)6 DeployDestination (com.cloud.deploy.DeployDestination)5 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)5 IPAddressVO (com.cloud.network.dao.IPAddressVO)5