1
0
mirror of https://github.com/pcvolkmer/checkbar.git synced 2025-04-19 11:06:50 +00:00

Initial commit

This commit is contained in:
Paul-Christian Volkmer 2022-03-04 14:18:15 +01:00
commit fb312d2102
6 changed files with 209 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

28
Cargo.toml Normal file
View File

@ -0,0 +1,28 @@
[package]
name = "checkbar"
version = "0.1.0"
edition = "2021"
author = "Paul-Christian Volkmer <code@pcvolkmer.de>"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dirs = "4"
serde = { version = "1", features = ["derive"] }
chrono = { version = "*", features = ["serde"] }
tokio = { version = "1", features = ["full"] }
toml = "*"
[dependencies.reqwest]
version = "*"
features = ["json", "rustls-tls"]
default-features = false
[dev-dependencies]
serde_derive = "1"
[profile.release]
opt-level = "s"
codegen-units = 1
lto = "thin"
strip = "debuginfo"

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Paul-Christian Volkmer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

34
README.adoc Normal file
View File

@ -0,0 +1,34 @@
= Checkbar
This tool shows up/warn/down state of configured hosts or applications using i3bar input protocol.
image::checkbar.png[]
== Usage
You should create a configuration file `.checkbar.toml` in your home directory, e.g.
----
# Update interval in seconds. Default value if not set is 60 sec.
interval = 60
[[checks]]
name = "Host 1"
url = "https://host1.example.com"
[[checks]]
name = "Host 2"
url = "https://host2.example.com"
[[checks]]
name = "App 1"
url = "https://app.example.com/actuator/health"
check_type = "Actuator"
----
Each host or application to be checked constists of `name` and `url`.
You can optionally specify `check_type`:
* `Html`: Default value, checks if a request is succeessful and returns HTTP OK - 200.
* `Actuator`: Like `Html`, but checks if _Actuator_ shows that the application is up and running.

BIN
checkbar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

125
src/main.rs Normal file
View File

@ -0,0 +1,125 @@
use serde::Deserialize;
use std::fmt::{Display, Formatter, Result};
use std::time::Duration;
#[derive(Deserialize)]
struct Config {
interval: Option<u64>,
checks: Vec<CheckConfig>,
}
#[derive(Deserialize)]
struct CheckConfig {
name: String,
url: String,
check_type: Option<CheckType>,
}
#[derive(Deserialize)]
enum CheckType {
Http,
Actuator,
}
#[derive(Deserialize)]
struct ActuatorResponse {
status: String,
}
struct CheckResult {
name: String,
state: CheckState,
}
impl Display for CheckResult {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let color = match &self.state {
CheckState::Up => "#00FF00",
CheckState::Warn => "#FFFF00",
CheckState::Down => "#FF0000",
};
write!(
f,
"{{\"full_text\":\"{}\",\"separator_block_width\":16,\"color\":\"{}\"}}",
self.name, color
)
}
}
enum CheckState {
Up,
Warn,
Down,
}
async fn check_host(check_config: &CheckConfig) -> CheckResult {
let state = match reqwest::get(check_config.url.as_str()).await {
Ok(r) => {
if r.status().is_success() {
match check_config.check_type {
Some(CheckType::Actuator) => match r.json::<ActuatorResponse>().await {
Ok(ar) => {
if ar.status == "OK" {
CheckState::Up
} else {
CheckState::Warn
}
}
_ => CheckState::Warn,
},
// Default: HTTP
_ => CheckState::Up,
}
} else {
CheckState::Warn
}
}
Err(_) => CheckState::Down,
};
CheckResult {
name: check_config.name.to_string(),
state,
}
}
async fn print_states(check_configs: &[CheckConfig]) {
print!("[");
let mut entries = vec![];
for check_config in check_configs {
entries.push(format!("{}", check_host(check_config).await));
}
entries.push(format!(
"{{\"full_text\":\"check@{}\"}}",
chrono::Local::now().format("%H:%M")
));
println!("{}],", entries.join(","));
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
println!("{{\"version\":1,\"click_events\":false}}");
println!("[");
loop {
let home_dir = dirs::home_dir().unwrap();
let config = match std::fs::read_to_string(format!(
"{}/.checkbar.toml",
home_dir.to_str().unwrap_or("")
)) {
Ok(config) => match toml::from_str(config.as_str()) {
Ok(config) => config,
Err(_e) => Config {
interval: None,
checks: vec![],
},
},
Err(_e) => Config {
interval: None,
checks: vec![],
},
};
print_states(&config.checks).await;
std::thread::sleep(Duration::from_secs(config.interval.unwrap_or(60)));
}
}