TinyHealthHttpHandler.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 net.morimekta.tiny.server.http;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

import static net.morimekta.tiny.server.http.TinyHealth.Status.ERROR;
import static net.morimekta.tiny.server.http.TinyHttpStatus.SC_INTERNAL;
import static net.morimekta.tiny.server.http.TinyHttpStatus.SC_OK;

/**
 * Simple HTTP handler for getting the healthiness of the entire tiny server.
 */
public final class TinyHealthHttpHandler extends TinyHttpHandler {
    private final static Logger LOGGER = LoggerFactory.getLogger(TinyHealthHttpHandler.class);

    private final Map<String, TinyHealth.HealthCheck> healthChecks;

    /**
     * @param healthChecks Map of healthiness checks to be checked by the service.
     */
    public TinyHealthHttpHandler(Map<String, TinyHealth.HealthCheck> healthChecks) {
        this.healthChecks = healthChecks;
    }

    @Override
    protected void doGet(HttpExchange exchange) throws IOException {
        var out = new TreeMap<String, TinyHealth.Result>();
        var status = new AtomicInteger(SC_OK);
        healthChecks.forEach((name, check) -> {
            try {
                var result = check.healthCheck();
                if (result.getStatus() != TinyHealth.Status.OK) {
                    LOGGER.warn("Non OK result: {}", result);
                    status.set(SC_INTERNAL);
                }
                out.put(name, result);
            } catch (Exception e) {
                LOGGER.warn("Exception in healthCheck(): {}", e.getMessage(), e);
                out.put(name,
                        new TinyHealth.Result(ERROR, e.getClass().getSimpleName() + ": " + e.getMessage()));
                status.set(SC_INTERNAL);
            }
        });
        var data = MAPPER.writeValueAsBytes(out);
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(status.get(), data.length);
        try (var os = exchange.getResponseBody()) {
            os.write(data);
        }
    }

    static final ObjectMapper MAPPER = new ObjectMapper();
}