Search in sources :

Example 16 with TransactionExecutionException

use of com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException in project cloudbreak by hortonworks.

the class StackService method getStackRequestByNameOrCrnInWorkspaceId.

public StackV4Request getStackRequestByNameOrCrnInWorkspaceId(NameOrCrn nameOrCrn, Long workspaceId) {
    try {
        return transactionService.required(() -> {
            ShowTerminatedClustersAfterConfig showTerminatedClustersAfterConfig = showTerminatedClusterConfigService.get();
            Optional<Stack> stack = findByNameOrCrnAndWorkspaceIdWithLists(nameOrCrn, workspaceId);
            if (stack.isEmpty()) {
                throw new NotFoundException(format(STACK_NOT_FOUND_BY_NAME_OR_CRN_EXCEPTION_MESSAGE, nameOrCrn));
            }
            StackV4Request request = stackToStackV4RequestConverter.convert(stack.get());
            request.getCluster().setName(null);
            request.setName(stack.get().getName());
            return request;
        });
    } catch (TransactionExecutionException e) {
        throw new TransactionRuntimeExecutionException(e);
    }
}
Also used : ShowTerminatedClustersAfterConfig(com.sequenceiq.cloudbreak.service.stack.ShowTerminatedClusterConfigService.ShowTerminatedClustersAfterConfig) StackV4Request(com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.StackV4Request) TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) NotFoundException(com.sequenceiq.cloudbreak.common.exception.NotFoundException) CloudbreakImageNotFoundException(com.sequenceiq.cloudbreak.core.CloudbreakImageNotFoundException) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack) AutoscaleStack(com.sequenceiq.cloudbreak.domain.projection.AutoscaleStack) TransactionRuntimeExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionRuntimeExecutionException)

Example 17 with TransactionExecutionException

use of com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException in project cloudbreak by hortonworks.

the class HostMetadataSetup method setupNewHostMetadata.

public void setupNewHostMetadata(Long stackId, Collection<String> newAddresses) {
    try {
        transactionService.required(() -> {
            LOGGER.info("Extending host metadata: {}", newAddresses);
            Stack stack = stackService.getByIdWithListsInTransaction(stackId);
            Set<InstanceMetaData> newInstanceMetadata = instanceMetaDataService.getNotDeletedAndNotZombieInstanceMetadataByStackId(stackId).stream().filter(instanceMetaData -> newAddresses.contains(instanceMetaData.getPrivateIp())).collect(Collectors.toSet());
            updateWithHostData(stack, newInstanceMetadata);
            instanceMetaDataService.saveAll(newInstanceMetadata);
        });
    } catch (TransactionExecutionException e) {
        throw new CloudbreakRuntimeException(e.getCause());
    }
}
Also used : InstanceMetaData(com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack) HostOrchestrator(com.sequenceiq.cloudbreak.orchestrator.host.HostOrchestrator) Logger(org.slf4j.Logger) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) InstanceStatus(com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceStatus) CloudbreakRuntimeException(com.sequenceiq.cloudbreak.service.CloudbreakRuntimeException) Set(java.util.Set) Collectors(java.util.stream.Collectors) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) GatewayConfigService(com.sequenceiq.cloudbreak.service.GatewayConfigService) List(java.util.List) TransactionService(com.sequenceiq.cloudbreak.common.service.TransactionService) InstanceMetaData(com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData) Service(org.springframework.stereotype.Service) TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) Map(java.util.Map) GatewayConfig(com.sequenceiq.cloudbreak.orchestrator.model.GatewayConfig) InstanceMetaDataService(com.sequenceiq.cloudbreak.service.stack.InstanceMetaDataService) StackService(com.sequenceiq.cloudbreak.service.stack.StackService) TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) CloudbreakRuntimeException(com.sequenceiq.cloudbreak.service.CloudbreakRuntimeException) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack)

Example 18 with TransactionExecutionException

use of com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException in project cloudbreak by hortonworks.

the class StackOperationService method updateNodeCount.

