Skip to content

Commit

Permalink
refactor: add notification level for webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Apr 28, 2024
1 parent f5fe9dd commit 01b9de4
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 11 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pingap"
version = "0.3.0"
version = "0.3.1"
authors = ["Tree Xie <[email protected]>"]
edition = "2021"
categories = ["network-programming", "web-programming::http-server"]
Expand Down
3 changes: 2 additions & 1 deletion src/acme/lets_encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,8 @@ async fn new_lets_encrypt(domains: &[String]) -> Result<()> {
let buf = serde_json::to_vec(&info).map_err(|e| Error::SerdeJson { source: e })?;
f.write(&buf).await.map_err(|e| Error::Io { source: e })?;
info!("Write cert success, {path:?}");
webhook::send(webhook::WebhookSendParams {
webhook::send(webhook::SendNotificationParams {
level: webhook::NotificationLevel::Info,
category: "lets_encrypt".to_string(),
msg: "Generate new cert from lets encrypt".to_string(),
});
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ fn run() -> Result<(), Box<dyn Error>> {
&& record.level() == Level::Warn
&& msg.contains("becomes unhealthy")
{
webhook::send(webhook::WebhookSendParams {
webhook::send(webhook::SendNotificationParams {
level: webhook::NotificationLevel::Warn,
category: "backend_unhealthy".to_string(),
msg: format!("{}", record.args()),
});
Expand Down
9 changes: 6 additions & 3 deletions src/state/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ impl BackgroundService for AutoRestart {
if should_restart {
let diff_result = get_current_config().diff(conf);
if !diff_result.is_empty() {
webhook::send(webhook::WebhookSendParams {
webhook::send(webhook::SendNotificationParams {
level: webhook::NotificationLevel::Info,
category: "diff_config".to_string(),
msg: diff_result.join("\n"),
});
Expand Down Expand Up @@ -134,7 +135,8 @@ pub fn restart_now() -> io::Result<process::Output> {
));
}
info!("Pingap will restart");
webhook::send(webhook::WebhookSendParams {
webhook::send(webhook::SendNotificationParams {
level: webhook::NotificationLevel::Info,
category: "restart".to_string(),
msg: format!("Restart now, pid:{}", std::process::id()),
});
Expand All @@ -159,7 +161,8 @@ pub fn restart() {
if count == PROCESS_RESTAR_COUNT.load(Ordering::Relaxed) {
if let Err(e) = restart_now() {
error!("Restart fail: {e}");
webhook::send(webhook::WebhookSendParams {
webhook::send(webhook::SendNotificationParams {
level: webhook::NotificationLevel::Error,
category: "restart_fail".to_string(),
msg: e.to_string(),
});
Expand Down
33 changes: 29 additions & 4 deletions src/webhook/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{config::get_app_name, state};
use log::{error, info};
use once_cell::sync::OnceCell;
use serde_json::{Map, Value};
use std::time::Duration;
use std::{fmt::Display, time::Duration};

static WEBHOOK_URL: OnceCell<String> = OnceCell::new();
static WEBHOOK_CATEGORY: OnceCell<String> = OnceCell::new();
Expand All @@ -25,12 +25,30 @@ pub fn set_web_hook(url: &str, category: &str) {
WEBHOOK_CATEGORY.get_or_init(|| category.to_string());
}

pub struct WebhookSendParams {
pub enum NotificationLevel {
Info,
Warn,
Error,
}

impl Display for NotificationLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let msg = match self {
NotificationLevel::Error => "error",
NotificationLevel::Warn => "warn",
_ => "info",
};
write!(f, "{msg}")
}
}

pub struct SendNotificationParams {
pub category: String,
pub level: NotificationLevel,
pub msg: String,
}

pub fn send(params: WebhookSendParams) {
pub fn send(params: SendNotificationParams) {
info!("Webhook {}, {}", params.category, params.msg);
let webhook_type = if let Some(value) = WEBHOOK_CATEGORY.get() {
value.to_string()
Expand All @@ -48,13 +66,19 @@ pub fn send(params: WebhookSendParams) {
std::thread::spawn(move || {
if let Ok(rt) = tokio::runtime::Runtime::new() {
let category = params.category;
let level = params.level;
let send = async move {
let client = reqwest::Client::new();
let mut data = serde_json::Map::new();
let hostname = state::get_hostname().clone();
let name = get_app_name();
let color_type = match level {
NotificationLevel::Error => "error",
NotificationLevel::Warn => "warning",
_ => "comment",
};
let content = format!(
r###"{name}
r###" <font color="{color_type}">{name}({level})</font>
>hostname: {hostname}
>category: {category}
>message: {}"###,
Expand All @@ -77,6 +101,7 @@ pub fn send(params: WebhookSendParams) {
}
_ => {
data.insert("name".to_string(), Value::String(name));
data.insert("level".to_string(), Value::String(level.to_string()));
data.insert("category".to_string(), Value::String(category));
data.insert("message".to_string(), Value::String(params.msg));
data.insert("hostname".to_string(), Value::String(hostname));
Expand Down

0 comments on commit 01b9de4

Please sign in to comment.