use of com.sequenceiq.cloudbreak.common.exception.BadRequestException in project cloudbreak by hortonworks.
the class StackOperationService method isStopNeeded.
private boolean isStopNeeded(Stack stack) {
boolean result = true;
StopRestrictionReason reason = stackStopRestrictionService.isInfrastructureStoppable(stack);
if (stack.isStopped()) {
eventService.fireCloudbreakEvent(stack.getId(), STOPPED.name(), STACK_STOP_IGNORED);
result = false;
} else if (reason != StopRestrictionReason.NONE) {
throw new BadRequestException(format("Cannot stop a stack '%s'. Reason: %s", stack.getName(), reason.getReason()));
} else if (!stack.isAvailable() && !stack.isStopFailed() && !stack.isAvailableWithStoppedInstances() && !stack.hasNodeFailure()) {
throw NotAllowedStatusUpdate.stack(stack).to(STOPPED).badRequest();
}
return result;
}
use of com.sequenceiq.cloudbreak.common.exception.BadRequestException in project cloudbreak by hortonworks.
the class StackOperationService method updateNodeCountStartInstances.
public FlowIdentifier updateNodeCountStartInstances(Stack stack, InstanceGroupAdjustmentV4Request instanceGroupAdjustmentJson, boolean withClusterEvent, ScalingStrategy scalingStrategy) {
if (instanceGroupAdjustmentJson.getScalingAdjustment() == 0) {
throw new BadRequestException("Attempting to upscale zero instances");
}
if (instanceGroupAdjustmentJson.getScalingAdjustment() < 0) {
throw new BadRequestException("Attempting to downscale via the start instances method. (File a bug)");
}
environmentService.checkEnvironmentStatus(stack, EnvironmentStatus.upscalable());
try {
return transactionService.required(() -> {
Stack stackWithLists = stackService.getByIdWithLists(stack.getId());
updateNodeCountValidator.validateServiceRoles(stackWithLists, instanceGroupAdjustmentJson);
updateNodeCountValidator.validateStackStatusForStartHostGroup(stackWithLists);
updateNodeCountValidator.validateInstanceGroup(stackWithLists, instanceGroupAdjustmentJson.getInstanceGroup());
updateNodeCountValidator.validateInstanceGroupForStopStart(stackWithLists, instanceGroupAdjustmentJson.getInstanceGroup(), instanceGroupAdjustmentJson.getScalingAdjustment());
updateNodeCountValidator.validateScalabilityOfInstanceGroup(stackWithLists, instanceGroupAdjustmentJson);
updateNodeCountValidator.validateScalingAdjustment(instanceGroupAdjustmentJson, stackWithLists);
if (withClusterEvent) {
updateNodeCountValidator.validateClusterStatusForStartHostGroup(stackWithLists);
updateNodeCountValidator.validateHostGroupIsPresent(instanceGroupAdjustmentJson, stackWithLists);
updateNodeCountValidator.validateCMStatus(stackWithLists, instanceGroupAdjustmentJson);
}
stackUpdater.updateStackStatus(stackWithLists.getId(), DetailedStackStatus.UPSCALE_BY_START_REQUESTED, "Requested node count for upscaling (stopstart): " + instanceGroupAdjustmentJson.getScalingAdjustment());
return flowManager.triggerStopStartStackUpscale(stackWithLists.getId(), instanceGroupAdjustmentJson, withClusterEvent);
});
} catch (TransactionExecutionException e) {
if (e.getCause() instanceof BadRequestException) {
throw e.getCause();
}
throw new TransactionRuntimeExecutionException(e);
}
}
use of com.sequenceiq.cloudbreak.common.exception.BadRequestException in project cloudbreak by hortonworks.
the class RequestPropertyAuthorizationFactory method calcAuthorization.
private Optional<AuthorizationRule> calcAuthorization(Object resourceObject, CheckPermissionByRequestProperty methodAnnotation, String userCrn) {
boolean skipOnNull = methodAnnotation.skipOnNull();
try {
Object fieldObject = PropertyUtils.getProperty(resourceObject, methodAnnotation.path());
AuthorizationVariableType authorizationVariableType = methodAnnotation.type();
AuthorizationResourceAction action = methodAnnotation.action();
if (fieldObject != null) {
return calcAuthorizationFromObject(action, authorizationVariableType, fieldObject, userCrn);
} else if (!methodAnnotation.skipOnNull()) {
throw new BadRequestException(String.format("Property [%s] of the request object must not be null.", methodAnnotation.path()));
}
} catch (NestedNullException nne) {
if (!skipOnNull) {
throw new BadRequestException(String.format("Property [%s] of the request object must not be null.", methodAnnotation.path()));
}
} catch (NotFoundException nfe) {
LOGGER.warn("Resource not found during permission check of resource object, this should be handled by microservice.");
} catch (Error | RuntimeException unchecked) {
LOGGER.error("Error happened during authorization of the request object: ", unchecked);
throw unchecked;
} catch (Throwable t) {
LOGGER.error("Error happened during authorization of the request object: ", t);
throw new AccessDeniedException("Error happened during authorization of the request object, thus access is denied!", t);
}
return Optional.empty();
}
use of com.sequenceiq.cloudbreak.common.exception.BadRequestException in project cloudbreak by hortonworks.
the class StackCreatorService method createStack.
public StackV4Response createStack(User user, Workspace workspace, StackV4Request stackRequest, boolean distroxRequest) {
long start = System.currentTimeMillis();
String stackName = stackRequest.getName();
nodeCountLimitValidator.validateProvision(stackRequest);
measure(() -> validateRecipeExistenceOnInstanceGroups(stackRequest.getInstanceGroups(), workspace.getId()), LOGGER, "Check that recipes do exist took {} ms");
measure(() -> ensureStackDoesNotExists(stackName, workspace), LOGGER, "Stack does not exist check took {} ms");
Stack stackStub = measure(() -> stackV4RequestToStackConverter.convert(stackRequest), LOGGER, "Stack request converted to stack took {} ms for stack {}", stackName);
stackStub.setWorkspace(workspace);
stackStub.setCreator(user);
StackType stackType = determineStackTypeBasedOnTheUsedApi(stackStub, distroxRequest);
stackStub.setType(stackType);
String platformString = stackStub.getCloudPlatform().toLowerCase();
MDCBuilder.buildMdcContext(stackStub);
Stack savedStack;
try {
Blueprint blueprint = measure(() -> determineBlueprint(stackRequest, workspace), LOGGER, "Blueprint determined in {} ms for stack {}", stackName);
Future<StatedImage> imgFromCatalogFuture = determineImageCatalog(stackName, platformString, stackRequest, blueprint, user, workspace);
hueWorkaroundValidatorService.validateForStackRequest(getHueHostGroups(blueprint.getBlueprintText()), stackStub.getName());
savedStack = transactionService.required(() -> {
Stack stack = measure(() -> stackDecorator.decorate(stackStub, stackRequest, user, workspace), LOGGER, "Decorate Stack with data took {} ms");
DetailedEnvironmentResponse environment = measure(() -> ThreadBasedUserCrnProvider.doAsInternalActor(regionAwareInternalCrnGeneratorFactory.iam().getInternalCrnForServiceAsString(), () -> environmentClientService.getByCrn(stack.getEnvironmentCrn())), LOGGER, "Get Environment from Environment service took {} ms");
if (stack.getOrchestrator() != null && stack.getOrchestrator().getApiEndpoint() != null) {
measure(() -> stackService.validateOrchestrator(stack.getOrchestrator()), LOGGER, "Validate orchestrator took {} ms");
}
stack.setUseCcm(environment.getTunnel().useCcm());
stack.setTunnel(environment.getTunnel());
if (stackRequest.getCluster() != null) {
measure(() -> setStackType(stack, blueprint), LOGGER, "Set stacktype for stack object took {} ms");
measure(() -> clusterCreationService.validate(stackRequest.getCluster(), stack, user, workspace, environment), LOGGER, "Validate cluster rds and autotls took {} ms");
}
measure(() -> fillInstanceMetadata(environment, stack), LOGGER, "Fill up instance metadata took {} ms");
StatedImage imgFromCatalog = measure(() -> getImageCatalog(imgFromCatalogFuture), LOGGER, "Select the correct image took {} ms");
stackRuntimeVersionValidator.validate(stackRequest, imgFromCatalog.getImage(), stackType);
Stack newStack = measure(() -> stackService.create(stack, platformString, imgFromCatalog, user, workspace, Optional.ofNullable(stackRequest.getResourceCrn())), LOGGER, "Save the remaining stack data took {} ms");
try {
LOGGER.info("Create cluster entity in the database with name {}.", stackName);
long clusterSaveStart = System.currentTimeMillis();
createClusterIfNeeded(user, stackRequest, newStack, stackName, blueprint);
LOGGER.info("Cluster save took {} ms", System.currentTimeMillis() - clusterSaveStart);
} catch (CloudbreakImageCatalogException | IOException | TransactionExecutionException e) {
throw new RuntimeException(e.getMessage(), e);
}
measure(() -> assignOwnerRoleOnDataHub(user, stackRequest, newStack), LOGGER, "assignOwnerRoleOnDataHub to stack took {} ms with name {}.", stackName);
return newStack;
});
} catch (TransactionExecutionException e) {
stackUnderOperationService.off();
if (e.getCause() instanceof DataIntegrityViolationException) {
String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.STACK, getProperSqlErrorMessage((DataIntegrityViolationException) e.getCause()));
throw new BadRequestException(msg, e.getCause());
}
throw new TransactionRuntimeExecutionException(e);
}
StackV4Response response = measure(() -> stackToStackV4ResponseConverter.convert(savedStack), LOGGER, "Stack response has been created for stack took {} ms with name {}", stackName);
LOGGER.info("Generated stack response after creation: {}", JsonUtil.writeValueAsStringSilentSafe(response));
FlowIdentifier flowIdentifier = measure(() -> flowManager.triggerProvisioning(savedStack.getId()), LOGGER, "Stack triggerProvisioning took {} ms with name {}", stackName);
response.setFlowIdentifier(flowIdentifier);
metricService.submit(STACK_PREPARATION, System.currentTimeMillis() - start);
return response;
}
use of com.sequenceiq.cloudbreak.common.exception.BadRequestException in project cloudbreak by hortonworks.
the class DistroXService method validate.
private void validate(DistroXV1Request request) {
DetailedEnvironmentResponse environment = Optional.ofNullable(environmentClientService.getByName(request.getEnvironmentName())).orElseThrow(() -> new BadRequestException("No environment name provided hence unable to obtain some important data"));
if (environment == null) {
throw new BadRequestException(format("'%s' Environment does not exist.", request.getEnvironmentName()));
}
DescribeFreeIpaResponse freeipa = freeipaClientService.getByEnvironmentCrn(environment.getCrn());
if (freeipa == null || freeipa.getAvailabilityStatus() == null || !freeipa.getAvailabilityStatus().isAvailable()) {
throw new BadRequestException(format("If you want to provision a Data Hub then the FreeIPA instance must be running in the '%s' Environment.", environment.getName()));
}
Set<String> sdxCrns = platformAwareSdxConnector.listSdxCrns(environment.getName(), environment.getCrn());
if (sdxCrns.isEmpty()) {
throw new BadRequestException(format("Data Lake stack cannot be found for environment CRN: %s (%s)", environment.getName(), environment.getCrn()));
}
Set<Pair<String, StatusCheckResult>> sdxCrnsWithAvailability = platformAwareSdxConnector.listSdxCrnsWithAvailability(environment.getName(), environment.getCrn(), sdxCrns);
if (!sdxCrnsWithAvailability.stream().map(Pair::getValue).allMatch(statusCheckResult -> StatusCheckResult.AVAILABLE.equals(statusCheckResult))) {
throw new BadRequestException("Data Lake stacks of environment should be available.");
}
}
Aggregations