Skip to content

Commit

Permalink
✨ write log to file
Browse files Browse the repository at this point in the history
  • Loading branch information
mokeyish committed Dec 31, 2022
1 parent f90ab9b commit 3e6dc75
Show file tree
Hide file tree
Showing 10 changed files with 286 additions and 80 deletions.
6 changes: 3 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
},
"args": [
"run",
// "-c", "tests/example/smartdns.conf",
"-c", "etc/smartdns/smartdns.conf",
"-d"
// "-c", "etc/smartdns/smartdns.conf",
"-c", "tests/example/smartdns.conf",
// "-d"
],
"cwd": "${workspaceFolder}"
},
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ async-trait = "0.1.43"
time = "0.3"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["std", "fmt", "env-filter"] }
# tracing-appender = "0.2"
tokio = { version = "1.21", features = ["time", "rt", "signal"] }
url = "2.3.1"
trust-dns-proto = { version = "0.22.0", features = ["dns-over-https-rustls"]}
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,10 @@ sudo ./target/release/smartdns run -c ./etc/smartdns/smartdns.conf
| rr-ttl-reply-max | 允许返回给客户端的最大 TTL 值 | :construction: | 远程查询结果 | 大于 0 的数字 | rr-ttl-reply-max 60 |
| local-ttl | 本地HOST,address的TTL值 | :construction: | rr-ttl-min | 大于 0 的数字 | local-ttl 60 |
| max-reply-ip-num | 允许返回给客户的最大IP数量 | :construction: | IP数量 | 大于 0 的数字 | max-reply-ip-num 1 |
| log-level | 设置日志级别 | :construction: | error | fatal、error、warn、notice、info 或 debug | log-level error |
| log-file | 日志文件路径 | :construction: | /var/log/smartdns/smartdns.log | 合法路径字符串 | log-file /var/log/smartdns/smartdns.log |
| log-size | 日志大小 | :construction: | 128K | 数字 + K、M 或 G | log-size 128K |
| log-num | 日志归档个数 | :construction: | 2 | 大于等于 0 的数字 | log-num 2 |
| log-level | 设置日志级别 | :white_check_mark: | error | fatal、error、warn、notice、info 或 debug | log-level error |
| log-file | 日志文件路径 | :white_check_mark: | /var/log/smartdns/smartdns.log | 合法路径字符串 | log-file /var/log/smartdns/smartdns.log |
| log-size | 日志大小 | :white_check_mark: | 128K | 数字 + K、M 或 G | log-size 128K |
| log-num | 日志归档个数 | :white_check_mark: | 2 | 大于等于 0 的数字 | log-num 2 |
| audit-enable | 设置审计启用 | :white_check_mark: | no | [yes\|no] | audit-enable yes |
| audit-file | 审计文件路径 | :white_check_mark: | /var/log/smartdns/smartdns-audit.log | 合法路径字符串,log 后缀可改成 csv | audit-file /var/log/smartdns/smartdns-audit.log |
| audit-size | 审计大小 | :white_check_mark: | 128K | 数字 + K、M 或 G | audit-size 128K |
Expand Down
79 changes: 79 additions & 0 deletions src/dns.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use cfg_if::cfg_if;
use std::fmt::Debug;
use std::path::PathBuf;
use std::{str::FromStr, sync::Arc, time::Duration};

use trust_dns_proto::rr::rdata::SOA;
use trust_dns_resolver::error::ResolveError;

use crate::dns_server::Request as OriginRequest;
use crate::log::info;
use crate::{dns_client::DnsClient, dns_conf::SmartDnsConfig};

