<commit_before>package com.sequenceiq.freeipa.sync;

import static com.sequenceiq.cloudbreak.util.Benchmark.checkedMeasure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.client.RPCResponse;
import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.DetailedStackStatus;
import com.sequenceiq.freeipa.entity.InstanceMetaData;
import com.sequenceiq.freeipa.entity.Stack;
import com.sequenceiq.freeipa.service.stack.FreeIpaInstanceHealthDetailsService;

@Component
public class FreeipaChecker {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreeipaChecker.class);

    @Inject
    private FreeIpaInstanceHealthDetailsService freeIpaInstanceHealthDetailsService;

    private Pair<Map<InstanceMetaData, DetailedStackStatus>, String> checkStatus(Stack stack, Set<InstanceMetaData> checkableInstances) throws Exception {
        return checkedMeasure(() -> {
            Map<InstanceMetaData, DetailedStackStatus> statuses = new HashMap<>();
            List<RPCResponse<Boolean>> responses = new LinkedList<>();
            LOGGER.info("Checking FreeIPA status for instance IDs {}",
                    checkableInstances.stream().map(InstanceMetaData::getInstanceId).collect(Collectors.toList()));
            for (InstanceMetaData instanceMetaData : checkableInstances) {
                try {
                    RPCResponse<Boolean> response = checkedMeasure(() -> freeIpaInstanceHealthDetailsService.checkFreeIpaHealth(stack, instanceMetaData), LOGGER,
                            ":::Auto sync::: FreeIPA health check ran in {}ms");
                    responses.add(response);
                    DetailedStackStatus newDetailedStackStatus;
                    if (response.getResult()) {
                        newDetailedStackStatus = DetailedStackStatus.AVAILABLE;
                    } else {
                        newDetailedStackStatus = DetailedStackStatus.UNHEALTHY;
                    }
                    LOGGER.info("FreeIpa health check reported {} for {}", newDetailedStackStatus, instanceMetaData);
                    statuses.put(instanceMetaData, newDetailedStackStatus);
                } catch (Exception e) {
                    LOGGER.info("FreeIpaClientException occurred during status fetch for {}: {}", instanceMetaData, e.getMessage(), e);
                    statuses.put(instanceMetaData, DetailedStackStatus.UNREACHABLE);
                }
            }
            String message = getMessages(responses);
            return Pair.of(statuses, message);
        }, LOGGER, ":::Auto sync::: freeipa server status is checked in {}ms");
    }

    public SyncResult getStatus(Stack stack, Set<InstanceMetaData> checkableInstances) {
        try {
            if (checkableInstances.isEmpty()) {
                throw new UnsupportedOperationException("There are no instances of FreeIPA to check the status of");
            }

            // Exclude terminated but include deleted
            Set<InstanceMetaData> notTermiatedStackInstances = stack.getAllInstanceMetaDataList().stream()
                    .filter(Predicate.not(InstanceMetaData::isTerminated))
                    .collect(Collectors.toSet());
            Pair<Map<InstanceMetaData, DetailedStackStatus>, String> statusCheckPair = checkStatus(stack, checkableInstances);
            List<DetailedStackStatus> responses = new ArrayList<>(statusCheckPair.getFirst().values());
            DetailedStackStatus status;
            if (areAllStatusTheSame(responses) && !hasMissingStatus(responses, notTermiatedStackInstances)) {
                status = responses.get(0);
            } else {
                status = DetailedStackStatus.UNHEALTHY;
            }

            return new SyncResult("FreeIpa is " + status + ", " + statusCheckPair.getSecond(), status, statusCheckPair.getFirst());
        } catch (Exception e) {
            LOGGER.info("Error occurred during status fetch: " + e.getMessage(), e);
            return new SyncResult("FreeIpa is unreachable, because error occurred: " + e.getMessage(), DetailedStackStatus.UNREACHABLE, null);
        }
    }<commit_msg>CB-18495 Fix unfinished FreeIPA statuReason<commit_after>package com.sequenceiq.freeipa.sync;

