Java Code Examples for reactor.bus.Event#getData()

The following examples show how to use reactor.bus.Event#getData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DisableKerberosHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<DisableKerberosRequest> event) {
    DisableKerberosResult result;
    try {
        LOGGER.info("Received DisableKerberosRequest event: {}", event.getData());
        ClusterApi clusterApi = clusterApiConnectors.getConnector(stackService.getByIdWithListsInTransaction(event.getData().getResourceId()));
        clusterApi.clusterSecurityService().disableSecurity();
        LOGGER.info("Finished disabling Security");
        result = new DisableKerberosResult(event.getData());
    } catch (Exception e) {
        LOGGER.warn("An error has occured during disabling security", e);
        result = new DisableKerberosResult(e.getMessage(), e, event.getData());
    }
    LOGGER.info("Sending out DisableKerberosResult: {}", result);
    eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result));
    LOGGER.info("DisableKerberosResult has been sent");
}
 
Example 2
Source File: AmbariStopServerAndAgentHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<AmbariStopServerAndAgentRequest> event) {
    AmbariStopServerAndAgentRequest request = event.getData();
    Long stackId = request.getResourceId();
    AmbariStopServerAndAgentResult result;
    try {
        Stack stack = stackService.getByIdWithListsInTransaction(stackId);
        GatewayConfig primaryGatewayConfig = gatewayConfigService.getPrimaryGatewayConfig(stack);
        Set<Node> allNodes = stackUtil.collectNodes(stack);
        hostOrchestrator.stopClusterManagerOnMaster(primaryGatewayConfig, allNodes, clusterDeletionBasedModel(stack.getId(), stack.getCluster().getId()));
        result = new AmbariStopServerAndAgentResult(request);
    } catch (Exception e) {
        String message = "Failed to start ambari agent and/or server on new host.";
        LOGGER.error(message, e);
        result = new AmbariStopServerAndAgentResult(message, e, request);
    }
    eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result));
}
 
Example 3
Source File: UpdateImageHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<UpdateImageRequest> event) {
    LOGGER.debug("Received event: {}", event);
    UpdateImageRequest<UpdateImageResult> request = event.getData();
    CloudContext cloudContext = request.getCloudContext();
    try {
        CloudConnector<?> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant());
        AuthenticatedContext auth = connector.authentication().authenticate(cloudContext, request.getCloudCredential());
        CloudStack stack = request.getCloudStack();

        List<CloudResource> cloudResources = request.getCloudResources();
        cloudResources.stream().filter(resource -> resource.getType().getCommonResourceType() == CommonResourceType.TEMPLATE)
                .forEach(resource -> resource.putParameter(CloudResource.IMAGE, stack.getImage().getImageName()));

        connector.resources().update(auth, stack, cloudResources);
        UpdateImageResult result = new UpdateImageResult(request.getResourceId());
        request.getResult().onNext(result);
        eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result));
        LOGGER.debug("Update image finished for {}", cloudContext);
    } catch (Exception e) {
        UpdateImageResult failure = new UpdateImageResult(e.getMessage(), e, request.getResourceId());
        request.getResult().onNext(failure);
        eventBus.notify(failure.selector(), new Event<>(event.getHeaders(), failure));
    }
}
 
Example 4
Source File: InteractiveCredentialCreationStatusHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<InteractiveCredentialCreationStatus> interactiveCredentialCreationStatusEvent) {
    InteractiveCredentialCreationStatus interactiveCredentialCreationStatus = interactiveCredentialCreationStatusEvent.getData();
    String userCrn = interactiveCredentialCreationStatus.getCloudContext().getUserId();
    ThreadBasedUserCrnProvider.doAs(userCrn, () -> {
        String message = interactiveCredentialCreationStatus.getMessage();
        InteractiveCredentialNotification notification = new InteractiveCredentialNotification()
                .withEventTimestamp(new Date().getTime())
                .withUserId(interactiveCredentialCreationStatus.getCloudContext().getUserId())
                .withCloud(interactiveCredentialCreationStatus.getExtendedCloudCredential().getCloudPlatform())
                .withEventMessage(message);
        ResourceEvent event;
        if (interactiveCredentialCreationStatus.isError()) {
            event = CREDENTIAL_AZURE_INTERACTIVE_FAILED;
            notification.withEventType(event.name());
            LOGGER.info("Interactive credential creation failed status: {}", new Json(notification).getValue());
        } else {
            event = CREDENTIAL_AZURE_INTERACTIVE_STATUS;
            notification.withEventType(event.name());
            LOGGER.info("Interactive credential creation success status: {}", new Json(notification).getValue());
        }
        notificationService.send(event, notification, ThreadBasedUserCrnProvider.getUserCrn());
    });
}
 