pub use trust_dns_proto::{
Expand Down Expand Up @@ -60,6 +63,34 @@ pub type DnsResponse = Lookup;
pub type DnsError = ResolveError;

impl SmartDnsConfig {
pub fn summary(&self) {
info!(r#"whoami 👉 {}"#, self.server_name());

const DEFAULT_GROUP: &'static str = "default";
for (group, servers) in self.servers.iter() {
if group == DEFAULT_GROUP {
continue;
}
for server in servers {
info!(
"upstream server: {} [group: {}]",
server.url.to_string(),
group
);
}
}

if let Some(ss) = self.servers.get(DEFAULT_GROUP) {
for s in ss {
info!(
"upstream server: {} [group: {}]",
s.url.to_string(),
DEFAULT_GROUP
);
}
}
}

pub fn server_name(&self) -> Name {
match self.server_name {
Some(ref server_name) => Some(server_name.clone()),
Expand Down Expand Up @@ -90,6 +121,54 @@ impl SmartDnsConfig {
pub fn audit_num(&self) -> usize {
self.audit_num.unwrap_or(2)
}

pub fn log_enabled(&self) -> bool {
self.log_num() > 0
}

pub fn log_file(&self) -> PathBuf {
match self.log_file.as_ref() {
Some(e) => e.to_owned(),
None => {
cfg_if! {
if #[cfg(target_os="windows")] {
let mut path = std::env::temp_dir();
path.push("smartdns");
path.push("smartdns.log");
path
} else {
PathBuf::from(r"/var/log/smartdns/smartdns.log")
}

}
}
}
}

pub fn log_level(&self) -> tracing::Level {
use tracing::Level;
match self
.log_level
.as_ref()
.map(|s| s.as_str())
.unwrap_or("error")
{
"tarce" => Level::TRACE,
"debug" => Level::DEBUG,
"info" | "notice" => Level::INFO,
"warn" => Level::WARN,
"error" | "fatal" => Level::ERROR,
_ => Level::ERROR,
}
}

pub fn log_num(&self) -> u64 {
self.log_num.unwrap_or(2)
}
pub fn log_size(&self) -> u64 {
use byte_unit::n_kb_bytes;
self.audit_size.unwrap_or(n_kb_bytes(128) as u64)
}
}

pub trait DefaultSOA {
Expand Down
13 changes: 3 additions & 10 deletions src/dns_conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use trust_dns_resolver::Name;

use crate::dns::RecordType;
use crate::dns_url::DnsUrl;
use crate::log::{error, info, warn};
use crate::log::{debug, error, info, warn};

const DEFAULT_SERVER: &'static str = "https://cloudflare-dns.com/dns-query";

Expand Down Expand Up @@ -327,12 +327,6 @@ impl SmartDnsConfig {
.push(DnsServer::from_str(DEFAULT_SERVER).unwrap());
}

if let Some(ss) = cfg.servers.get("default") {
for s in ss {
info!("default server: {}", s.url.to_string());
}
}

cfg
}
}
Expand Down Expand Up @@ -695,8 +689,6 @@ mod parse {
use super::*;
use std::{collections::hash_map::Entry, ffi::OsStr, net::AddrParseError};

use crate::log::{info, warn};

impl SmartDnsConfig {
pub fn load_file<P: AsRef<Path>>(
&mut self,
Expand All @@ -705,6 +697,7 @@ mod parse {
let path = find_path(path, self.conf_file.as_ref());

if path.exists() {
debug!("loading extra configuration from {:?}", path);
let file = File::open(path)?;
let reader = BufReader::new(file);
for line in reader.lines() {
Expand Down Expand Up @@ -846,7 +839,7 @@ mod parse {
}

if server.group.is_some() {
info!(
debug!(
"append server {} to group {}",
server.url.to_string(),
server.group.as_ref().unwrap()
Expand Down
44 changes: 44 additions & 0 deletions src/infra/mapped_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fs;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use chrono::Local;

Expand Down Expand Up @@ -64,6 +65,20 @@ impl MappedFile {
}
}

#[inline]
pub fn touch(&mut self) -> io::Result<()> {
if !self.path().exists() {
let dir = self
.path()
.parent()
.ok_or(io::Error::from(io::ErrorKind::NotFound))?;
fs::create_dir_all(dir)?;
}
let file = self.get_active_file()?;
file.sync_all()?;
Ok(())
}

pub fn mapped_files(&self) -> io::Result<Vec<PathBuf>> {
match (
self.path
Expand Down Expand Up @@ -204,6 +219,35 @@ impl Write for MappedFile {
}
}

pub struct MutexMappedFile(pub Mutex<MappedFile>);

impl MutexMappedFile {
#[inline]
pub fn open<P: AsRef<Path>>(path: P, size: u64, num: Option<usize>) -> Self {
Self(Mutex::new(MappedFile::open(path, size, num)))
}
}

impl io::Write for MutexMappedFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.get_mut().unwrap().write(buf)
}

fn flush(&mut self) -> io::Result<()> {
self.0.get_mut().unwrap().flush()
}
}

impl io::Write for &MutexMappedFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().write(buf)
}

fn flush(&mut self) -> io::Result<()> {
self.0.lock().unwrap().flush()
}
}

#[cfg(test)]
mod tests {

Expand Down
Loading

0 comments on commit 3e6dc75

Please sign in to comment.