Search in sources :

Example 1 with CloudException

use of com.cloud.legacymodel.exceptions.CloudException in project cosmic by MissionCriticalCloud.

the class PrivateGatewayRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    boolean result = false;
    try {
        final NetworkModel networkModel = visitor.getVirtualNetworkApplianceFactory().getNetworkModel();
        _network = networkModel.getNetwork(_privateGateway.getNetworkId());
        final NicProfileHelper nicProfileHelper = visitor.getVirtualNetworkApplianceFactory().getNicProfileHelper();
        final NicProfile requested = nicProfileHelper.createPrivateNicProfileForGateway(_privateGateway, _router);
        final NetworkHelper networkHelper = visitor.getVirtualNetworkApplianceFactory().getNetworkHelper();
        if (!networkHelper.checkRouterVersion(_router)) {
            s_logger.warn("Router requires upgrade. Unable to send command to router: " + _router.getId());
            return false;
        }
        final VirtualMachineManager itMgr = visitor.getVirtualNetworkApplianceFactory().getItMgr();
        _nicProfile = itMgr.addVmToNetwork(_router, _network, requested);
        // setup source nat
        if (_nicProfile != null) {
            _isAddOperation = true;
            result = visitor.visit(this);
        }
    } catch (final CloudException ex) {
        s_logger.error("Failed to create private gateway " + _privateGateway + " on router " + _router + " due to ", ex);
        result = false;
    } finally {
        if (!result) {
            s_logger.debug("Failed to setup gateway " + _privateGateway + " on router " + _router + " with the source nat. Will now remove the gateway.");
            _isAddOperation = false;
            final boolean isRemoved = destroyPrivateGateway(visitor);
            if (isRemoved) {
                s_logger.debug("Removed the gateway " + _privateGateway + " from router " + _router + " as a part of cleanup");
            } else {
                s_logger.warn("Failed to remove the gateway " + _privateGateway + " from router " + _router + " as a part of cleanup");
            }
        }
    }
    return result;
}
Also used : NetworkModel(com.cloud.network.NetworkModel) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) NicProfileHelper(com.cloud.network.router.NicProfileHelper) CloudException(com.cloud.legacymodel.exceptions.CloudException) NicProfile(com.cloud.vm.NicProfile) NetworkHelper(com.cloud.network.router.NetworkHelper)

Example 2 with CloudException

use of com.cloud.legacymodel.exceptions.CloudException in project cosmic by MissionCriticalCloud.

the class VmWorkJobHandlerProxy method handleVmWorkJob.

@Override
public Pair<JobInfo.Status, String> handleVmWorkJob(final VmWork work) throws CloudException {
    final Method method = getHandlerMethod(work.getClass());
    if (method != null) {
        try {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Execute VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
            }
            final Object obj = method.invoke(_target, work);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Done executing VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
            }
            assert (obj instanceof Pair);
            return (Pair<JobInfo.Status, String>) obj;
        } catch (final InvocationTargetException e) {
            final Throwable cause = e.getCause();
            s_logger.error("Invocation exception, caused by: " + cause);
            // we need to re-throw the real exception here
            if (cause != null && cause instanceof Exception) {
                s_logger.info("Rethrow exception " + cause);
                throw new CloudException("Caught exception while handling a VmWorkJob", cause);
            }
            throw new CloudException("Caught exception while handling a VmWorkJob", e);
        } catch (final IllegalAccessException e) {
            throw new CloudException("Caught exception while handling a VmWorkJob", e);
        }
    } else {
        s_logger.error("Unable to find handler for VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work));
        final RuntimeException ex = new RuntimeException("Unable to find handler for VM work job: " + work.getClass().getName());
        return new Pair<>(JobInfo.Status.FAILED, JobSerializerHelper.toObjectSerializedString(ex));
    }
}
Also used : JobInfo(com.cloud.jobs.JobInfo) Method(java.lang.reflect.Method) CloudException(com.cloud.legacymodel.exceptions.CloudException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CloudException(com.cloud.legacymodel.exceptions.CloudException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Pair(com.cloud.legacymodel.utils.Pair)

Example 3 with CloudException

use of com.cloud.legacymodel.exceptions.CloudException 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.legacymodel.exceptions.CloudException) CallContext(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) Project(com.cloud.projects.Project) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) DispatchTask(com.cloud.api.dispatch.DispatchTask)

Example 4 with CloudException

use of com.cloud.legacymodel.exceptions.CloudException 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.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) ExceptionResponse(com.cloud.api.response.ExceptionResponse) Gson(com.google.gson.Gson) CloudException(com.cloud.legacymodel.exceptions.CloudException) CallContext(com.cloud.context.CallContext) Type(java.lang.reflect.Type) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Map(java.util.Map)

Example 5 with CloudException