import static com.sequenceiq.cloudbreak.util.Benchmark.checkedMeasure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.client.RPCResponse;
import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.DetailedStackStatus;
import com.sequenceiq.freeipa.entity.InstanceMetaData;
import com.sequenceiq.freeipa.entity.Stack;
import com.sequenceiq.freeipa.service.stack.FreeIpaInstanceHealthDetailsService;

@Component
public class FreeipaChecker {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreeipaChecker.class);

    @Inject
    private FreeIpaInstanceHealthDetailsService freeIpaInstanceHealthDetailsService;

    private Pair<Map<InstanceMetaData, DetailedStackStatus>, String> checkStatus(Stack stack, Set<InstanceMetaData> checkableInstances) throws Exception {
        return checkedMeasure(() -> {
            Map<InstanceMetaData, DetailedStackStatus> statuses = new HashMap<>();
            List<RPCResponse<Boolean>> responses = new LinkedList<>();
            LOGGER.info("Checking FreeIPA status for instance IDs {}",
                    checkableInstances.stream().map(InstanceMetaData::getInstanceId).collect(Collectors.toList()));
            for (InstanceMetaData instanceMetaData : checkableInstances) {
                try {
                    RPCResponse<Boolean> response = checkedMeasure(() -> freeIpaInstanceHealthDetailsService.checkFreeIpaHealth(stack, instanceMetaData), LOGGER,
                            ":::Auto sync::: FreeIPA health check ran in {}ms");
                    responses.add(response);
                    DetailedStackStatus newDetailedStackStatus;
                    if (response.getResult()) {
                        newDetailedStackStatus = DetailedStackStatus.AVAILABLE;
                    } else {
                        newDetailedStackStatus = DetailedStackStatus.UNHEALTHY;
                    }
                    LOGGER.info("FreeIpa health check reported {} for {}", newDetailedStackStatus, instanceMetaData);
                    statuses.put(instanceMetaData, newDetailedStackStatus);
                } catch (Exception e) {
                    LOGGER.info("FreeIpaClientException occurred during status fetch for {}: {}", instanceMetaData, e.getMessage(), e);
                    statuses.put(instanceMetaData, DetailedStackStatus.UNREACHABLE);
                }
            }
            String message = getMessages(responses);
            return Pair.of(statuses, message);
        }, LOGGER, ":::Auto sync::: freeipa server status is checked in {}ms");
    }

    public SyncResult getStatus(Stack stack, Set<InstanceMetaData> checkableInstances) {
        try {
            if (checkableInstances.isEmpty()) {
                throw new UnsupportedOperationException("There are no instances of FreeIPA to check the status of");
            }

            // Exclude terminated but include deleted
            Set<InstanceMetaData> notTermiatedStackInstances = stack.getAllInstanceMetaDataList().stream()
                    .filter(Predicate.not(InstanceMetaData::isTerminated))
                    .collect(Collectors.toSet());
            Pair<Map<InstanceMetaData, DetailedStackStatus>, String> statusCheckPair = checkStatus(stack, checkableInstances);
            List<DetailedStackStatus> responses = new ArrayList<>(statusCheckPair.getFirst().values());
            DetailedStackStatus status;
            if (areAllStatusTheSame(responses) && !hasMissingStatus(responses, notTermiatedStackInstances)) {
                status = responses.get(0);
            } else {
                status = DetailedStackStatus.UNHEALTHY;
            }
            String statusReason = "FreeIpa is " + status;
            if (StringUtils.isNotBlank(statusCheckPair.getSecond())) {
                statusReason += ", " + statusCheckPair.getSecond();
            }
            return new SyncResult(statusReason, status, statusCheckPair.getFirst());
        } catch (Exception e) {
            LOGGER.info("Error occurred during status fetch: " + e.getMessage(), e);
            return new SyncResult("FreeIpa is unreachable, because error occurred: " + e.getMessage(), DetailedStackStatus.UNREACHABLE, null);
        }
    }
{'fraction_non_alphanumeric': 0.09404117009750812, 'fraction_numerical': 0.0015167930660888408, 'mean_word_length': 2.8949367088607594, 'pattern_counts': {'":': 4, '<': 33, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4045497', 'n_tokens_mistral': 2332, 'n_tokens_neox': 2342, 'n_words': 478}