001/*
002 * Copyright 2012-2018 the original author or authors.
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
017package org.springframework.boot.actuate.elasticsearch;
018
019import com.google.gson.JsonElement;
020import com.google.gson.JsonParser;
021import io.searchbox.client.JestClient;
022import io.searchbox.client.JestResult;
023
024import org.springframework.boot.actuate.health.AbstractHealthIndicator;
025import org.springframework.boot.actuate.health.Health;
026import org.springframework.boot.actuate.health.HealthIndicator;
027
028/**
029 * {@link HealthIndicator} for Elasticsearch using a {@link JestClient}.
030 *
031 * @author Stephane Nicoll
032 * @author Julian Devia Serna
033 * @author Brian Clozel
034 * @since 2.0.0
035 */
036public class ElasticsearchJestHealthIndicator extends AbstractHealthIndicator {
037
038        private final JestClient jestClient;
039
040        private final JsonParser jsonParser = new JsonParser();
041
042        public ElasticsearchJestHealthIndicator(JestClient jestClient) {
043                super("Elasticsearch health check failed");
044                this.jestClient = jestClient;
045        }
046
047        @Override
048        protected void doHealthCheck(Health.Builder builder) throws Exception {
049                JestResult healthResult = this.jestClient
050                                .execute(new io.searchbox.cluster.Health.Builder().build());
051                if (healthResult.getResponseCode() != 200 || !healthResult.isSucceeded()) {
052                        builder.down();
053                }
054                else {
055                        JsonElement root = this.jsonParser.parse(healthResult.getJsonString());
056                        JsonElement status = root.getAsJsonObject().get("status");
057                        if (status.getAsString()
058                                        .equals(io.searchbox.cluster.Health.Status.RED.getKey())) {
059                                builder.outOfService();
060                        }
061                        else {
062                                builder.up();
063                        }
064                }
065        }
066
067}