<commit_before>/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.fabric8.elasticsearch.plugin.kibana;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.RemoteTransportException;

import com.floragunn.searchguard.support.ConfigConstants;

import io.fabric8.elasticsearch.plugin.ConfigurationSettings;
import io.fabric8.elasticsearch.plugin.OpenshiftRequestContextFactory.OpenshiftRequestContext;
import io.fabric8.elasticsearch.plugin.PluginClient;
import io.fabric8.elasticsearch.plugin.PluginSettings;
import io.fabric8.elasticsearch.plugin.acl.UserRolesSyncStrategy;

public class KibanaSeed implements ConfigurationSettings {


    private static final String DEFAULT_INDEX_TYPE = "config";
    private static final String INDICIES_TYPE = "index-pattern";

    private static final String OPERATIONS_PROJECT = ".operations";
    private static final String BLANK_PROJECT = ".empty-project";
    private static final String ADMIN_ALIAS_NAME = ".all";
    private static final ESLogger LOGGER = Loggers.getLogger(KibanaSeed.class);

    public static final String DEFAULT_INDEX_FIELD = "defaultIndex";

    private final IndexMappingLoader mappingLoader;
    private final PluginClient pluginClient;
    private final String defaultKibanaIndex;
    private final PluginSettings settings;

    @Inject
    public KibanaSeed(final PluginSettings settings, final IndexMappingLoader loader, final PluginClient pluginClient)  {
        this.mappingLoader = loader;
        this.pluginClient = pluginClient;
        this.defaultKibanaIndex = settings.getDefaultKibanaIndex();
        this.settings = settings;
    }

    public void setDashboards(final OpenshiftRequestContext context, Client client, String kibanaVersion, final String projectPrefix) {

        LOGGER.debug("Begin setDashboards:  projectPrefix '{}' for user '{}' projects '{}' kibanaIndex '{}'",
                projectPrefix, context.getUser(), context.getProjects(), context.getKibanaIndex());

        // We want to seed the Kibana user index initially
        // since the logic from Kibana has changed to create before this plugin
        // starts...
        boolean changed = initialSeedKibanaIndex(context, client);

        // GET .../.kibana/index-pattern/_search?pretty=true&fields=
        // compare results to projects; handle any deltas (create, delete?)

        Set<String> indexPatterns = getProjectNamesFromIndexes(context, client, projectPrefix);
        LOGGER.debug("Found '{}' Index patterns for user", indexPatterns.size());

        Set<String> projects = new HashSet<>(context.getProjects());
        List<String> filteredProjects = new ArrayList<String>(filterProjectsWithIndices(projectPrefix, projects));
        LOGGER.debug("projects for '{}' that have existing indexes: '{}'", context.getUser(), filteredProjects);

        addAliasToAllProjects(context, filteredProjects);
        Collections.sort(filteredProjects);
        
        // If none have been set yet
        if (indexPatterns.isEmpty()) {
            create(context.getKibanaIndex(), filteredProjects, true, client, kibanaVersion, projectPrefix);
            changed = true;
        } else {
            
            List<String> common = new ArrayList<String>(indexPatterns);

            common.retainAll(filteredProjects);

            filteredProjects.removeAll(common);
            indexPatterns.removeAll(common);

            // if we aren't a cluster-admin, make sure we're deleting the
            // ADMIN_ALIAS_NAME
            if (!context.isOperationsUser()) {
                LOGGER.debug("user is not a cluster admin, ensure they don't keep/have the admin alias pattern");
                indexPatterns.add(ADMIN_ALIAS_NAME);
            }

            // check if we're going to be adding or removing any projects
            if (!filteredProjects.isEmpty() || !indexPatterns.isEmpty()) {
                changed = true;
            }

            // for any to create (remaining in projects) call createIndices, createSearchmapping?, create dashboard
            create(context.getKibanaIndex(), filteredProjects, false, client, kibanaVersion, projectPrefix);

            // cull any that are in ES but not in OS (remaining in indexPatterns)
            remove(context.getKibanaIndex(), indexPatterns, client, projectPrefix);

            common.addAll(filteredProjects);
            Collections.sort(common);
            // Set default index to first index in common if we removed the default
            String defaultIndex = getDefaultIndex(context, client, kibanaVersion, projectPrefix);

            LOGGER.debug("Checking if index patterns '{}' contain default index '{}'", indexPatterns, defaultIndex);

            if ( indexPatterns.contains(defaultIndex) || StringUtils.isEmpty(defaultIndex) ) {
                LOGGER.debug("'{}' does contain '{}' and common size is {}", indexPatterns, defaultIndex, common.size());
                if ( !common.isEmpty() ) {
                    setDefaultIndex(context.getKibanaIndex(), common.get(0), client, kibanaVersion, projectPrefix);
                }
            }
        }

        if ( changed ) {
            refreshKibanaUser(context.getKibanaIndex(), client);
        }
    }
    
