001/*
002 * (C) Copyright 2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Mariana Cedica
018 */
019package org.nuxeo.elasticsearch.status;
020
021import java.util.List;
022
023import org.elasticsearch.cluster.health.ClusterHealthStatus;
024import org.nuxeo.ecm.core.api.NuxeoException;
025import org.nuxeo.elasticsearch.api.ElasticSearchAdmin;
026import org.nuxeo.runtime.api.Framework;
027import org.nuxeo.runtime.management.api.Probe;
028import org.nuxeo.runtime.management.api.ProbeStatus;
029
030/**
031 * Probe to check the status of the ES cluster. Returns success if the cluster is GREEN or YELLOW, Failure otherwise
032 *
033 * @since 9.3
034 */
035public class ElasticSearchStatusProbe implements Probe {
036
037    @Override
038    public ProbeStatus run() {
039        String[] indices = getIndexNames();
040        try {
041            ClusterHealthStatus clusterStatus = Framework.getService(ElasticSearchAdmin.class)
042                                                         .getClient()
043                                                         .getHealthStatus(indices);
044            switch (clusterStatus) {
045            case GREEN:
046            case YELLOW:
047                return ProbeStatus.newSuccess(clusterStatus.toString());
048            default:
049                return ProbeStatus.newFailure(clusterStatus.toString());
050            }
051        } catch (NuxeoException e) {
052            return ProbeStatus.newError(e);
053        }
054    }
055
056    protected String[] getIndexNames() {
057        ElasticSearchAdmin esa = Framework.getService(ElasticSearchAdmin.class);
058        List<String> repositoryNames = Framework.getService(ElasticSearchAdmin.class).getRepositoryNames();
059        String indices[] = new String[repositoryNames.size()];
060        int i = 0;
061        for (String repo : repositoryNames) {
062            indices[i++] = esa.getIndexNameForRepository(repo);
063        }
064        return indices;
065    }
066
067}