Write to stdout all at once to reduce "flashing" on remote monitoring
[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         V4RoutingTableSize(usize),
15         V6RoutingTableSize(usize),
16         RoutingTablePaths(usize),
17 }
18
19 struct Stats {
20         lines: LinkedList<String>,
21         header_count: u64,
22         connection_count: u64,
23         v4_table_size: usize,
24         v6_table_size: usize,
25         paths: usize,
26 }
27
28 pub struct Printer {
29         stats: Arc<Mutex<Stats>>,
30 }
31
32 impl Printer {
33         pub fn new(store: &'static Store) -> Printer {
34                 let stats: Arc<Mutex<Stats>> = Arc::new(Mutex::new(Stats {
35                         lines: LinkedList::new(),
36                         header_count: 0,
37                         connection_count: 0,
38                         v4_table_size: 0,
39                         v6_table_size: 0,
40                         paths: 0,
41                 }));
42                 let thread_arc = Arc::clone(&stats);
43                 std::thread::spawn(move || {
44                         loop {
45                                 std::thread::sleep(std::time::Duration::from_secs(1));
46
47                                 let mut out = Vec::new();
48
49                                 {
50                                         let stats = thread_arc.lock().unwrap();
51                                         if START_SHUTDOWN.load(Ordering::Relaxed) && stats.connection_count == 0 {
52                                                 break;
53                                         }
54
55                                         out.write_all(b"\x1b[2J\x1b[;H\n").unwrap();
56                                         for line in stats.lines.iter() {
57                                                 out.write_all(line.as_bytes()).unwrap();
58                                                 out.write_all(b"\n").unwrap();
59                                         }
60
61                                         out.write_all(b"\nNode counts by status:\n").unwrap();
62                                         for i in 0..AddressState::get_count() {
63                                                 out.write_all(format!("{:22}: {}\n", AddressState::from_num(i).unwrap().to_str(),
64                                                                 store.get_node_count(AddressState::from_num(i).unwrap())
65                                                                 ).as_bytes()).unwrap();
66                                         }
67                                         let generations = store.get_bloom_node_count();
68                                         out.write_all(b"Bloom filter generations contain:").unwrap();
69                                         for generation in &generations {
70                                                 out.write_all(format!(" {}", generation).as_bytes()).unwrap();
71                                         }
72
73                                         out.write_all(format!(
74                                                         "\n\nCurrent connections open/in progress: {}\n", stats.connection_count).as_bytes()).unwrap();
75                                         out.write_all(format!(
76                                                         "Current block count: {}\n", stats.header_count).as_bytes()).unwrap();
77
78                                         out.write_all(format!(
79                                                         "Timeout for full run (in seconds): {} (\"t x\" to change to x seconds)\n", store.get_u64(U64Setting::RunTimeout)
80                                                         ).as_bytes()).unwrap();
81                                         out.write_all(format!(
82                                                         "Minimum protocol version: {} (\"v x\" to change value to x)\n", store.get_u64(U64Setting::MinProtocolVersion)
83                                                         ).as_bytes()).unwrap();
84                                         out.write_all(format!(
85                                                         "Subversion match regex: {} (\"s x\" to change value to x)\n", store.get_regex(RegexSetting::SubverRegex).as_str()
86                                                         ).as_bytes()).unwrap();
87
88                                         out.write_all(b"\nRetry times (in seconds):\n").unwrap();
89                                         for i in 0..AddressState::get_count() {
90                                                 let scan_secs = store.get_u64(U64Setting::RescanInterval(AddressState::from_num(i).unwrap()));
91                                                 out.write_all(format!(
92                                                                 "{:22} ({:2}): {:5} (ie {} hrs, {} min)\n", AddressState::from_num(i).unwrap().to_str(), i,
93                                                                 scan_secs, scan_secs / 60 / 60, (scan_secs / 60) % 60,
94                                                                 ).as_bytes()).unwrap();
95                                         }
96
97                                         out.write_all(format!(
98                                                         "\nBGP Routing Table: {} v4 nets, {} v6 nets, {} max paths\n",
99                                                         stats.v4_table_size, stats.v6_table_size, stats.paths).as_bytes()).unwrap();
100
101                                         out.write_all(b"\nCommands:\n").unwrap();
102                                         out.write_all(b"q: quit\n").unwrap();
103                                         out.write_all(format!(
104                                                         "r x y: Change retry time for status x (int value, see retry times section for name mappings) to y (in seconds)\n"
105                                                         ).as_bytes()).unwrap();
106                                         out.write_all(format!(
107                                                         "w x: Change the amount of time a node is considered WAS_GOOD after it fails to x from {} (in seconds)\n",
108                                                         store.get_u64(U64Setting::WasGoodTimeout)
109                                                         ).as_bytes()).unwrap();
110                                         out.write_all(b"a x: Scan node x\n").unwrap();
111                                         out.write_all(b"b x: BGP Lookup IP x\n").unwrap();
112                                         out.write_all(b"\x1b[s").unwrap(); // Save cursor position and provide a blank line before cursor
113                                         out.write_all(b"\x1b[;H\x1b[2K").unwrap();
114                                         out.write_all(b"Most recent log:\n").unwrap();
115                                         out.write_all(b"\x1b[u").unwrap(); // Restore cursor position and go up one line
116                                 }
117
118                                 let stdout = std::io::stdout();
119                                 let mut stdout_lock = stdout.lock();
120                                 stdout_lock.write_all(&out).expect("stdout broken?");
121                                 stdout_lock.flush().expect("stdout broken?");
122                         }
123                 });
124                 Printer {
125                         stats,
126                 }
127         }
128
129         pub fn add_line(&self, line: String, err: bool) {
130                 let mut stats = self.stats.lock().unwrap();
131                 if err {
132                         stats.lines.push_back("\x1b[31m".to_string() + &line + "\x1b[0m");
133                 } else {
134                         stats.lines.push_back(line);
135                 }
136                 if stats.lines.len() > 150 {
137                         stats.lines.pop_front();
138                 }
139         }
140
141         pub fn set_stat(&self, s: Stat) {
142                 match s {
143                         Stat::HeaderCount(c) => self.stats.lock().unwrap().header_count = c,
144                         Stat::NewConnection => self.stats.lock().unwrap().connection_count += 1,
145                         Stat::ConnectionClosed => self.stats.lock().unwrap().connection_count -= 1,
146                         Stat::V4RoutingTableSize(c) => self.stats.lock().unwrap().v4_table_size = c,
147                         Stat::V6RoutingTableSize(c) => self.stats.lock().unwrap().v6_table_size = c,
148                         Stat::RoutingTablePaths(c) => self.stats.lock().unwrap().paths = c,
149                 }
150         }
151 }