use of com.cloud.legacymodel.exceptions.CloudException in project cosmic by MissionCriticalCloud.

the class NetworkHelperImpl method startVirtualRouter.

@Override
public DomainRouterVO startVirtualRouter(final DomainRouterVO router, final User user, final Account caller, final Map<Param, Object> params) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
    logger.info("Starting Virtual Router {}", router);
    if (router.getState() == State.Running) {
        logger.debug("Redundant router {} is already running!", router);
        return router;
    }
    // We will wait until VR is up or fail
    if (router.getState() == State.Starting) {
        return waitRouter(router);
    }
    final DataCenterDeployment plan = new DataCenterDeployment(0, null, null, null, null, null);
    final List<Long> networkIds = _routerDao.getRouterNetworks(router.getId());
    DomainRouterVO routerToBeAvoid = null;
    List<DomainRouterVO> routerList = null;
    if (router.getVpcId() != null) {
        routerList = _routerDao.listByVpcId(router.getVpcId());
    } else if (networkIds.size() != 0) {
        routerList = _routerDao.findByNetwork(networkIds.get(0));
    }
    if (routerList != null) {
        for (final DomainRouterVO rrouter : routerList) {
            if (rrouter.getHostId() != null && rrouter.getIsRedundantRouter() && rrouter.getState() == State.Running) {
                if (routerToBeAvoid != null) {
                    throw new ResourceUnavailableException("Try to start router " + router.getInstanceName() + "(" + router.getId() + ")" + ", but there are already two redundant routers with IP " + router.getPublicIpAddress() + ", they are " + rrouter.getInstanceName() + "(" + rrouter.getId() + ") and " + routerToBeAvoid.getInstanceName() + "(" + routerToBeAvoid.getId() + ")", DataCenter.class, rrouter.getDataCenterId());
                }
                routerToBeAvoid = rrouter;
            }
        }
    }
    // Look for dedication
    List<Long> dedicatedAvoidSet = _dedicatedDao.listAllHosts();
    final AffinityGroup affinityGroup = findDedicatedAffinityGroup(router.getDomainId(), router.getAccountId());
    if (affinityGroup != null) {
        logger.debug("Found affinity group: " + affinityGroup + " for domainId " + router.getDomainId() + " and/or accountId " + router.getAccountId());
        // All hosts in zone
        final List<Long> allHostsInDc = _hostDao.listAllHosts(router.getDataCenterId());
        logger.debug("All hosts: " + allHostsInDc);
        // All dedicated ones
        final List<Long> allDedicatedHosts = _dedicatedDao.listAllHosts();
        logger.debug("All dedicated hosts: " + allDedicatedHosts);
        // All non-decicated ones need to be in avoid set
        allHostsInDc.removeAll(allDedicatedHosts);
        dedicatedAvoidSet = allHostsInDc;
    }
    logger.debug("All hosts to avoid: " + dedicatedAvoidSet);
    // We would try best to deploy the router to another place
    final ExcludeList[] avoids = getExcludeLists(routerToBeAvoid, dedicatedAvoidSet);
    logger.debug("Will start to deploy router {} with the most strict avoidance rules first (total number of attempts = {})", router, avoids.length);
    DomainRouterVO result = null;
    for (int i = 0; i < avoids.length; i++) {
        plan.setAvoids(avoids[i]);
        try {
            logger.debug("Starting router {} while trying to {}", router, avoids[i]);
            result = start(router, params, plan);
        } catch (final CloudException | CloudRuntimeException e) {
            logger.debug("Failed to start virtual router {} while trying to {} ({} attempts to go)", router, avoids[i], avoids.length - i);
            result = null;
        }
        if (result != null) {
            break;
        }
    }
    return result;
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) CloudException(com.cloud.legacymodel.exceptions.CloudException) AffinityGroup(com.cloud.affinity.AffinityGroup) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Aggregations

CloudException (com.cloud.legacymodel.exceptions.CloudException)8 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)4 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)4 VirtualMachineEntity (com.cloud.engine.cloud.entity.api.VirtualMachineEntity)3 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)3 CallContext (com.cloud.context.CallContext)2 Account (com.cloud.legacymodel.user.Account)2 AffinityGroup (com.cloud.affinity.AffinityGroup)1 DispatchTask (com.cloud.api.dispatch.DispatchTask)1 ExceptionResponse (com.cloud.api.response.ExceptionResponse)1 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)1 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)1 ActionEvent (com.cloud.event.ActionEvent)1 JobInfo (com.cloud.jobs.JobInfo)1 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)1 NetworkRuleConflictException (com.cloud.legacymodel.exceptions.NetworkRuleConflictException)1 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)1 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)1 ResourceState (com.cloud.legacymodel.resource.ResourceState)1 User (com.cloud.legacymodel.user.User)1