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;
}
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));
}
}
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);
}
}
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));
}
}
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;
}
Aggregations