vdash 0.17.1

Safe Network safenode Dashboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
///! Terminal based interface and dashboard
///!

use chrono::Utc;
use std::collections::HashMap;

#[path = "../widgets/mod.rs"]
pub mod widgets;
use self::widgets::gauge::Gauge2;

use super::app::{DashState, LogMonitor};
use super::timelines::Timeline;
use crate::custom::app_timelines::EARNINGS_UNITS_TEXT;
use crate::custom::timelines::{get_min_buckets_value, get_max_buckets_value, get_duration_text};

use crate::custom::ui::{push_subheading, push_metric, push_metric_with_units, draw_sparkline, monetary_string};

use ratatui::{
	layout::{Constraint, Direction, Layout, Rect},
	widgets::{Block, Borders, List, ListItem},
	style::{Color, Modifier, Style},
	text::Line,
	Frame,
};

pub fn draw_node_dash(
	f: &mut Frame,
	dash_state: &mut DashState,
	monitors: &mut HashMap<String, LogMonitor>,
) {
	let size = f.size();
	let chunks_with_3_bands = Layout::default()
		.direction(Direction::Vertical)
		.constraints([
			Constraint::Length(12), // Stats summary and graphs
			Constraint::Length(18), // Timelines
			Constraint::Min(0),     // Logfile panel
		].as_ref())
		.split(size);

	let chunks_with_2_bands = Layout::default()
		.direction(Direction::Vertical)
		.constraints([
			Constraint::Length(12), // Stats summary and graphs
			Constraint::Min(0),     // Timelines
		].as_ref())
		.split(size);

	for entry in monitors.into_iter() {
		let (logfile, mut monitor) = entry;
		if monitor.has_focus {
			if dash_state.node_logfile_visible {
				// Stats and Graphs / Timelines / Logfile
				draw_node(f, chunks_with_3_bands[0], dash_state, &mut monitor);
				draw_timelines_panel(f, chunks_with_3_bands[1], dash_state, &mut monitor);
				draw_bottom_panel(f, chunks_with_3_bands[2], dash_state, &logfile, &mut monitor);
				return;
			} else {
				// Stats and Graphs / Timelines
				draw_node(f, chunks_with_2_bands[0], dash_state, &mut monitor);
				draw_timelines_panel(f, chunks_with_2_bands[1], dash_state, &mut monitor);
				return;
			}
		}
	}

	// In debug mode there's one node dash and this provide the debug dash
	crate::custom::ui_debug::draw_debug_dash(f, dash_state, monitors);
}

fn draw_node(f: &mut Frame, area: Rect, dash_state: &mut DashState, monitor: &mut LogMonitor) {
	// Columns:
	let constraints = [
		Constraint::Length(40), // Stats summary
		Constraint::Min(10),    // Graphs
	];

	let chunks = Layout::default()
		.direction(Direction::Horizontal)
		.constraints(constraints.as_ref())
		.split(area);

	draw_node_stats(f, dash_state, chunks[0], monitor);
	draw_node_storage(f, chunks[1], dash_state, monitor);
}

