diff --git a/src/exec/cli_exec.rs b/src/exec/cli_exec.rs index 41fec25..d0eede6 100644 --- a/src/exec/cli_exec.rs +++ b/src/exec/cli_exec.rs @@ -1,10 +1,13 @@ use std::{ - any::Any, error::Error, thread::sleep, time::{Duration, Instant} + any::Any, + error::Error, + thread::sleep, + time::{Duration, Instant}, }; use crate::{ consts::DURATION, - logger::err, + err, term::tty::{DynTty, Tty, WrapperTty}, util::{anybase::AnyBase, util::rand_string}, }; @@ -90,14 +93,15 @@ impl CliTestApi for CliTester { break; } if begin.elapsed().as_secs() > timeout as u64 { - err(format!( + err!( "Timeout! Expected: {}, Actual: {}", expected, String::from_utf8(buf.clone()).unwrap() - )); + ); return Err(Box::::from("Timeout")); } } + Ok(()) } fn script_run(&mut self, script: &str, timeout: u32) -> Result<(), Box> { @@ -122,11 +126,7 @@ impl CliTestApi for CliTester { } res } - fn assert_script_run( - &mut self, - script: &str, - timeout: u32, - ) -> Result<(), Box> { + fn assert_script_run(&mut self, script: &str, timeout: u32) -> Result<(), Box> { let mut cmd = script.to_owned(); let echo_content_rand = String::from_utf8(rand_string(8)).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 5ae1fa7..ce5dcb2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,6 @@ #![feature(box_into_inner)] pub mod consts; -pub mod logger; pub mod term { pub mod tty; @@ -29,6 +28,8 @@ pub mod device { pub mod util { pub mod anybase; pub mod util; + pub mod singleton; + pub mod logger; } pub mod pythonapi { pub mod shell_like; @@ -40,12 +41,13 @@ pub mod pythonapi { } use pyo3::prelude::*; -use pythonapi::{pyshell::PyShell, shell_like::PyTty}; +use pythonapi::{pyexec::PyExec, pyshell::PyShell, shell_like::PyTty}; #[pymodule] #[pyo3(name = "tester")] fn tester(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; + m.add_class::()?; Ok(()) } diff --git a/src/logger.rs b/src/logger.rs deleted file mode 100644 index 9e022c0..0000000 --- a/src/logger.rs +++ /dev/null @@ -1,15 +0,0 @@ - -#[allow(unused)] -pub fn log(msg: T) { - println!("{}", msg); -} - -#[allow(unused)] -pub fn warn(msg: T) { - eprintln!("{}", msg); -} - -#[allow(unused)] -pub fn err(msg: T) { - eprintln!("{}", msg); -} \ No newline at end of file diff --git a/src/pythonapi/shell_like.rs b/src/pythonapi/shell_like.rs index b50c3e1..82a495b 100644 --- a/src/pythonapi/shell_like.rs +++ b/src/pythonapi/shell_like.rs @@ -4,14 +4,16 @@ use pyo3::{exceptions::PyTypeError, prelude::*}; use serde::Deserialize; use crate::{ - logger::log, term::{ + log, + term::{ asciicast::Asciicast, recorder::{Recorder, SimpleRecorder}, serial::Serial, shell::Shell, ssh::Ssh, tty::{DynTty, WrapperTty}, - }, util::anybase::heap_raw + }, + util::anybase::heap_raw, }; use super::{pyexec::handel_clitester, pyshell::handel_shell}; @@ -64,9 +66,7 @@ pub struct PyTty { impl PyTty { pub fn build(inner: PyTtyWrapper) -> Self { - PyTty { - inner - } + PyTty { inner } } } @@ -93,7 +93,10 @@ struct PyTtyExecConf { sudo: Option, } -pub fn handel_wrap(inner: &mut Option, be_wrapped: Option<&mut PyTty>) -> PyResult<()> { +pub fn handel_wrap( + inner: &mut Option, + be_wrapped: Option<&mut PyTty>, +) -> PyResult<()> { if be_wrapped.is_none() { return Err(PyTypeError::new_err( "be_wrapped must be provided when wrap is true", @@ -165,7 +168,7 @@ impl PyTty { #[new] #[pyo3(signature = (conf, be_wrapped=None))] fn py_new(conf: &str, be_wrapped: Option<&mut PyTty>) -> PyResult { - log(format!("Got conf: {}", conf)); + log!("Got conf: {}", conf); let conf: PyTtyConf = toml::from_str(conf).unwrap(); @@ -400,4 +403,3 @@ impl PyTty { } } } - diff --git a/src/term/serial.rs b/src/term/serial.rs index 59d5d22..eeaf345 100644 --- a/src/term/serial.rs +++ b/src/term/serial.rs @@ -7,7 +7,7 @@ use std::time::Duration; use serialport::{self, SerialPort}; use crate::consts::SHELL_DURATION; -use crate::logger::err; +use crate::err; use crate::term::tty::Tty; use crate::util::anybase::AnyBase; @@ -20,7 +20,7 @@ impl Serial { let inner = serialport::new(port, baud).open(); if let Err(e) = inner { - err(format!("Open serial port failed! Reason: {}", e)); + err!("Open serial port failed! Reason: {}", e); return Err(Box::new(e)); } @@ -55,7 +55,7 @@ impl Tty for Serial { } Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { - err(format!("Read from serial port failed. Reason: {}", e)); + err!("Read from serial port failed. Reason: {}", e); return Err(Box::new(e)); } } @@ -76,7 +76,7 @@ impl Tty for Serial { } Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { - err(format!("Read line from serial port failed. Reason: {}", e)); + err!("Read line from serial port failed. Reason: {}", e); return Err(Box::new(e)); } } @@ -89,7 +89,7 @@ impl Tty for Serial { Ok(_) => break, Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { - err(format!("Write to serial port failed. Reason: {}", e)); + err!("Write to serial port failed. Reason: {}", e); return Err(Box::new(e)); } } diff --git a/src/term/shell.rs b/src/term/shell.rs index 83ee122..87f9eb9 100644 --- a/src/term/shell.rs +++ b/src/term/shell.rs @@ -8,9 +8,8 @@ use std::{ time::Duration, }; -use crate::{ +use crate::{log, err, consts::SHELL_DURATION, - logger::{err, log}, util::anybase::AnyBase, }; @@ -27,7 +26,7 @@ impl Shell { pub fn build(shell: Option<&str>) -> Result> { let shell = shell.unwrap_or("/bin/sh"); - log(format!("Spawn shell process: {}", shell)); + log!("Spawn shell process: {}", shell); let inner = Command::new("stdbuf") .args(&["-oL", "-eL", shell,]) @@ -36,28 +35,28 @@ impl Shell { .stderr(Stdio::piped()) .spawn(); if let Err(e) = inner { - err(format!("Failed to spawn shell process. Reason: {}", e)); + err!("Failed to spawn shell process. Reason: {}", e); return Err(Box::new(e)); } let mut inner = inner.unwrap(); let stdin = inner.stdin.take(); if let None = stdin { - err("Failed to get stdin of shell process."); + err!("Failed to get stdin of shell process."); return Err(Box::::from("")); } let stdin = stdin.unwrap(); let stdout = inner.stdout.take(); if let None = stdout { - err("Failed to get stdout of shell process."); + err!("Failed to get stdout of shell process."); return Err(Box::::from("")); } let stdout = stdout.unwrap(); let stderr = inner.stderr.take(); if let None = stderr { - err("Failed to get stderr of shell process."); + err!("Failed to get stderr of shell process."); return Err(Box::::from("")); } let stderr = stderr.unwrap(); @@ -79,14 +78,14 @@ impl Shell { { let stop = stop_clone.lock().unwrap(); if *stop { - log("Stop shell process"); + log!("Stop shell process"); return; } } let mut buf = [0u8]; let sz = reader.read(&mut buf); if let Err(e) = sz { - err(format!("Read from shell process failed. Reason: {}", e)); + err!("Read from shell process failed. Reason: {}", e); break; } if buf[0] == 0x0 { @@ -104,7 +103,7 @@ impl Shell { fn __stop(&mut self) { let stop = self.stop.lock(); if let Err(e) = stop { - err(format!("Failed to lock stop mutex. Reason: {}", e)); + err!("Failed to lock stop mutex. Reason: {}", e); return; } let mut stop = stop.unwrap(); @@ -112,7 +111,7 @@ impl Shell { return; } *stop = true; - log("Try to stop shell process"); + log!("Try to stop shell process"); // if let Some(handle) = self.handle.take() { // handle.join().unwrap(); // self.inner.wait().unwrap(); @@ -174,14 +173,14 @@ impl Tty for Shell { Ok(_) => break, Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { - err(format!("Write to shell process failed. Reason: {}", e)); + err!("Write to shell process failed. Reason: {}", e); return Err(Box::new(e)); } } } let res = self.stdin.flush(); if let Err(e) = res { - err(format!("Flush to shell process failed. Reason: {}", e)); + err!("Flush to shell process failed. Reason: {}", e); return Err(Box::::from(e)); } return Ok(()); diff --git a/src/term/ssh.rs b/src/term/ssh.rs index 4d2b770..130fb8e 100644 --- a/src/term/ssh.rs +++ b/src/term/ssh.rs @@ -12,9 +12,7 @@ use std::{ use ssh2::Channel; use crate::{ - consts::SHELL_DURATION, - logger::{err, log}, - util::anybase::AnyBase, + consts::SHELL_DURATION, err, log, util::anybase::AnyBase }; use super::tty::Tty; @@ -70,7 +68,7 @@ impl Ssh { let e = channel.shell(); if let Err(e) = e { - err(format!("Failed to open SSH shell. Reason: {}", e)); + err!("Failed to open SSH shell. Reason: {}", e); } let channel = Arc::new(Mutex::new(channel)); @@ -84,7 +82,7 @@ impl Ssh { let handle = spawn(move || loop { let stop = stop_clone.lock().unwrap(); if *stop { - log("Stop SSH shell."); + log!("Stop SSH shell."); break; } @@ -92,7 +90,7 @@ impl Ssh { let mut buf = [0u8]; let sz = channel.read(&mut buf); if let Err(e) = sz { - err(format!("Read from SSH channel failed. Reason: {}", e)); + err!("Read from SSH channel failed. Reason: {}", e); break; } if buf[0] == 0x0 { @@ -114,7 +112,7 @@ impl Ssh { pub fn exit(self) { let stop = self.stop.lock(); if let Err(e) = stop { - err(format!("Failed to lock stop mutex. Reason: {}", e)); + err!("Failed to lock stop mutex. Reason: {}", e); return; } let mut stop = stop.unwrap(); @@ -122,7 +120,7 @@ impl Ssh { return; } *stop = true; - log("Try to stop SSH shell."); + log!("Try to stop SSH shell."); // if let Some(handle) = self.handle.take() { // handle.join().unwrap(); // self.inner.wait().unwrap(); @@ -181,7 +179,7 @@ impl Tty for Ssh { Ok(_) => break, Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { - err(format!("Write to shell process failed. Reason: {}", e)); + err!("Write to shell process failed. Reason: {}", e); return Err(Box::new(e)); } } @@ -189,7 +187,7 @@ impl Tty for Ssh { let mut channel = self.channel.lock().unwrap(); let res = channel.flush(); if let Err(e) = res { - err(format!("Flush to shell process failed. Reason: {}", e)); + err!("Flush to shell process failed. Reason: {}", e); return Err(Box::::from(e)); } return Ok(()); diff --git a/src/util/logger.rs b/src/util/logger.rs new file mode 100644 index 0000000..42621a5 --- /dev/null +++ b/src/util/logger.rs @@ -0,0 +1,48 @@ +use crate::singleton; + +pub enum LogLevel { + Debug = 0, + Info = 10, + Warn = 20, + Error = 30, +} + +singleton!(LogLevelConf, i32, LogLevel::Debug as i32); + +pub fn __log(s: &str) { + if LogLevelConf::get().to_owned() <= LogLevel::Info as i32 { + println!("{}", s); + } +} + +#[macro_export] +macro_rules! log { + ($($arg:tt)*) => (crate::util::logger::__log(&format!($($arg)*))) +} + +pub fn __warn(s: &str) { + if LogLevelConf::get().to_owned() <= LogLevel::Warn as i32 { + eprintln!("{}", s); + } +} + +#[macro_export] +macro_rules! warn { + ($($arg:tt)*) => (crate::util::logger::__warn(&format!($($arg)*))) +} + +pub fn __err(s: &str) { + if LogLevelConf::get().to_owned() <= LogLevel::Error as i32 { + eprintln!("{}", s); + } +} + +#[macro_export] +macro_rules! err { + ($($arg:tt)*) => (crate::util::logger::__err(&format!($($arg)*))) +} + +pub fn set_log_level(level: LogLevel) { + let l = LogLevelConf::get(); + *l = level as i32; +} diff --git a/src/util/singleton.rs b/src/util/singleton.rs new file mode 100644 index 0000000..ed4e168 --- /dev/null +++ b/src/util/singleton.rs @@ -0,0 +1,17 @@ +#[macro_export] +macro_rules! singleton { + ($name:ident, $t:ty, $init:expr) => { + pub struct $name { + } + + impl $name { + + pub fn get() -> &'static mut $t { + static mut INSTANCE: Option<$t> = None; + unsafe { + INSTANCE.get_or_insert_with(|| $init) + } + } + } + }; +} \ No newline at end of file diff --git a/src/util/util.rs b/src/util/util.rs index 6d19550..e0cc6c4 100644 --- a/src/util/util.rs +++ b/src/util/util.rs @@ -24,6 +24,3 @@ pub fn rand_string(len: usize) -> Vec { rnd } -pub trait DynLevel { - -}