kayak 0.3.0

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

use std::path::PathBuf;
use std::time::Duration;

use anyhow::Result;
use clap::Parser;
use config::Config;
use env_logger::{Builder, Env};
use metrics_exporter_prometheus::PrometheusBuilder;
use tokio::task::JoinSet;

use address::assigner::AddressAssigner;
use address::broadcaster::AddressBroadcaster;
use health::Health;
use health::checker::HealthChecker;
use health::tracker::HealthTracker;
use monitoring::ReadyState;

mod address;
mod config;
mod etcd;
mod health;
mod monitoring;
mod notify;
mod signal;

#[derive(Parser)]
#[command(version, about)]
struct Cli {
    #[arg(short, long, value_name = "FILE")]
    config: PathBuf,
}

#[tokio::main]
async fn main() -> Result<()> {
    Builder::from_env(Env::default().default_filter_or("info")).init();
    let mut signal_handlers = signal::SignalHandlers::new()?;

    let cli = Cli::parse();
    let config = Config::new(&cli.config)?;

    // Initialize this early so we can get metrics
    let builder = PrometheusBuilder::new();
    let handle = builder
        .install_recorder()
        .expect("Failed to install Prometheus recorder");

    let link_name = config.vip.network_link;
    let cidr = config.vip.cidr;

    let assigner = AddressAssigner::new(link_name.to_owned(), cidr)?;
    // It's possible that we had the address last time and are now restarting
    // from a horrible crash, so remove the address to be safe since we don't
    // have the lock yet.
    assigner.remove().await?;

    let broadcaster = AddressBroadcaster::new(&link_name, cidr.ip())?;

    let keep_alive_period = Duration::from_secs(config.etcd.lease.keep_alive_period_seconds.get().into());
    let broadcast_period = Duration::from_secs(config.vip.broadcast_period_seconds.get().into());
    let healthcheck_period = Duration::from_secs(config.healthcheck.period_seconds.get().into());

    let initial_health = Health::Unhealthy;
    let (health_sender, health_receiver) = tokio::sync::watch::channel(initial_health);

    let tracker = HealthTracker::new(
        initial_health,
        config.healthcheck.success_threshold.get(),
        config.healthcheck.failure_threshold.get(),
    );

    let checker = HealthChecker::new(config.healthcheck)?;

    let mut set = JoinSet::new();

    // Start the watchdog now, since connecting to etcd uses the network and
    // that could take a while
    notify::start_watchdog(&mut set);

    let mut ready_state = ReadyState::new();

    if let Some(monitoring) = config.monitoring {
        set.spawn(monitoring::run_server(
            monitoring.ip,
            monitoring.port,
            ready_state.clone(),
            handle,
        ));
    }

    let ttl: i64 = config.etcd.lease.time_to_live_seconds.get().into();

    let mut etcd_client = etcd::client::new_client(&config.etcd).await?;
    let lease_id = etcd::lease::try_to_create_lease(&mut etcd_client, &config.etcd.retry, ttl).await?;

    set.spawn(etcd::lease::lease_keep_alive_loop(
        etcd_client.clone(),
        config.etcd.retry,
        lease_id,
        keep_alive_period,
    ));
    set.spawn(etcd::lock::address_lock_loop(
        etcd_client.clone(),
        lease_id,
        config.etcd.retry,
        broadcast_period,
        assigner.clone(),
        broadcaster,
        health_receiver,
    ));
    set.spawn(health::health_check_loop(
        healthcheck_period,
        checker,
        tracker,
        health_sender,
    ));

    ready_state.ready();
    notify::ready()?;

    let result = tokio::select! {
        signal = signal_handlers.wait_for_signal() => {
            log::info!("Received {signal}, shutting down");
            Ok(())
        }
        result = set.join_next() => {
            log::error!("Task failed, shutting down");
            result.unwrap()
        }
    };

    ready_state.not_ready();
    notify::stopping()?;

    set.shutdown().await;

    // It's possible that the shutdown prevented us from removing the address,
    // so do it now to be safe.
    if let Err(e) = assigner.remove().await {
        log::error!("{e:#}");
    }

    // It's also possible that the shutdown prevented us from releasing the
    // lock, so revoke the lease to expire it.
    if let Err(e) = etcd::lease::try_to_revoke_lease(&mut etcd_client, &config.etcd.retry, lease_id).await {
        log::error!("{e:#}");
    }

    Ok(result?)
}