kayak 0.3.0

A virtual IP manager using etcd
// SPDX-License-Identifier: MPL-2.0

use metrics::{Gauge, gauge};

use super::Health;

pub struct HealthTracker {
    health: Health,
    counter: u32,
    success_threshold: u32,
    failure_threshold: u32,
    gauge: Gauge,
}

impl HealthTracker {
    pub fn new(initial_health: Health, success_threshold: u32, failure_threshold: u32) -> HealthTracker {
        let initial_status = match initial_health {
            Health::Healthy => 1,
            Health::Unhealthy => 0,
        };

        let gauge = gauge!("kayak_overall_health_checks_status");
        gauge.set(initial_status);

        HealthTracker {
            health: initial_health,
            counter: 0,
            success_threshold,
            failure_threshold,
            gauge,
        }
    }

    pub fn failure(&mut self) -> Health {
        if self.health == Health::Healthy {
            self.counter += 1;
            log::warn!("Health check {}/{} failed", self.counter, self.failure_threshold);
            if self.counter >= self.failure_threshold {
                log::warn!("Health checks are now unhealthy");
                self.health = Health::Unhealthy;
                self.counter = 0;
                self.gauge.set(0);
            }
        }
        // If we are already unhealthy then an extra failure changes nothing
        self.health
    }

    pub fn success(&mut self) -> Health {
        if self.health == Health::Unhealthy {
            self.counter += 1;
            log::info!("Health check {}/{} succeeded", self.counter, self.success_threshold);
            if self.counter >= self.success_threshold {
                log::info!("Health checks are now healthy");
                self.health = Health::Healthy;
                self.counter = 0;
                self.gauge.set(1);
            }
        }
        // If we are already healthy then an extra success changes nothing
        self.health
    }
}