Example 5
Source File: GetPlatformVmTypesHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<GetPlatformVmTypesRequest> getPlatformVmTypesRequest) {
    LOGGER.debug("Received event: {}", getPlatformVmTypesRequest);
    GetPlatformVmTypesRequest request = getPlatformVmTypesRequest.getData();

    try {
        CloudPlatformVariant cloudPlatformVariant = new CloudPlatformVariant(
                Platform.platform(request.getExtendedCloudCredential().getCloudPlatform()),
                Variant.variant(request.getVariant()));
        PlatformResources platformResources = cloudPlatformConnectors.get(cloudPlatformVariant).platformResources();
        CloudVmTypes platformVirtualMachinesJson;
        if (CdpResourceType.DATAHUB.equals(request.getCdpResourceType())) {
            platformVirtualMachinesJson = platformResources
                    .virtualMachinesForDistroX(request.getCloudCredential(), Region.region(request.getRegion()), request.getFilters());
        } else {
            platformVirtualMachinesJson = platformResources
                    .virtualMachines(request.getCloudCredential(), Region.region(request.getRegion()), request.getFilters());
        }
        GetPlatformVmTypesResult getPlatformSecurityGroupsResult = new GetPlatformVmTypesResult(request.getResourceId(), platformVirtualMachinesJson);
        request.getResult().onNext(getPlatformSecurityGroupsResult);
        LOGGER.debug("Query platform vmtypes types finished.");
    } catch (Exception e) {
        request.getResult().onNext(new GetPlatformVmTypesResult(e.getMessage(), e, request.getResourceId()));
    }
}
 
Example 6
Source File: PublicKeyDeleteHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<EnvironmentDeletionDto> environmentDtoEvent) {
    LOGGER.debug("Accepting PublickeyDelete event");
    EnvironmentDeletionDto environmentDeletionDto = environmentDtoEvent.getData();
    EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto();
    EnvDeleteEvent envDeleteEvent = getEnvDeleteEvent(environmentDeletionDto);
    try {
        environmentService.findEnvironmentById(environmentDto.getId()).ifPresent(this::deleteManagedKey);
        eventSender().sendEvent(envDeleteEvent, environmentDtoEvent.getHeaders());
    } catch (Exception e) {
        if (environmentDeletionDto.isForceDelete()) {
            LOGGER.warn("The %s was not successful but the environment deletion was requested as force delete so " +
                    "continue the deletion flow", selector());
            eventSender().sendEvent(envDeleteEvent, environmentDtoEvent.getHeaders());
        } else {
            EnvDeleteFailedEvent failedEvent = new EnvDeleteFailedEvent(environmentDto.getId(),
                    environmentDto.getName(), e, environmentDto.getResourceCrn());
            eventSender().sendEvent(failedEvent, environmentDtoEvent.getHeaders());
        }
    }
}
 
Example 7
Source File: GetVirtualMachineRecommendationsHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<GetVirtualMachineRecommendtaionRequest> gVMRRE) {
    LOGGER.debug("Received GetVirtualMachineRecommendtaionRequest event: {}", gVMRRE);
    GetVirtualMachineRecommendtaionRequest request = gVMRRE.getData();
    String cloudPlatform = request.getCloudPlatform();
    try {
        CloudConnector<Object> connector = cloudPlatformConnectors.getDefault(Platform.platform(cloudPlatform));
        VmRecommendations recommendations = connector.parameters().recommendedVms();
        GetVirtualMachineRecommendationResponse gVMRResponse = new GetVirtualMachineRecommendationResponse(request.getResourceId(), recommendations);
        request.getResult().onNext(gVMRResponse);
        LOGGER.debug("Query platform machine recommendations finished.");
    } catch (RuntimeException e) {
        LOGGER.error("Could not get virtual machine recommendations for platform: " + cloudPlatform, e);
        request.getResult().onNext(new GetVirtualMachineRecommendationResponse(e.getMessage(), e, request.getResourceId()));
    }
}
 
