Print time more logically
[dnsseed-rust] / src / printer.rs
1 use std::sync::atomic::Ordering;
2 use std::collections::LinkedList;
3 use std::sync::{Arc, Mutex};
4 use std::io::Write;
5
6 use crate::datastore::{Store, AddressState, U64Setting, RegexSetting};
7
8 use crate::START_SHUTDOWN;
9
10 pub enum Stat {
11         HeaderCount(u64),
12         NewConnection,
13         ConnectionClosed,
14 }
15
16 struct Stats {
17         lines: LinkedList<String>,
18         header_count: u64,
19         connection_count: u64,
20 }
21
22 pub struct Printer {
23         stats: Arc<Mutex<Stats>>,
24 }
25
26 impl Printer {
27         pub fn new(store: &'static Store) -> Printer {
28                 let stats: Arc<Mutex<Stats>> = Arc::new(Mutex::new(Stats {
29                         lines: LinkedList::new(),
30                         header_count: 0,
31                         connection_count: 0,
32                 }));
33                 let thread_arc = Arc::clone(&stats);
34                 std::thread::spawn(move || {
35                         loop {
36                                 std::thread::sleep(std::time::Duration::from_secs(1));
37
38                                 let stdout = std::io::stdout();
39                                 let mut out = stdout.lock();
40
41                                 let stats = thread_arc.lock().unwrap();
42                                 if START_SHUTDOWN.load(Ordering::Relaxed) && stats.connection_count == 0 {
43                                         break;
44                                 }
45
46                                 out.write_all(b"\x1b[2J\x1b[;H\n").expect("stdout broken?");
47                                 for line in stats.lines.iter() {
48                                         out.write_all(line.as_bytes()).expect("stdout broken?");
49                                         out.write_all(b"\n").expect("stdout broken?");
50                                 }
51
52                                 out.write_all(b"\nNode counts by status:\n").expect("stdout broken?");
53                                 for i in 0..AddressState::get_count() {
54                                         out.write_all(format!("{:22}: {}\n", AddressState::from_num(i).unwrap().to_str(),
55                                                         store.get_node_count(AddressState::from_num(i).unwrap())
56                                                         ).as_bytes()).expect("stdout broken?");
57                                 }
58
59                                 out.write_all(format!(
60                                                 "\nCurrent connections open/in progress: {}\n", stats.connection_count).as_bytes()).expect("stdout broken?");
61                                 out.write_all(format!(
62                                                 "Connections opened each second: {} (\"c x\" to change to x seconds)\n", store.get_u64(U64Setting::ConnsPerSec)
63                                                 ).as_bytes()).expect("stdout broken?");
64                                 out.write_all(format!(
65                                                 "Current block count: {}\n", stats.header_count).as_bytes()).expect("stdout broken?");
66
67                                 out.write_all(format!(
68                                                 "Timeout for full run (in seconds): {} (\"t x\" to change to x seconds)\n", store.get_u64(U64Setting::RunTimeout)
69                                                 ).as_bytes()).expect("stdout broken?");
70                                 out.write_all(format!(
71                                                 "Minimum protocol version: {} (\"v x\" to change value to x)\n", store.get_u64(U64Setting::MinProtocolVersion)
72                                                 ).as_bytes()).expect("stdout broken?");
73                                 out.write_all(format!(
74                                                 "Subversion match regex: {} (\"s x\" to change value to x)\n", store.get_regex(RegexSetting::SubverRegex).as_str()
75                                                 ).as_bytes()).expect("stdout broken?");
76
77                                 out.write_all(b"\nRetry times (in seconds):\n").expect("stdout broken?");
78                                 for i in 0..AddressState::get_count() {
79                                         let scan_secs = store.get_u64(U64Setting::RescanInterval(AddressState::from_num(i).unwrap()));
80                                         out.write_all(format!(
81                                                         "{:22} ({:2}): {:5} (ie {} hrs, {} min)\n", AddressState::from_num(i).unwrap().to_str(), i,
82                                                         scan_secs, scan_secs / 60 / 60, (scan_secs / 60) % 60,
83                                                         ).as_bytes()).expect("stdout broken?");
84                                 }
85
86                                 out.write_all(b"\nCommands:\n").expect("stdout broken?");
87                                 out.write_all(b"q: quit\n").expect("stdout broken?");
88                                 out.write_all(format!(
89                                                 "r x y: Change retry time for status x (int value, see retry times section for name mappings) to y (in seconds)\n"
90                                                 ).as_bytes()).expect("stdout broken?");
91                                 out.write_all(format!(
92                                                 "w x: Change the amount of time a node is considered WAS_GOOD after it fails to x from {} (in seconds)\n",
93                                                 store.get_u64(U64Setting::WasGoodTimeout)
94                                                 ).as_bytes()).expect("stdout broken?");
95                                 out.write_all(b"a x: Scan node x\n").expect("stdout broken?");
96                                 out.write_all(b"\x1b[s").expect("stdout broken?"); // Save cursor position and provide a blank line before cursor
97                                 out.write_all(b"\x1b[;H\x1b[2K").expect("stdout broken?");
98                                 out.write_all(b"Most recent log:\n").expect("stdout broken?");
99                                 out.write_all(b"\x1b[u").expect("stdout broken?"); // Restore cursor position and go up one line
100
101                                 out.flush().expect("stdout broken?");
102                         }
103                 });
104                 Printer {
105                         stats,
106                 }
107         }
108
109         pub fn add_line(&self, line: String, err: bool) {
110                 let mut stats = self.stats.lock().unwrap();
111                 if err {
112                         stats.lines.push_back("\x1b[31m".to_string() + &line + "\x1b[0m");
113                 } else {
114                         stats.lines.push_back(line);
115                 }
116                 if stats.lines.len() > 50 {
117                         stats.lines.pop_front();
118                 }
119         }
120
121         pub fn set_stat(&self, s: Stat) {
122                 match s {
123                         Stat::HeaderCount(c) => self.stats.lock().unwrap().header_count = c,
124                         Stat::NewConnection => self.stats.lock().unwrap().connection_count += 1,
125                         Stat::ConnectionClosed => self.stats.lock().unwrap().connection_count -= 1,
126                 }
127         }
128 }