package com.codahale.metrics.health;
import com.codahale.metrics.health.annotation.Async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static com.codahale.metrics.health.HealthCheck.Result;
public class HealthCheckRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class);
private static final int ASYNC_EXECUTOR_POOL_SIZE = 2;
private final ConcurrentMap<String, HealthCheck> healthChecks;
private final List<HealthCheckRegistryListener> listeners;
private final ScheduledExecutorService asyncExecutorService;
private final Object lock = new Object();
public HealthCheckRegistry() {
this(ASYNC_EXECUTOR_POOL_SIZE);
}
public HealthCheckRegistry(int asyncExecutorPoolSize) {
this(createExecutorService(asyncExecutorPoolSize));
}
public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) {
this.healthChecks = new ConcurrentHashMap<>();
this.listeners = new CopyOnWriteArrayList<>();
this.asyncExecutorService = asyncExecutorService;
}
public void addListener(HealthCheckRegistryListener listener) {
listeners.add(listener);
for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
listener.onHealthCheckAdded(entry.getKey(), entry.getValue());
}
}
public void removeListener(HealthCheckRegistryListener listener) {
listeners.remove(listener);
}
public void register(String name, HealthCheck healthCheck) {
HealthCheck registered;
synchronized (lock) {
if (healthChecks.containsKey(name)) {
throw new IllegalArgumentException("A health check named " + name + " already exists");
}
registered = healthCheck;
if (healthCheck.getClass().isAnnotationPresent(Async.class)) {
registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService);
}
healthChecks.put(name, registered);
}
onHealthCheckAdded(name, registered);
}
public void unregister(String name) {
HealthCheck healthCheck;
synchronized (lock) {
healthCheck = healthChecks.remove(name);
if (healthCheck instanceof AsyncHealthCheckDecorator) {
((AsyncHealthCheckDecorator) healthCheck).tearDown();
}
}
if (healthCheck != null) {
onHealthCheckRemoved(name, healthCheck);
}
}
public SortedSet<String> getNames() {
return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet()));
}
public HealthCheck getHealthCheck(String name) {
return healthChecks.get(name);
}
public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException {
final HealthCheck healthCheck = healthChecks.get(name);
if (healthCheck == null) {
throw new NoSuchElementException("No health check named " + name + " exists");
}
return healthCheck.execute();
}
public SortedMap<String, HealthCheck.Result> runHealthChecks() {
return runHealthChecks(HealthCheckFilter.ALL);
}
public SortedMap<String, HealthCheck.Result> runHealthChecks(HealthCheckFilter filter) {
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
final Result result = entry.getValue().execute();
results.put(entry.getKey(), result);
}
}
return Collections.unmodifiableSortedMap(results);
}
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor) {
return runHealthChecks(executor, HealthCheckFilter.ALL);
}
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor, HealthCheckFilter filter) {
final Map<String, Future<HealthCheck.Result>> futures = new HashMap<>();
for (final Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
futures.put(name, executor.submit(() -> healthCheck.execute()));
}
}
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, Future<Result>> entry : futures.entrySet()) {
try {
results.put(entry.getKey(), entry.getValue().get());
} catch (Exception e) {
LOGGER.warn("Error executing health check {}", entry.getKey(), e);
results.put(entry.getKey(), HealthCheck.Result.unhealthy(e));
}
}
return Collections.unmodifiableSortedMap(results);
}
private void onHealthCheckAdded(String name, HealthCheck healthCheck) {
for (HealthCheckRegistryListener listener : listeners) {
listener.onHealthCheckAdded(name, healthCheck);
}
}
private void onHealthCheckRemoved(String name, HealthCheck healthCheck) {
for (HealthCheckRegistryListener listener : listeners) {
listener.onHealthCheckRemoved(name, healthCheck);
}
}
public void shutdown() {
asyncExecutorService.shutdown();
try {
if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) {
asyncExecutorService.shutdownNow();
}
} catch (InterruptedException ie) {
asyncExecutorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
private static ScheduledExecutorService createExecutorService(int corePoolSize) {
final ScheduledThreadPoolExecutor asyncExecutorService = new ScheduledThreadPoolExecutor(corePoolSize,
new NamedThreadFactory("healthcheck-async-executor-"));
asyncExecutorService.setRemoveOnCancelPolicy(true);
return asyncExecutorService;
}
private static class NamedThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
NamedThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}