    private void addAliasToAllProjects(final OpenshiftRequestContext context, List<String> filteredProjects) {
        String projectPrefix = settings.getCdmProjectPrefix();
        if (context.isOperationsUser()) {
            // Check roles here, if user is a cluster-admin we should add
            LOGGER.debug("Adding indexes to alias '{}' for user '{}'", ADMIN_ALIAS_NAME, context.getUser());
            buildAdminAlias(filteredProjects, projectPrefix);
            filteredProjects.add(ADMIN_ALIAS_NAME);
            filteredProjects.add(OPERATIONS_PROJECT);
        } else {
            if (filteredProjects.isEmpty()) {
                filteredProjects.add(BLANK_PROJECT);
            } else {
                // only add alias if kibana index mode is UNIQUE
                if(context.getKibanaIndexMode() == UNIQUE) {
                    String alias = UserRolesSyncStrategy.formatAllAlias(context.getUser());
                    LOGGER.debug("Adding indexes to alias '{}' for user '{}'", alias, context.getUser());
                    buildUserAlias(filteredProjects, projectPrefix, alias);
                    filteredProjects.add(alias);
                }
            }
        }
    }
    
    /*
     * Given a list of projects, filter out those which do not have any
     * index associated with it
     */
    private List<String> filterProjectsWithIndices(final String projectPrefix, Set<String> projects){
        List<String> result = new ArrayList<>(projects.size());
        for (String project : projects) {
            String index = getIndexPattern(project, projectPrefix);
            if (pluginClient.indexExists(index)) {
                result.add(project);
            }<commit_msg>bug 1490719. Operations missing from .all alias<commit_after>/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.fabric8.elasticsearch.plugin.kibana;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.RemoteTransportException;

import com.floragunn.searchguard.support.ConfigConstants;

import io.fabric8.elasticsearch.plugin.ConfigurationSettings;
import io.fabric8.elasticsearch.plugin.OpenshiftRequestContextFactory.OpenshiftRequestContext;
import io.fabric8.elasticsearch.plugin.PluginClient;
import io.fabric8.elasticsearch.plugin.PluginSettings;
import io.fabric8.elasticsearch.plugin.acl.UserRolesSyncStrategy;

public class KibanaSeed implements ConfigurationSettings {


    private static final String DEFAULT_INDEX_TYPE = "config";
    private static final String INDICIES_TYPE = "index-pattern";

    private static final String OPERATIONS_PROJECT = ".operations";
    private static final String BLANK_PROJECT = ".empty-project";
    private static final String ADMIN_ALIAS_NAME = ".all";
    private static final ESLogger LOGGER = Loggers.getLogger(KibanaSeed.class);

    public static final String DEFAULT_INDEX_FIELD = "defaultIndex";

    private final IndexMappingLoader mappingLoader;
    private final PluginClient pluginClient;
    private final String defaultKibanaIndex;
    private final PluginSettings settings;

    @Inject
    public KibanaSeed(final PluginSettings settings, final IndexMappingLoader loader, final PluginClient pluginClient)  {
        this.mappingLoader = loader;
        this.pluginClient = pluginClient;
        this.defaultKibanaIndex = settings.getDefaultKibanaIndex();
        this.settings = settings;
    }

    public void setDashboards(final OpenshiftRequestContext context, Client client, String kibanaVersion, final String projectPrefix) {

        LOGGER.debug("Begin setDashboards:  projectPrefix '{}' for user '{}' projects '{}' kibanaIndex '{}'",
                projectPrefix, context.getUser(), context.getProjects(), context.getKibanaIndex());

        // We want to seed the Kibana user index initially
        // since the logic from Kibana has changed to create before this plugin
        // starts...
        boolean changed = initialSeedKibanaIndex(context, client);

        // GET .../.kibana/index-pattern/_search?pretty=true&fields=
        // compare results to projects; handle any deltas (create, delete?)

        Set<String> indexPatterns = getProjectNamesFromIndexes(context, client, projectPrefix);
        LOGGER.debug("Found '{}' Index patterns for user", indexPatterns.size());

        Set<String> projects = new HashSet<>(context.getProjects());
        List<String> filteredProjects = new ArrayList<String>(filterProjectsWithIndices(projectPrefix, projects));
        LOGGER.debug("projects for '{}' that have existing indexes: '{}'", context.getUser(), filteredProjects);

        addAliasToAllProjects(context, filteredProjects);
        Collections.sort(filteredProjects);
        
        // If none have been set yet
        if (indexPatterns.isEmpty()) {
            create(context.getKibanaIndex(), filteredProjects, true, client, kibanaVersion, projectPrefix);
            changed = true;
        } else {
            
            List<String> common = new ArrayList<String>(indexPatterns);

            common.retainAll(filteredProjects);

            filteredProjects.removeAll(common);
            indexPatterns.removeAll(common);

            // if we aren't a cluster-admin, make sure we're deleting the
            // ADMIN_ALIAS_NAME
            if (!context.isOperationsUser()) {
                LOGGER.debug("user is not a cluster admin, ensure they don't keep/have the admin alias pattern");
                indexPatterns.add(ADMIN_ALIAS_NAME);
            }

            // check if we're going to be adding or removing any projects
            if (!filteredProjects.isEmpty() || !indexPatterns.isEmpty()) {
                changed = true;
            }

            // for any to create (remaining in projects) call createIndices, createSearchmapping?, create dashboard
            create(context.getKibanaIndex(), filteredProjects, false, client, kibanaVersion, projectPrefix);

            // cull any that are in ES but not in OS (remaining in indexPatterns)
            remove(context.getKibanaIndex(), indexPatterns, client, projectPrefix);

            common.addAll(filteredProjects);
            Collections.sort(common);
            // Set default index to first index in common if we removed the default
            String defaultIndex = getDefaultIndex(context, client, kibanaVersion, projectPrefix);

            LOGGER.debug("Checking if index patterns '{}' contain default index '{}'", indexPatterns, defaultIndex);

            if ( indexPatterns.contains(defaultIndex) || StringUtils.isEmpty(defaultIndex) ) {
                LOGGER.debug("'{}' does contain '{}' and common size is {}", indexPatterns, defaultIndex, common.size());
                if ( !common.isEmpty() ) {
                    setDefaultIndex(context.getKibanaIndex(), common.get(0), client, kibanaVersion, projectPrefix);
                }
            }
        }

        if ( changed ) {
            refreshKibanaUser(context.getKibanaIndex(), client);
        }
    }
    
    private void addAliasToAllProjects(final OpenshiftRequestContext context, List<String> filteredProjects) {
        String projectPrefix = settings.getCdmProjectPrefix();
        if (context.isOperationsUser()) {
            // Check roles here, if user is a cluster-admin we should add
            LOGGER.debug("Adding indexes to alias '{}' for user '{}'", ADMIN_ALIAS_NAME, context.getUser());
            filteredProjects.add(OPERATIONS_PROJECT);
            buildAdminAlias(filteredProjects, projectPrefix);
        } else {
            if (filteredProjects.isEmpty()) {
                filteredProjects.add(BLANK_PROJECT);
            } else {
                // only add alias if kibana index mode is UNIQUE
                if(context.getKibanaIndexMode() == UNIQUE) {
                    String alias = UserRolesSyncStrategy.formatAllAlias(context.getUser());
                    LOGGER.debug("Adding indexes to alias '{}' for user '{}'", alias, context.getUser());
                    buildUserAlias(filteredProjects, projectPrefix, alias);
                    filteredProjects.add(alias);
                }
            }
        }
    }
    
    /*
     * Given a list of projects, filter out those which do not have any
     * index associated with it
     */
    private List<String> filterProjectsWithIndices(final String projectPrefix, Set<String> projects){
        List<String> result = new ArrayList<>(projects.size());
        for (String project : projects) {
            String index = getIndexPattern(project, projectPrefix);
            if (pluginClient.indexExists(index)) {
                result.add(project);
            }
{'fraction_non_alphanumeric': 0.09271746459878624, 'fraction_numerical': 0.0020791189031242976, 'mean_word_length': 3.2083234807283048, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '5452433', 'n_tokens_mistral': 4595, 'n_tokens_neox': 4532, 'n_words': 1197}