Example 8
Source File: CollectMetadataHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<CollectMetadataRequest> collectMetadataRequestEvent) {
    LOGGER.debug("Received event: {}", collectMetadataRequestEvent);
    CollectMetadataRequest request = collectMetadataRequestEvent.getData();
    try {
        CloudConnector<Object> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant());
        AuthenticatedContext ac = connector.authentication().authenticate(request.getCloudContext(), request.getCloudCredential());

        List<CloudVmMetaDataStatus> instanceStatuses = connector.metadata()
                .collect(ac, request.getCloudResource(), request.getVms(), request.getKnownVms());
        CollectMetadataResult collectMetadataResult = new CollectMetadataResult(request.getResourceId(), instanceStatuses);
        request.getResult().onNext(collectMetadataResult);
        eventBus.notify(collectMetadataResult.selector(), new Event<>(collectMetadataRequestEvent.getHeaders(), collectMetadataResult));
        LOGGER.debug("Metadata collection successfully finished");
    } catch (RuntimeException e) {
        LOGGER.error("Collecting metadata failed", e);
        CollectMetadataResult failure = new CollectMetadataResult(e, request.getResourceId());
        request.getResult().onNext(failure);
        eventBus.notify(failure.selector(), new Event<>(collectMetadataRequestEvent.getHeaders(), failure));
    }
}
 
Example 9
Source File: CredentialPrerequisitesHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<CredentialPrerequisitesRequest> credentialPrerequisitesRequestEvent) {
    LOGGER.debug("Received event: {}", credentialPrerequisitesRequestEvent);
    CredentialPrerequisitesRequest request = credentialPrerequisitesRequestEvent.getData();
    CloudContext cloudContext = request.getCloudContext();
    try {
        LOGGER.info("Gathering credential prerequisites for platform: '{}'", cloudContext.getPlatform());
        CloudConnector<?> connector = cloudPlatformConnectors.getDefault(cloudContext.getPlatform());
        CredentialPrerequisitesResponse result = connector.credentials()
                .getPrerequisites(cloudContext, request.getExternalId(), request.getDeploymentAddress());
        CredentialPrerequisitesResult credentialPrerequisitesResult = new CredentialPrerequisitesResult(request.getResourceId(), result);
        request.getResult().onNext(credentialPrerequisitesResult);
        LOGGER.debug("Credential prerequisites have been collected successfully for platform: '{}'!", cloudContext.getPlatform().value());
    } catch (RuntimeException e) {
        request.getResult().onNext(new CredentialPrerequisitesResult(e.getMessage(), e, request.getResourceId()));
    }
}
 
Example 10
Source File: StopDatahubHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<EnvironmentDto> environmentDtoEvent) {
    EnvironmentDto environmentDto = environmentDtoEvent.getData();
    try {
        datahubPollerService.stopAttachedDatahubClusters(environmentDto.getId(), environmentDto.getResourceCrn());
        EnvStopEvent envStopEvent = EnvStopEvent.EnvStopEventBuilder.anEnvStopEvent()
                .withSelector(EnvStopStateSelectors.ENV_STOP_DATALAKE_EVENT.selector())
                .withResourceId(environmentDto.getId())
                .withResourceName(environmentDto.getName())
                .build();
        eventSender().sendEvent(envStopEvent, environmentDtoEvent.getHeaders());
    } catch (Exception e) {
        EnvStopFailedEvent failedEvent = new EnvStopFailedEvent(environmentDto, e, EnvironmentStatus.STOP_DATAHUB_FAILED);
        eventSender().sendEvent(failedEvent, environmentDtoEvent.getHeaders());
    }
}
 
Example 11
Source File: PrerequisitesCreationHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<EnvironmentDto> environmentDtoEvent) {
    EnvironmentDto environmentDto = environmentDtoEvent.getData();
    environmentService.findEnvironmentById(environmentDto.getId())
            .ifPresentOrElse(environment -> {
                        try {
                            if (AZURE.name().equals(environmentDto.getCloudPlatform())) {
                                createResourceGroup(environmentDto, environment);
                            } else {
                                LOGGER.debug("Cloudplatform not Azure, not creating resource group.");
                            }
                            goToNetworkCreationState(environmentDtoEvent);
                        } catch (Exception e) {
                            goToFailedState(environmentDtoEvent, e.getMessage());
                        }
                    }, () -> goToFailedState(environmentDtoEvent, String.format("Environment was not found with id '%s'.", environmentDto.getId()))
            );
}
 
