Skip to content

Commit

Permalink
support notify test
Browse files Browse the repository at this point in the history
  • Loading branch information
zdz committed Apr 3, 2022
1 parent c9dff1b commit 35dc59a
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 20 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ enabled = false
bot_token = "<tg bot token>"
chat_id = "<chat id>"
# host 可用字段参见 payload.rs 文件 HostStat 结构
online_tpl = "❗<b>Server Status</b>\n❗ {{ host.name }} 主机上线 🟢"
offline_tpl = "❗<b>Server Status</b>\n❗ {{ host.name }} 主机下线 🔴"
online_tpl = "❗<b>Server Status</b>\n❗ {{ host.location }} 地区的 {{ host.name }} 主机恢复上线 🟢"
offline_tpl = "❗<b>Server Status</b>\n❗ {{ host.location }} 地区的 {{ host.name }} 主机已经下线 🔴"
# 模板置空则停用自定义告警,只保留上下线通知
custom_tpl = """
{% if host.memory_used / host.memory_total > 0.5 %}
Expand All @@ -100,15 +100,18 @@ wget --no-check-certificate -qO docker-compose.yml 'https://raw.githubuserconten
wget --no-check-certificate -qO config.toml 'https://raw.githubusercontent.com/zdz/ServerStatus-Rust/master/config.toml'
touch stats.json
docker network create traefik_gw
# 默认使用 watchtower 自动更新,不需要可以去掉
docker-compose up -d

./stat_server -h
# 手动运行
./stat_server
#
./stat_server -c config.toml
#
RUST_BACKTRACE=1 RUST_LOG=trace ./stat_server -c config.toml

# 测试通知是否生效
./stat_server -c config.toml --notify-test
```

## 4.客户端说明
Expand Down
12 changes: 6 additions & 6 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ enabled = false
bot_token = "<tg bot token>"
chat_id = "<chat id>"
# host 可用字段参见 payload.rs 文件 HostStat 结构
online_tpl = "❗<b>Server Status</b>\n❗ {{ host.name }} 主机上线 🟢"
offline_tpl = "❗<b>Server Status</b>\n❗ {{ host.name }} 主机下线 🔴"
online_tpl = "❗<b>Server Status</b>\n❗ {{ host.location }} 地区的 {{ host.name }} 主机恢复上线 🟢"
offline_tpl = "❗<b>Server Status</b>\n❗ {{ host.location }} 地区的 {{ host.name }} 主机已经下线 🔴"
# 模板置空则停用自定义告警,只保留上下线通知
custom_tpl = """
{% if host.memory_used / host.memory_total > 0.5 %}
Expand All @@ -41,8 +41,8 @@ enabled = false
corp_id = "<corp id>"
corp_secret = "<corp secret>"
agent_id = "<agent id>"
online_tpl = "❗Server Status\n❗ {{ host.name }} 主机上线 🟢"
offline_tpl = "❗Server Status\n❗ {{ host.name }} 主机下线 🔴"
online_tpl = "❗Server Status\n❗ {{ host.location }} 地区的 {{ host.name }} 主机恢复上线 🟢"
offline_tpl = "❗Server Status\n❗ {{ host.location }} 地区的 {{ host.name }} 主机已经下线 🔴"
custom_tpl = """
{% if host.memory_used / host.memory_total > 0.8 %}
❗{{ host.name }} 主机内存使用率超80%
Expand All @@ -60,8 +60,8 @@ username = "[email protected]"
password = "***"
to = "[email protected];[email protected]"
subject = "ServerStatus Notification"
online_tpl = "❗<b>Server Status</b><br/>❗ {{ host.name }} 主机上线 🟢"
offline_tpl = "❗<b>Server Status</b><br/>❗ {{ host.name }} 主机下线 🔴"
online_tpl = "❗<b>Server Status</b><br/>❗ {{ host.location }} 地区的 {{ host.name }} 主机恢复上线 🟢"
offline_tpl = "❗<b>Server Status</b><br/>❗ {{ host.location }} 地区的 {{ host.name }} 主机已经下线 🔴"
custom_tpl = """
{% if host.memory_used / host.memory_total > 0.8 %}
<pre>❗{{ host.name }} 主机内存使用率超80%, 当前{{ (100 * host.memory_used / host.memory_total) | round }}% </pre>
Expand Down
21 changes: 19 additions & 2 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::runtime::Handle;

mod config;
mod notifier;
Expand Down Expand Up @@ -139,6 +140,8 @@ async fn shutdown_signal() {
struct Args {
#[clap(short, long, default_value = "config.toml")]
config: String,
#[clap(long = "notify-test", help = "test notify, default:false")]
notify_test: bool,
}

async fn serv_tcp() -> Result<()> {
Expand Down Expand Up @@ -215,7 +218,8 @@ async fn serv_tcp() -> Result<()> {
});
}
}

