Search in sources :

Example 61 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateAddVmToNetwork.

private NicProfile orchestrateAddVmToNetwork(final VirtualMachine vm, final Network network, final NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final CallContext cctx = CallContext.current();
    s_logger.debug("Orchestrating add vm " + vm + " to network " + network + " with requested nic profile " + requested);
    final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
    final Zone zone = _zoneRepository.findOne(network.getDataCenterId());
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(zone, null, null, host);
    // check vm state
    if (vm.getState() == State.Running) {
        // 1) allocate and prepare nic
        final NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true);
        // 2) Convert vmProfile to vmTO
        final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
        final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
        // 3) Convert nicProfile to NicTO
        final NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType());
        // 4) plug the nic to the vm
        s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
        boolean result = false;
        try {
            result = plugNic(network, nicTO, vmTO, context, dest);
            if (result) {
                s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm  is a part of network now");
                final long isDefault = nic.isDefaultNic() ? 1 : 0;
                // insert nic's Id into DB as resource_name
                return nic;
            } else {
                s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
                return null;
            }
        } finally {
            if (!result) {
                s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
                _networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
            }
        }
    } else if (vm.getState() == State.Stopped) {
        // 1) allocate nic
        return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
    } else {
        s_logger.warn("Unable to add vm " + vm + " to network  " + network);
        throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
    }
}
Also used : Zone(com.cloud.db.model.Zone) TimeZone(java.util.TimeZone) Host(com.cloud.host.Host) CallContext(com.cloud.context.CallContext) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DataCenter(com.cloud.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NicTO(com.cloud.agent.api.to.NicTO)

Example 62 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method addVmToNetworkThroughJobQueue.

public Outcome<VirtualMachine> addVmToNetworkThroughJobQueue(final VirtualMachine vm, final Network network, final NicProfile requested) {
    final CallContext context = CallContext.current();
    s_logger.info("Orchestrating add vm " + vm + " to network " + network + " with requested nic profile " + requested + " via job queue");
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final VmWorkJobVO workJob = fetchOrCreateVmWorkJob(vm, network, requested, context, user, account);
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vm.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(com.cloud.context.CallContext) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO)

Example 63 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class CreatePortForwardingRuleCmd method execute.

// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException {
    final CallContext callerContext = CallContext.current();
    boolean success = true;
    PortForwardingRule rule = null;
    try {
        CallContext.current().setEventDetails("Rule Id: " + getEntityId());
        if (getOpenFirewall()) {
            success = success && _firewallService.applyIngressFirewallRules(ipAddressId, callerContext.getCallingAccount());
        }
        success = success && _rulesService.applyPortForwardingRules(ipAddressId, callerContext.getCallingAccount());
        // State is different after the rule is applied, so get new object here
        rule = _entityMgr.findById(PortForwardingRule.class, getEntityId());
        FirewallRuleResponse fwResponse = new FirewallRuleResponse();
        if (rule != null) {
            fwResponse = _responseGenerator.createPortForwardingRuleResponse(rule);
            setResponseObject(fwResponse);
        }
        fwResponse.setResponseName(getCommandName());
    } finally {
        if (!success || rule == null) {
            if (getOpenFirewall()) {
                _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
            }
            try {
                _rulesService.revokePortForwardingRule(getEntityId(), true);
            } catch (final Exception ex) {
            // Ignore e.g. failed to apply rules to device error
            }
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to apply port forwarding rule");
        }
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) CallContext(com.cloud.context.CallContext) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) FirewallRuleResponse(com.cloud.api.response.FirewallRuleResponse) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ServerApiException(com.cloud.api.ServerApiException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException)

Example 64 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class ApiAsyncJobDispatcher method runJob.