Example 12
Source File: StackPreTerminationHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<StackPreTerminationRequest> requestEvent) {
    StackPreTerminationRequest request = requestEvent.getData();
    Stack stack = stackService.getByIdWithListsInTransaction(request.getResourceId());
    try {
        Cluster cluster = stack.getCluster();
        if (cluster != null) {
            Set<Recipe> recipesByCluster = hostGroupService.getRecipesByCluster(cluster.getId());
            telemetryAgentService.stopTelemetryAgent(stack);
            recipeEngine.executePreTerminationRecipes(stack, recipesByCluster, request.getForced());
            preTerminationStateExecutor.runPreteraminationTasks(stack);
        }
    } catch (Exception ex) {
        LOGGER.info("Pre-termination failed: {}", ex.getMessage(), ex);
    }

    Selectable result = new StackPreTerminationSuccess(stack.getId());
    eventBus.notify(result.selector(), new Event<>(requestEvent.getHeaders(), result));
}
 
Example 13
Source File: ClusterCredentialChangeHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<ClusterCredentialChangeRequest> event) {
    ClusterCredentialChangeRequest request = event.getData();
    ClusterCredentialChangeResult result;
    try {
        Stack stack = stackService.getByIdWithListsInTransaction(request.getResourceId());
        ClusterSecurityService clusterSecurityService = clusterApiConnectors.getConnector(stack).clusterSecurityService();
        switch (request.getType()) {
            case REPLACE:
                clusterSecurityService.replaceUserNamePassword(request.getUser(), request.getPassword());
                break;
            case UPDATE:
                clusterSecurityService.updateUserNamePassword(request.getPassword());
                break;
            default:
                throw new UnsupportedOperationException("Ambari credential update request not supported: " + request.getType());
        }
        result = new ClusterCredentialChangeResult(request);
    } catch (Exception e) {
        result = new ClusterCredentialChangeResult(e.getMessage(), e, request);
    }
    eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result));
}
 
Example 14
Source File: BootstrapMachineHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<BootstrapMachinesRequest> event) {
    BootstrapMachinesRequest request = event.getData();
    Selectable response;
    try {
        if (request.isReBootstrap()) {
            clusterBootstrapper.reBootstrapMachines(request.getResourceId());
        } else {
            clusterBootstrapper.bootstrapMachines(request.getResourceId());
        }
        response = new BootstrapMachinesSuccess(request.getResourceId());
    } catch (Exception e) {
        response = new BootstrapMachinesFailed(request.getResourceId(), e);
    }
    eventBus.notify(response.selector(), new Event<>(event.getHeaders(), response));
}
 
Example 15
Source File: ResourcePersistenceHandler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<ResourceNotification> event) {
    LOGGER.debug("Resource notification event received: {}", event);
    ResourceNotification notification = event.getData();

    RetryUtil.withDefaultRetries()
            .retry(() -> {
                ResourceNotification notificationPersisted;
                switch (notification.getType()) {
                    case CREATE:
                        notificationPersisted = cloudResourcePersisterService.persist(notification);
                        break;
                    case UPDATE:
                        notificationPersisted = cloudResourcePersisterService.update(notification);
                        break;
                    case DELETE:
                        notificationPersisted = cloudResourcePersisterService.delete(notification);
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported notification type: " + notification.getType());
                }
                notificationPersisted.getPromise().onNext(new ResourcePersisted());
            })
            .checkIfRecoverable(e -> e instanceof TransientDataAccessException)
            .ifNotRecoverable(e -> notification.getPromise().onError(e)).run();
}
 