fn draw_node_stats(f: &mut Frame, dash_state: &mut DashState, area: Rect, monitor: &mut LogMonitor) {
	// TODO maybe add items to monitor.metrics_status and make items from that as in draw_logfile()
	let mut items = Vec::<ListItem>::new();

	let mut node_title_text = String::from(super::app::SAFENODE_BINARY_NAME);

	if let Some(node_running_version) = &monitor.metrics.running_version {
		node_title_text += format!(" {}", node_running_version).as_str();
	}

	if let Some(node_process_id) = &monitor.metrics.node_process_id {
		node_title_text += format!("  (PID: {})", node_process_id).as_str();
	}

	push_subheading(&mut items, &node_title_text);

	let mut node_uptime_txt = String::from("Start time unknown");
	if let Some(node_start_time) = monitor.metrics.node_started {
		node_uptime_txt = get_duration_text(Utc::now() - node_start_time);
	}
	push_metric(
		&mut items,
		&"Node Uptime".to_string(),
		&node_uptime_txt,
	);

	push_metric(
		&mut items,
		&"Status".to_string(),
		&monitor.metrics.node_status_string,
	);

	let units_text = if dash_state.ui_uses_currency { "" } else { crate::custom::app_timelines::EARNINGS_UNITS_TEXT };

	let wallet_balance = monetary_string(dash_state, monitor.metrics.wallet_balance);
	push_metric_with_units(&mut items,
		&"Wallet".to_string(),
		&wallet_balance,
		&units_text.to_string());

	let storage_payments_txt = monetary_string(dash_state, monitor.metrics.storage_payments.total);
	push_metric_with_units(&mut items,
		&"Earnings".to_string(),
		&storage_payments_txt,
		&units_text.to_string());

	let chunk_fee_txt = if monitor.metrics.storage_cost.most_recent == 0 {
		String::from("unknown")
	} else {
		format!("{} ({}-{}){} ",
		monitor.metrics.storage_cost.most_recent.to_string(),
		monitor.metrics.storage_cost.min.to_string(),
		monitor.metrics.storage_cost.max.to_string(),
		crate::custom::app_timelines::STORAGE_COST_UNITS_TEXT,)
	};

	push_metric(&mut items,
		&"Storage Cost".to_string(),
		&chunk_fee_txt);

	let connections_text = format!("{}", monitor.metrics.peers_connected.most_recent);
	push_metric(&mut items,
	&"Connections".to_string(),
	&connections_text);

	push_metric(
		&mut items,
		&"PUTS".to_string(),
		&monitor.metrics.activity_puts.total.to_string(),
	);

	push_metric(
		&mut items,
		&"GETS".to_string(),
		&monitor.metrics.activity_gets.total.to_string(),
	);

	push_metric(
		&mut items,
		&"ERRORS".to_string(),
		&monitor.metrics.activity_errors.total.to_string(),
	);

	push_subheading(&mut items, &"".to_string());
	let heading = format!("Node {:>2} Status", monitor.index + 1);
	let monitor_widget = List::new(items).block(
		Block::default()
			.borders(Borders::ALL)
			.title(heading.to_string()),
	);
	f.render_stateful_widget(monitor_widget, area, &mut monitor.metrics_status.state);
}

fn draw_timelines_panel(
	f: &mut Frame,
	area: Rect,
	dash_state: &mut DashState,
	monitor: &mut LogMonitor,
) {
	if let Some(active_timescale_name) = dash_state.get_active_timescale_name() {
		let window_widget = Block::default()
			.borders(Borders::ALL)
			.title(format!("Timeline - {}", active_timescale_name).to_string());
		f.render_widget(window_widget, area);

		// For debugging the bucket state
		//
		// if let Some(b_time) = monitor.metrics.sparkline_bucket_time {
		// 	dash_state._debug_window(format!("sparkline_b_time: {}", b_time).as_str());
		// 	dash_state._debug_window(
			// 		format!(
				// 			"sparkline_b_width: {}",
		// 			monitor.metrics.sparkline_bucket_width
		// 		)
		// 		.as_str(),
		// 	);
		// }

		// let mut i = 0;
		// while i < monitor.metrics.puts_sparkline.len() {
		// 	dash_state._debug_window(
		// 		format!(
		// 			"{:>2}: {:>2} puts, {:>2} gets",
		// 			i, monitor.metrics.puts_sparkline[i], monitor.metrics.gets_sparkline[i]
		// 		)
		// 		.as_str(),
		// 	);
		// 	i += 1;
		// }

		const NUM_TIMELINES_VISIBLE: u16 = 3;
		let num_timelines_visible = if dash_state.node_logfile_visible {
			NUM_TIMELINES_VISIBLE
		} else {
			crate::custom::app_timelines::APP_TIMELINES.len() as u16
		};

		let chunks_slim = Layout::default()
			.direction(Direction::Vertical)
			.margin(1)
			.constraints(
				[
					// Three timelines
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
				]
				.as_ref(),
			)
			.split(area);


		let chunks_fat = Layout::default()
			.direction(Direction::Vertical)
			.margin(1)
			.constraints(
				[
					// Tailored to display all timelines in APP_TIMELINES (currently 7)
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
					Constraint::Percentage(100/num_timelines_visible),
				]
				.as_ref(),
			)
			.split(area);

		let mut index = dash_state.top_timeline_index() + 1;
		for i in 1 ..= num_timelines_visible {
			if index > monitor.metrics.app_timelines.get_num_timelines() {
				index = 1;
			}
			let timeline_index = if dash_state.node_logfile_visible {index} else {i as usize};
			if let Some(timeline) = monitor.metrics.app_timelines.get_timeline_by_index(timeline_index - 1) {
				let chunk = if dash_state.node_logfile_visible {&chunks_slim} else {&chunks_fat};
				draw_timeline(f, chunk[i as usize - 1], dash_state, timeline, active_timescale_name);
			}
			index += 1;
		}
	}
}