@Override
public void runJob(final AsyncJob job) {
    BaseAsyncCmd cmdObj = null;
    try {
        final Class<?> cmdClass = Class.forName(job.getCmd());
        cmdObj = (BaseAsyncCmd) cmdClass.newInstance();
        cmdObj = ComponentContext.inject(cmdObj);
        cmdObj.configure();
        cmdObj.setJob(job);
        final Type mapType = new TypeToken<Map<String, String>>() {
        }.getType();
        final Gson gson = ApiGsonHelper.getBuilder().create();
        final Map<String, String> params = gson.fromJson(job.getCmdInfo(), mapType);
        // whenever we deserialize, the UserContext needs to be updated
        final String userIdStr = params.get("ctxUserId");
        final String acctIdStr = params.get("ctxAccountId");
        final String contextDetails = params.get("ctxDetails");
        final Long userId;
        Account accountObject = null;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            final BaseAsyncCreateCmd create = (BaseAsyncCreateCmd) cmdObj;
            create.setEntityId(Long.parseLong(params.get("id")));
            create.setEntityUuid(params.get("uuid"));
        }
        User user = null;
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
            user = _entityMgr.findById(User.class, userId);
        }
        if (acctIdStr != null) {
            accountObject = _entityMgr.findById(Account.class, Long.parseLong(acctIdStr));
        }
        final CallContext ctx = CallContext.register(user, accountObject);
        if (contextDetails != null) {
            final Type objectMapType = new TypeToken<Map<Object, Object>>() {
            }.getType();
            ctx.putContextParameters((Map<Object, Object>) gson.fromJson(contextDetails, objectMapType));
        }
        try {
            // dispatch could ultimately queue the job
            _dispatcher.dispatch(cmdObj, params, true);
            // serialize this to the async job table
            _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, ApiSerializerHelper.toSerializedString(cmdObj.getResponseObject()));
        } catch (final InvalidParameterValueException | CloudException e) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.getMessage());
        } finally {
            CallContext.unregister();
        }
    } catch (IllegalAccessException | InstantiationException | ClassNotFoundException | ServerApiException e) {
        final String errorMsg = ExceptionUtils.getRootCauseMessage(e);
        final int errorCode = ApiErrorCode.INTERNAL_ERROR.getHttpCode();
        final ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode(errorCode);
        response.setErrorText(errorMsg);
        response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName());
        // FIXME:  setting resultCode to ApiErrorCode.INTERNAL_ERROR is not right, usually executors have their exception handling
        // and we need to preserve that as much as possible here
        _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), ApiSerializerHelper.toSerializedString(response));
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) ExceptionResponse(com.cloud.api.response.ExceptionResponse) Gson(com.google.gson.Gson) CloudException(com.cloud.exception.CloudException) CallContext(com.cloud.context.CallContext) Type(java.lang.reflect.Type) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Map(java.util.Map)

Example 65 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class ApiDispatcher method dispatch.

public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws CloudException {
    // Let the chain of responsibility dispatch gradually
    standardDispatchChain.dispatch(new DispatchTask(cmd, params));
    final CallContext ctx = CallContext.current();
    ctx.setEventDisplayEnabled(cmd.isDisplay());
    if (params.get(ApiConstants.PROJECT_ID) != null) {
        final Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
        ctx.setProject(project);
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCmd) {
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
        final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
        ctx.setStartEventId(Long.parseLong(startEventId));
        // Synchronise job on the object if needed
        if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
            final Long queueSizeLimit;
            if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
                queueSizeLimit = _createSnapshotQueueSizeLimit;
            } else {
                queueSizeLimit = 1L;
            }
            if (queueSizeLimit != null) {
                if (!execute) {
                    // if we are not within async-execution context, enqueue the command
                    _asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
                    return;
                }
            } else {
                s_logger.trace("The queue size is unlimited, skipping the synchronizing");
            }
        }
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCustomIdCmd) {
        ((BaseAsyncCustomIdCmd) cmd).checkUuid();
    } else if (cmd instanceof BaseCustomIdCmd) {
        ((BaseCustomIdCmd) cmd).checkUuid();
    }
    try {
        cmd.execute();
    } catch (ResourceUnavailableException | InsufficientCapacityException | ResourceAllocationException | NetworkRuleConflictException e) {
        throw new CloudException("Caught exception while executing command", e);
    }
}
Also used : CloudException(com.cloud.exception.CloudException) CallContext(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) Project(com.cloud.projects.Project) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) DispatchTask(com.cloud.api.dispatch.DispatchTask)

Aggregations

CallContext (com.cloud.context.CallContext)72 Account (com.cloud.user.Account)41 User (com.cloud.user.User)26 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)26 VmWorkJobVO (com.cloud.framework.jobs.impl.VmWorkJobVO)22 ActionEvent (com.cloud.event.ActionEvent)20 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)19 DB (com.cloud.utils.db.DB)12 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)10 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)9 ServerApiException (com.cloud.api.ServerApiException)8 FirewallRule (com.cloud.network.rules.FirewallRule)8 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)6 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)6 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)6 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)6 Network (com.cloud.network.Network)6 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)5