Search in sources :

Example 31 with BadRequestException

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;
}
Also used : StopRestrictionReason(com.sequenceiq.cloudbreak.domain.StopRestrictionReason) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException)

Example 32 with BadRequestException

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);
    }
}
Also used : TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack) TransactionRuntimeExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionRuntimeExecutionException)

Example 33 with BadRequestException

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();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) NestedNullException(org.apache.commons.beanutils.NestedNullException) NotFoundException(com.sequenceiq.cloudbreak.common.exception.NotFoundException) RequestObject(com.sequenceiq.authorization.annotation.RequestObject) AuthorizationResourceAction(com.sequenceiq.authorization.resource.AuthorizationResourceAction) AuthorizationVariableType(com.sequenceiq.authorization.resource.AuthorizationVariableType)

Example 34 with BadRequestException

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;
}
Also used : Blueprint(com.sequenceiq.cloudbreak.domain.Blueprint) FlowIdentifier(com.sequenceiq.flow.api.model.FlowIdentifier) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) TransactionRuntimeExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionRuntimeExecutionException) StackType(com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType) StackV4Response(com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.StackV4Response) TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) DetailedEnvironmentResponse(com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) StatedImage(com.sequenceiq.cloudbreak.service.image.StatedImage)

Example 35 with BadRequestException

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.");
    }
}
Also used : StackOperations(com.sequenceiq.distrox.v1.distrox.StackOperations) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) StatusCheckResult(com.sequenceiq.cloudbreak.saas.sdx.status.StatusCheckResult) Set(java.util.Set) WorkspaceService(com.sequenceiq.cloudbreak.service.workspace.WorkspaceService) EnvironmentClientService(com.sequenceiq.cloudbreak.service.environment.EnvironmentClientService) DistroXV1RequestToStackV4RequestConverter(com.sequenceiq.distrox.v1.distrox.converter.DistroXV1RequestToStackV4RequestConverter) String.format(java.lang.String.format) Inject(javax.inject.Inject) CloudbreakRestRequestThreadLocalService(com.sequenceiq.cloudbreak.structuredevent.CloudbreakRestRequestThreadLocalService) FreeipaClientService(com.sequenceiq.cloudbreak.service.freeipa.FreeipaClientService) DescribeFreeIpaResponse(com.sequenceiq.freeipa.api.v1.freeipa.stack.model.describe.DescribeFreeIpaResponse) Pair(org.apache.commons.lang3.tuple.Pair) Service(org.springframework.stereotype.Service) DetailedEnvironmentResponse(com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse) Optional(java.util.Optional) PlatformAwareSdxConnector(com.sequenceiq.cloudbreak.saas.sdx.PlatformAwareSdxConnector) StackV4Response(com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.StackV4Response) DistroXV1Request(com.sequenceiq.distrox.api.v1.distrox.model.DistroXV1Request) DescribeFreeIpaResponse(com.sequenceiq.freeipa.api.v1.freeipa.stack.model.describe.DescribeFreeIpaResponse) DetailedEnvironmentResponse(com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

BadRequestException (com.sequenceiq.cloudbreak.common.exception.BadRequestException)298 Test (org.junit.jupiter.api.Test)134 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)45 Stack (com.sequenceiq.cloudbreak.domain.stack.Stack)34 Cluster (com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster)26 SdxCluster (com.sequenceiq.datalake.entity.SdxCluster)23 ValidationResult (com.sequenceiq.cloudbreak.validation.ValidationResult)22 StackV4Request (com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.StackV4Request)21 DetailedEnvironmentResponse (com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse)21 Blueprint (com.sequenceiq.cloudbreak.domain.Blueprint)19 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)19 Stack (com.sequenceiq.freeipa.entity.Stack)18 BaseDiagnosticsCollectionRequest (com.sequenceiq.common.api.diagnostics.BaseDiagnosticsCollectionRequest)14 FlowIdentifier (com.sequenceiq.flow.api.model.FlowIdentifier)14 SdxClusterRequest (com.sequenceiq.sdx.api.model.SdxClusterRequest)14 Set (java.util.Set)14 NotFoundException (com.sequenceiq.cloudbreak.common.exception.NotFoundException)13 NameOrCrn (com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn)12 Json (com.sequenceiq.cloudbreak.common.json.Json)12 TransactionExecutionException (com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException)12