fn draw_timeline(
	f: &mut Frame,
	area: Rect,
	dash_state: &mut DashState,
	timeline: &Timeline,
	active_timescale_name: &str,
) {
	use crate::custom::timelines::MinMeanMax;

	let mmm_ui_mode = dash_state.mmm_ui_mode();
	let mmm_text = if timeline.is_mmm {
		match mmm_ui_mode {
			MinMeanMax::Min => {" Min "}
			MinMeanMax::Mean => {" Mean"}
			MinMeanMax::Max => {" Max "}
		}
	} else { "" };

	if let Some(bucket_set) = timeline.get_bucket_set(active_timescale_name) {
		if let Some(buckets) = timeline.get_buckets(active_timescale_name, Some(mmm_ui_mode)) {
			// dash_state._debug_window(format!("bucket[0-2 to max]: {},{},{},{} to {}, for {}", buckets[0], buckets[1], buckets[2], buckets[3], buckets[buckets.len()-1], display_name).as_str());
			let duration_text = bucket_set.get_duration_text();

			let mut max_bucket_value = get_max_buckets_value(buckets);
			let mut min_bucket_value = get_min_buckets_value(buckets);
			let label_stats = if timeline.is_cumulative {
				if  dash_state.ui_uses_currency && timeline.units_text == EARNINGS_UNITS_TEXT {
					format!("{} in last {}", monetary_string(dash_state, bucket_set.values_total), duration_text)
				} else {
					format!("{} {} in last {}", bucket_set.values_total, timeline.units_text, duration_text)
				}
			} else {
				dash_state._debug_window(format!("min: {} max: {}", min_bucket_value, max_bucket_value).as_str());
				if max_bucket_value == 0 {max_bucket_value = timeline.last_non_zero_value;}
				if min_bucket_value == u64::MAX || min_bucket_value == 0 {min_bucket_value = max_bucket_value;}
				format!("range {}-{} {} in last {}", min_bucket_value,  max_bucket_value, timeline.units_text, duration_text)
			};
			let label_scale = if max_bucket_value > 0 {
				format!( " (vertical scale: 0-{} {})", max_bucket_value, timeline.units_text)
			} else {
				String::from("")
			};
			let timeline_label = format!("{}{}: {}{}", timeline.name, mmm_text, label_stats, label_scale);
			draw_sparkline(f, area, &buckets, &timeline_label, timeline.colour);
		};
	};
}

fn draw_bottom_panel(
	f: &mut Frame,
	area: Rect,
	dash_state: &mut DashState,
	logfile: &String,
	monitor: &mut LogMonitor,
) {
	if dash_state.debug_window {
		// Vertical split:
		let constraints = [
			Constraint::Percentage(50), // Logfile
			Constraint::Percentage(50), // Debug window
		];

		let chunks = Layout::default()
			.direction(Direction::Horizontal)
			.constraints(constraints.as_ref())
			.split(area);

		draw_logfile(f, chunks[0], &logfile, monitor);
		crate::custom::ui_debug::draw_debug_window(f, chunks[1], dash_state);
	} else {
		draw_logfile(f, area, &logfile, monitor);
	}
}