public FlowIdentifier updateNodeCount(Stack stack, InstanceGroupAdjustmentV4Request instanceGroupAdjustmentJson, boolean withClusterEvent) {
    environmentService.checkEnvironmentStatus(stack, EnvironmentStatus.upscalable());
    try {
        return transactionService.required(() -> {
            boolean upscale = instanceGroupAdjustmentJson.getScalingAdjustment() > 0;
            Stack stackWithLists = stackService.getByIdWithLists(stack.getId());
            updateNodeCountValidator.validateServiceRoles(stackWithLists, instanceGroupAdjustmentJson);
            updateNodeCountValidator.validateStackStatus(stackWithLists, upscale);
            updateNodeCountValidator.validateInstanceGroup(stackWithLists, instanceGroupAdjustmentJson.getInstanceGroup());
            updateNodeCountValidator.validateScalabilityOfInstanceGroup(stackWithLists, instanceGroupAdjustmentJson);
            updateNodeCountValidator.validateScalingAdjustment(instanceGroupAdjustmentJson, stackWithLists);
            boolean instanceStatusValidationNeeded = !upscale || !targetedUpscaleSupportService.targetedUpscaleOperationSupported(stackWithLists);
            if (instanceStatusValidationNeeded) {
                updateNodeCountValidator.validateInstanceStatuses(stackWithLists, instanceGroupAdjustmentJson);
            }
            if (withClusterEvent) {
                updateNodeCountValidator.validateClusterStatus(stackWithLists, upscale);
                updateNodeCountValidator.validateHostGroupIsPresent(instanceGroupAdjustmentJson, stackWithLists);
                if (instanceStatusValidationNeeded) {
                    updateNodeCountValidator.validataHostMetadataStatuses(stackWithLists, instanceGroupAdjustmentJson);
                }
            }
            if (upscale) {
                stackUpdater.updateStackStatus(stackWithLists.getId(), DetailedStackStatus.UPSCALE_REQUESTED, "Requested node count for upscaling: " + instanceGroupAdjustmentJson.getScalingAdjustment());
                return flowManager.triggerStackUpscale(stackWithLists.getId(), instanceGroupAdjustmentJson, withClusterEvent);
            } else {
                stackUpdater.updateStackStatus(stackWithLists.getId(), DetailedStackStatus.DOWNSCALE_REQUESTED, "Requested node count for downscaling: " + abs(instanceGroupAdjustmentJson.getScalingAdjustment()));
                return flowManager.triggerStackDownscale(stackWithLists.getId(), instanceGroupAdjustmentJson);
            }
        });
    } catch (TransactionExecutionException e) {
        if (e.getCause() instanceof ConcurrencyFailureException) {
            LOGGER.info("A concurrent update arrived to this cluster.", e.getCause());
            throw new BadRequestException("A concurrent update arrived to this cluster. Please try again later.");
        }
        if (e.getCause() instanceof BadRequestException) {
            throw e.getCause();
        }
        throw new TransactionRuntimeExecutionException(e);
    }
}
Also used : TransactionExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) Stack(com.sequenceiq.cloudbreak.domain.stack.Stack) TransactionRuntimeExecutionException(com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionRuntimeExecutionException)

Example 19 with TransactionExecutionException

use of com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException 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 20 with TransactionExecutionException

use of com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException 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)

Aggregations

TransactionExecutionException (com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException)56 TransactionRuntimeExecutionException (com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionRuntimeExecutionException)34 Stack (com.sequenceiq.cloudbreak.domain.stack.Stack)26 InstanceMetaData (com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData)17 BadRequestException (com.sequenceiq.cloudbreak.common.exception.BadRequestException)12 TransactionService (com.sequenceiq.cloudbreak.common.service.TransactionService)10 List (java.util.List)10 Set (java.util.Set)10 Inject (javax.inject.Inject)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10 FlowIdentifier (com.sequenceiq.flow.api.model.FlowIdentifier)9 Optional (java.util.Optional)9 StackService (com.sequenceiq.cloudbreak.service.stack.StackService)8 Collection (java.util.Collection)8 Map (java.util.Map)8 Collectors (java.util.stream.Collectors)8 Service (org.springframework.stereotype.Service)8 InstanceStatus (com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceStatus)7 CloudbreakServiceException (com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException)7