TinyHealthHttpHandler.java

/*
 * Copyright 2023 Morimekta Utils Authors
 *
 * 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.health;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import net.morimekta.tiny.http.TinyHttpHandler;
import net.morimekta.tiny.http.TinyHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static net.morimekta.tiny.health.TinyHealthStatus.ERROR;
import static net.morimekta.tiny.http.TinyHttpStatus.SC_INTERNAL;
import static net.morimekta.tiny.http.TinyHttpStatus.SC_OK;

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

    private final Map<String, TinyHealthCheck> healthChecks;

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

    @Override
    protected void doGet(HttpExchange exchange) throws IOException {
        var params = TinyHttpUtil.getExchangeQuery(exchange);
        var out = new TreeMap<String, TinyHealthResult>();
        var status = new AtomicInteger(SC_OK);
        healthChecks.forEach((name, check) -> {
            try {
                var result = check.healthCheck();
                if (result.getStatus() != TinyHealthStatus.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 TinyHealthResult(ERROR, e.getClass().getSimpleName() + ": " + e.getMessage()));
                status.set(SC_INTERNAL);
            }
        });
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(status.get(), 0);
        try (var os = exchange.getResponseBody()) {
            if (params.get("pretty") != null) {
                os.write((MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(out) + "\n")
                        .getBytes(StandardCharsets.UTF_8));
            } else {
                MAPPER.writeValue(os, out);
            }
        }
    }

    static final ObjectMapper MAPPER = new ObjectMapper();
}