add logger

This commit is contained in:
Dmitry Belyaev 2024-09-12 19:24:20 +03:00
parent 0ce539f956
commit 5c59a5126b
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
3 changed files with 116 additions and 12 deletions

79
Cargo.lock generated
View File

@ -17,6 +17,15 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "android-tzdata"
version = "0.1.1"
@ -194,7 +203,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bollard",
"flexi_logger",
"futures-util",
"log",
"log-panics",
"serde",
"tokio",
"tokio-macros",
@ -206,6 +218,20 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "flexi_logger"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a250587a211932896a131f214a4f64c047b826ce072d2018764e5ff5141df8fa"
dependencies = [
"chrono",
"glob",
"log",
"nu-ansi-term",
"regex",
"thiserror",
]
[[package]]
name = "fnv"
version = "1.0.7"
@ -290,6 +316,12 @@ version = "0.31.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64"
[[package]]
name = "glob"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
[[package]]
name = "hashbrown"
version = "0.12.3"
@ -548,6 +580,15 @@ version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "log-panics"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f9dd8546191c1850ecf67d22f5ff00a935b890d0e84713159a55495cc2ac5f"
dependencies = [
"log",
]
[[package]]
name = "memchr"
version = "2.7.4"
@ -575,6 +616,15 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "num-conv"
version = "0.1.0"
@ -705,6 +755,35 @@ dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
[[package]]
name = "ring"
version = "0.17.8"

View File

@ -6,7 +6,10 @@ edition = "2021"
[dependencies]
anyhow = "1.0.88"
bollard = { version = "0.17.1", features = ["ssl", "json_data_content", "tokio-stream"] }
flexi_logger = "0.29.0"
futures-util = "0.3.30"
log = "0.4.22"
log-panics = "2.1.0"
serde = "1.0.210"
tokio = {version = "1.40.0", features = ["full"]}
tokio-macros = "2.4.0"

View File

@ -1,3 +1,4 @@
use anyhow::Context;
use bollard::container::ListContainersOptions;
use bollard::Docker;
@ -9,6 +10,8 @@ use std::default::Default;
use tokio::time::{timeout, Instant};
use flexi_logger::{AdaptiveFormat, Logger, LoggerHandle};
use std::sync::Arc;
use std::time::Duration;
@ -24,6 +27,18 @@ fn get_query_options() -> ListContainersOptions<&'static str> {
}
}
fn create_logger() -> anyhow::Result<LoggerHandle> {
let logger = Logger::try_with_str("info")
.context("default logging level invalid")?
.format(flexi_logger::detailed_format)
.adaptive_format_for_stdout(AdaptiveFormat::Detailed)
.log_to_stdout()
.start()
.context("can't start logger");
log_panics::init();
logger
}
async fn query_containers<T>(
connection: &Docker,
query_options: ListContainersOptions<T>,
@ -55,7 +70,7 @@ async fn query_task(
) {
let query_options = get_query_options();
let mut query_time = Duration::new(0, 0);
println!("start recv");
log::debug!("query_task -> start recv");
while (timeout(interval - query_time, shutdown_rx.recv()).await).is_err() {
let start = Instant::now();
@ -82,7 +97,7 @@ async fn filter_task(
while let Some(containers) = in_rx.recv().await {
let now = Instant::now();
println!("filter -> found unhealthy: {}", containers.len());
log::info!("filter -> found unhealthy: {}", containers.len());
let prev_times = unhealthy_time.take().unwrap();
let mut new_times: HashMap<String, Instant> = prev_times
@ -102,7 +117,7 @@ async fn filter_task(
let _ = unhealthy_time.replace(new_times);
println!("filter -> filtered unhealthy: {}", containers.len());
log::info!("filter -> filtered unhealthy: {}", containers.len());
if containers.is_empty() {
continue;
@ -116,15 +131,15 @@ async fn filter_task(
}
async fn restart_task(connection: Arc<Docker>, mut rx: mpsc::Receiver<Containers>) {
println!("restart task start");
log::debug!("restart task start");
while let Some(containers) = rx.recv().await {
println!("restart -> found: {}", containers.len());
log::info!("restart -> found: {}", containers.len());
for container_id in containers {
print!("restart -> container: {}...", &container_id);
log::warn!("restart -> container: {}...", &container_id);
let res = restart_container(&connection, container_id.as_str()).await;
match res {
Ok(_) => println!("ok\n"),
Err(e) => println!("error: \n{e:?}\n"),
Ok(_) => log::info!("ok\n"),
Err(e) => log::error!("error: \n{e:?}\n"),
}
}
}
@ -132,7 +147,15 @@ async fn restart_task(connection: Arc<Docker>, mut rx: mpsc::Receiver<Containers
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let logger = create_logger()?;
let connection = Arc::new(Docker::connect_with_defaults()?);
let _ = connection
.as_ref()
.ping()
.await
.context("ping on docker connection")?;
let query_connection = connection.clone();
let restart_connection = connection.clone();
@ -154,15 +177,14 @@ async fn main() -> anyhow::Result<()> {
tokio::spawn(filter_task(unhealthy_timeout, filter_rx, filter_tx)),
tokio::spawn(restart_task(restart_connection, restart_rx)),
tokio::spawn(async {
println!("shutdown -> sleep");
log::debug!("shutdown -> sleep");
tokio::time::sleep(Duration::from_secs(80)).await;
println!("shutdown -> drop");
log::warn!("shutdown -> drop");
drop(shutdown_tx);
})
)?;
//let restart = restart_container(&connection, container_id.as_str()).await;
//println!("restart: {}", restart.is_ok());
drop(logger);
Ok(())
}