use std::thread;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<()> {
pretty_env_logger::init();
Expand All @@ -230,10 +234,11 @@ async fn main() -> Result<()> {
process::exit(1);
}

// init notifier
*notifier::NOTIFIER_HANDLE.lock().unwrap() = Some(Handle::current());
let cfg = G_CONFIG.get().unwrap();
let notifies: Arc<Mutex<Vec<Box<dyn notifier::Notifier + Send>>>> =
Arc::new(Mutex::new(Vec::new()));
// init notifier
if cfg.tgbot.enabled {
let o = Box::new(notifier::tgbot::TGBot::new(&cfg.tgbot));
notifies.lock().unwrap().push(o);
Expand All @@ -246,6 +251,18 @@ async fn main() -> Result<()> {
let o = Box::new(notifier::email::Email::new(&cfg.email));
notifies.lock().unwrap().push(o);
}
// init notifier end

// notify test
if args.notify_test {
for notifier in &*notifies.lock().unwrap() {
eprintln!("send test message to {}", notifier.kind());
notifier.notify_test().unwrap();
}
thread::sleep(Duration::from_millis(7000)); // TODO: wait
eprintln!("Please check for notifications");
process::exit(0);
}

// init mgr
let mut mgr = crate::stats::StatsMgr::new();
Expand Down
7 changes: 5 additions & 2 deletions server/src/notifier/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use lettre::{
transport::smtp::authentication::Credentials,
AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
};
use log::{error, info, trace};
use log::{error, info};
use serde::{Deserialize, Serialize};

use crate::notifier::{add_template, get_tag, render_template, Event, HostStat, NOTIFIER_HANDLE};
Expand Down Expand Up @@ -106,8 +106,11 @@ impl crate::notifier::Notifier for Email {
KIND
}

fn notify_test(&self) -> Result<()> {
self.send_msg("❗ServerStatus test msg".to_string())
}

fn notify(&self, e: &Event, stat: &HostStat) -> Result<()> {
trace!("{} notify {:?} => {:?}", self.kind(), e, stat);
match *e {
Event::NodeUp | Event::NodeDown => render_template(KIND, get_tag(e), stat)
.map(|content| self.send_msg(content))
Expand Down
5 changes: 3 additions & 2 deletions server/src/notifier/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use minijinja::{context, Environment};
use minijinja::{context, Environment, Source};
use once_cell::sync::Lazy;
use std::sync::Mutex;
use tokio::runtime::Handle;
Expand All @@ -23,6 +23,7 @@ pub enum Event {
pub trait Notifier {
fn kind(&self) -> &'static str;
fn notify(&self, e: &Event, stat: &HostStat) -> Result<()>;
fn notify_test(&self) -> Result<()>;
}

fn get_tag(e: &Event) -> &'static str {
Expand All @@ -47,7 +48,7 @@ fn add_template<
.lock()
.as_mut()
.map(|env| {
let mut s = env.source().unwrap().to_owned();
let mut s = env.source().unwrap_or(&Source::new()).to_owned();
s.add_template(tpl_name, tpl).unwrap();
env.set_source(s);
})
Expand Down
7 changes: 5 additions & 2 deletions server/src/notifier/tgbot.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![deny(warnings)]
use anyhow::Result;
use log::{error, info, trace};
use log::{error, info};
use reqwest;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand Down Expand Up @@ -91,8 +91,11 @@ impl crate::notifier::Notifier for TGBot {
KIND
}

fn notify_test(&self) -> Result<()> {
self.send_msg("❗ServerStatus test msg".to_string())
}

fn notify(&self, e: &Event, stat: &HostStat) -> Result<()> {
trace!("{} notify {:?} => {:?}", self.kind(), e, stat);
match *e {
Event::NodeUp | Event::NodeDown => render_template(KIND, get_tag(e), stat)
.map(|content| self.send_msg(content))
Expand Down
7 changes: 5 additions & 2 deletions server/src/notifier/wechat.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![deny(warnings)]
use anyhow::Result;
use log::{error, info, trace};
use log::{error, info};
use reqwest;
use serde::{Deserialize, Serialize};
use serde_json;
Expand Down Expand Up @@ -127,8 +127,11 @@ impl crate::notifier::Notifier for WeChat {
KIND
}

fn notify_test(&self) -> Result<()> {
self.send_msg("❗ServerStatus test msg".to_string())
}

fn notify(&self, e: &Event, stat: &HostStat) -> Result<()> {
trace!("{} notify {:?} => {:?}", self.kind(), e, stat);
match *e {
Event::NodeUp | Event::NodeDown => render_template(KIND, get_tag(e), stat)
.map(|content| self.send_msg(content))
Expand Down
2 changes: 1 addition & 1 deletion server/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,13 @@ impl StatsMgr {
});

// notify thread
*NOTIFIER_HANDLE.lock().unwrap() = Some(Handle::current());
thread::spawn(move || loop {
while let Ok(msg) = notifier_rx.recv() {
let (e, stat) = msg;
let notifiers = &*notifies.lock().unwrap();
trace!("recv notify => {:?}, {:?}", e, stat);
for notifier in notifiers {
trace!("{} notify {:?} => {:?}", notifier.kind(), e, stat);
notifier.notify(&e, stat.borrow());
}
}
Expand Down

0 comments on commit 35dc59a

Please sign in to comment.