Example 16
Source File: Flow2Handler.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Event<? extends Payload> event) {
    String key = (String) event.getKey();
    Payload payload = event.getData();
    String flowId = getFlowId(event);
    String flowChainId = getFlowChainId(event);
    String flowTriggerUserCrn = getFlowTriggerUserCrn(event);
    Span activeSpan = tracer.activeSpan();
    SpanContext spanContext = event.getHeaders().get(FlowConstants.SPAN_CONTEXT);
    String operationName = event.getKey().toString();
    if (TracingUtil.isActiveSpanReusable(activeSpan, spanContext, operationName)) {
        LOGGER.debug("Reusing existing span. {}", activeSpan.context());
        doAccept(event, key, payload, flowId, flowChainId, flowTriggerUserCrn, spanContext);
    } else {
        Span span = TracingUtil.getSpan(tracer, operationName, spanContext, flowId, flowChainId, flowTriggerUserCrn);
        spanContext = TracingUtil.useOrCreateSpanContext(spanContext, span);
        try (Scope ignored = tracer.activateSpan(span)) {
            doAccept(event, key, payload, flowId, flowChainId, flowTriggerUserCrn, spanContext);
        } finally {
            span.finish();
        }
    }
}
 
Example 17
Source File: StopDatabaseServerHandler.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Event<StopDatabaseServerRequest> event) {
    LOGGER.debug("Received event: {}", event);
    StopDatabaseServerRequest request = event.getData();
    CloudContext cloudContext = request.getCloudContext();
    try {
        CloudConnector<Object> connector = cloudPlatformConnectors.get(cloudContext.getPlatformVariant());
        AuthenticatedContext ac = connector.authentication().authenticate(cloudContext, request.getCloudCredential());

        ExternalDatabaseStatus status = connector.resources().getDatabaseServerStatus(ac, request.getDbStack());
        if (status != null && status.isTransient()) {
            LOGGER.debug("Database server '{}' is in '{}' status. Start waiting for a permanent status.", request.getDbStack(), status);

            PollTask<ExternalDatabaseStatus> task = statusCheckFactory.newPollPermanentExternalDatabaseStateTask(ac, request.getDbStack());
            status = externalDatabaseStatusPollingScheduler.schedule(task);
        }

        if (status != STOPPED) {
            LOGGER.debug("Database server '{}' is in '{}' status. Calling for '{}' status.", request.getDbStack(), status, STOPPED);
            connector.resources().stopDatabaseServer(ac, request.getDbStack());
        } else {
            LOGGER.debug("Database server '{}' is already in '{}' status.", request.getDbStack(), STOPPED);
        }

        RedbeamsEvent success = new StopDatabaseServerSuccess(request.getResourceId());
        eventBus.notify(success.selector(), new Event<>(event.getHeaders(), success));
        LOGGER.debug("Stopping the database server successfully finished for {}", cloudContext);
    } catch (Exception e) {
        StopDatabaseServerFailed failure = new StopDatabaseServerFailed(request.getResourceId(), e);
        LOGGER.warn("Error stopping the database server:", e);
        eventBus.notify(failure.selector(), new Event<>(event.getHeaders(), failure));
    }
}
 
Example 18
Source File: EnvironmentInitHandler.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Event<EnvironmentDto> environmentDtoEvent) {
    EnvironmentDto environmentDto = environmentDtoEvent.getData();
    environmentService.findEnvironmentById(environmentDto.getId())
            .ifPresentOrElse(environment -> {
                        try {
                            LOGGER.debug("Environment initialization flow step started.");
                            initEnvironment(environment);
                            goToValidationState(environmentDtoEvent, environmentDto);
                        } catch (Exception e) {
                            goToFailedState(environmentDtoEvent, e.getMessage());
                        }
                    }, () -> goToFailedState(environmentDtoEvent, String.format("Environment was not found with id '%s'.", environmentDto.getId()))
            );
}
 
Example 19
Source File: EphemeralClusterUpdateHandler.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Event<EphemeralClusterUpdateRequest> event) {
    EphemeralClusterUpdateRequest request = event.getData();
    Selectable response;
    try {
        clusterServiceRunner.updateSaltState(request.getResourceId());
        response = new EphemeralClusterUpdateSuccess(request.getResourceId());
    } catch (Exception e) {
        response = new EphemeralClusterUpdateFailed(request.getResourceId(), e);
    }
    eventBus.notify(response.selector(), new Event<>(event.getHeaders(), response));
}
 
Example 20
Source File: NotificationConsumer.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void accept(Event<NotificationData> notificationDataEvent) {

    NotificationData notificationData = notificationDataEvent.getData();
    try {
        notificationService.initiateNotification(notificationData);
    } catch (InterruptedException e) {
    }

}