pub fn draw_logfile(
	f: &mut Frame,
	area: Rect,
	logfile: &String,
	monitor: &mut LogMonitor,
) {
	let highlight_style = match monitor.has_focus {
		true => Style::default()
			.bg(Color::LightGreen)
			.add_modifier(Modifier::BOLD),
		false => Style::default().add_modifier(Modifier::BOLD),
	};

	let items: Vec<ListItem> = monitor
		.content
		.items
		.iter()
		.map(|s| {
			ListItem::new(vec![Line::from(s.clone())])
				.style(Style::default().fg(Color::Black).bg(Color::White))
		})
		.collect();

	let node_log_title = format!("Node Log ({})", logfile);

	let logfile_widget = List::new(items)
		.block(
			Block::default()
				.borders(Borders::ALL)
				.title(node_log_title.clone()),
		)
		.highlight_style(highlight_style);

	f.render_stateful_widget(logfile_widget, area, &mut monitor.content.state);
}

// TODO split into two sub functions, one for gauges, one for text strings
fn draw_node_storage(f: &mut Frame, area: Rect, _dash_state: &mut DashState, monitor: &mut LogMonitor) {
	let heading = format!("Node {:>2} Resources", monitor.index+1);
	let monitor_widget = List::new(Vec::<ListItem>::new())
		.block(
			Block::default()
				.borders(Borders::ALL)
				.title(heading.clone()),
		)
		.highlight_style(
			Style::default()
				.bg(Color::LightGreen)
				.add_modifier(Modifier::BOLD),
		);
	f.render_stateful_widget(monitor_widget, area, &mut monitor.content.state);

	// Two rows top=gauges / bottom=text
	let rows = Layout::default()
		.direction(Direction::Vertical)
		.margin(1)
		.constraints(
			[
				Constraint::Length(2),	// Rows for storage gauges
				Constraint::Min(8),		// Rows for other metrics
			]
			.as_ref(),
		)
		.split(area);

	// Storage: two columns for label+value | bar
	let columns = Layout::default()
		.direction(Direction::Horizontal)
		.margin(0)
		.constraints(
			[
				Constraint::Length(27),
				Constraint::Min(12),
			]
			.as_ref(),
		)
		.split(rows[0]);

	let mut storage_items = Vec::<ListItem>::new();
	push_storage_subheading(&mut storage_items, &"Storage".to_string());
	let mut gauges_column = columns[1];
	gauges_column.height = 1;

	// One gauge gap for heading, and an extra gauge so the last one drawn doesn't expand to the bottom
	let constraints = vec![Constraint::Length(1); 1 + 2];
	let gauges = Layout::default()
		.direction(Direction::Vertical)
		.constraints::<&[Constraint]>(constraints.as_ref())
		.split(columns[1]);

		let max_string = if monitor.metrics.records_max > 0 {
			format!("/{}", monitor.metrics.records_max)
		} else {
			String::from("")
		};
		push_storage_metric(
		&mut storage_items,
		&"Records".to_string(),
		&format!("{}{}", monitor.metrics.records_stored, max_string)
	);

	let denominator = if monitor.metrics.records_max > 0 { monitor.metrics.records_max } else { 1 };
	let gauge = Gauge2::default()
		.block(Block::default())
		.gauge_style(Style::default().fg(Color::Yellow))
		.ratio(ratio(monitor.metrics.records_stored, denominator));
	f.render_widget(gauge, gauges[1]);

	// TODO lobby to re-instate in node logfile
	// push_storage_metric(
	// 	&mut storage_items,
	// 	&"Space Avail".to_string(),
	// 	&max_string
	// );

	// push_storage_metric(
	// 	&mut storage_items,
	// 	&"Space Free".to_string(),
	// 	&device_limit_string
	// );

	let storage_text_widget = List::new(storage_items).block(
		Block::default()
			.borders(Borders::NONE)
	);
	f.render_widget(storage_text_widget, columns[0]);

	let mut text_items = Vec::<ListItem>::new();
	// push_storage_subheading(&mut text_items, &"".to_string());
	push_storage_subheading(&mut text_items, &"Network".to_string());

	const UPDATE_INTERVAL: u64 = 5;	// Match value in s from maidsafe/safe_network/sn_logging/metrics.rs

	let current_rx_text = format!("{:9} B/s",
		monitor.metrics.bytes_written / UPDATE_INTERVAL,
	);

	push_storage_metric(
		&mut text_items,
		&"Current Rx".to_string(),
		&current_rx_text
	);

	let current_tx_text = format!("{:9} B/s",
		monitor.metrics.bytes_read / UPDATE_INTERVAL,
	);

	push_storage_metric(
		&mut text_items,
		&"Current Tx".to_string(),
		&current_tx_text
	);

	let total_rx_text = format!("{:<13}: {:.0} / {:.0} MB",
		"Total Rx",
		monitor.metrics.total_mb_read,
		monitor.metrics.total_mb_received,
	);

	text_items.push(
		ListItem::new(vec![Line::from(total_rx_text.clone())])
			.style(Style::default().fg(Color::Blue)),
	);

	let total_tx_text = format!("{:<13}: {:.0} / {:.0} MB",
		"Total Tx",
		monitor.metrics.total_mb_written,
		monitor.metrics.total_mb_transmitted,
	);

	text_items.push(
		ListItem::new(vec![Line::from(total_tx_text.clone())])
			.style(Style::default().fg(Color::Blue)),
	);

	push_storage_subheading(&mut text_items, &"Load".to_string());

	let node_text = format!("{:<13}: CPU {:8.2} (MAX {:2.2}) MEM {}MB",
		"Node",
		monitor.metrics.cpu_usage_percent,
		monitor.metrics.cpu_usage_percent_max,
		monitor.metrics.memory_used_mb.most_recent,
	);
	text_items.push(
		ListItem::new(vec![Line::from(node_text.clone())])
			.style(Style::default().fg(Color::Blue)),
	);

	let system_text = format!("{:<13}: CPU {:8.2} MEM {:.0} / {:.0} MB {:.1}%",
		"System",
		monitor.metrics.system_cpu,
		monitor.metrics.system_memory_used_mb,
		monitor.metrics.system_memory,
		monitor.metrics.system_memory_usage_percent,
	);
	text_items.push(
		ListItem::new(vec![Line::from(system_text.clone())])
			.style(Style::default().fg(Color::Blue)),
	);

	// Render text
	let text_widget = List::new(text_items).block(
		Block::default()
			.borders(Borders::NONE)
	);
	f.render_widget(text_widget, rows[1]);
}

// Return string representation in TB, MB, KB or bytes depending on magnitude
// fn format_size(bytes: u64, fractional_digits: usize) -> String {
// 	use::byte_unit::Byte;
// 	let bytes = Byte::from_bytes(bytes as u128);
// 	bytes.get_appropriate_unit(false).format(fractional_digits)
// }

// Return ratio from two u64
fn ratio(numerator: u64, denomimator: u64) -> f64 {
	let percent = numerator as f64 / denomimator as f64;
	if  percent.is_nan() || percent < 0.0 {
		0.0
	} else if percent > 1.0 {
		1.0
	} else {
		percent
	}
}

pub fn push_storage_subheading(items: &mut Vec<ListItem>, subheading: &String) {
	items.push(
		ListItem::new(vec![Line::from(subheading.clone())])
			.style(Style::default().fg(Color::Yellow)),
	);
}

pub fn push_storage_metric(items: &mut Vec<ListItem>, metric: &String, value: &String) {
	let s = format!("{:<11}:{:>11}", metric, value);
	items.push(
		ListItem::new(vec![Line::from(s.clone())])
			.style(Style::default().fg(Color::Blue)),
	);
}