Skip to content

Commit

Permalink
refactor bandwidth
Browse files Browse the repository at this point in the history
  • Loading branch information
pythops committed Sep 26, 2024
1 parent b7bb3d3 commit 1bf37eb
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 79 deletions.
33 changes: 7 additions & 26 deletions oryx-tui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use std::{
error,
sync::{Arc, Mutex},
thread,
time::Duration,
};
use tui_big_text::{BigText, PixelSize};

Expand Down Expand Up @@ -82,7 +81,7 @@ pub struct App {
pub packet_window_size: usize,
pub update_filters: bool,
pub data_channel_sender: kanal::Sender<[u8; RawPacket::LEN]>,
pub bandwidth: Arc<Mutex<Option<Bandwidth>>>,
pub bandwidth: Bandwidth,
pub show_packet_infos_popup: bool,
pub packet_index: Option<usize>,
pub alert: Alert,
Expand Down Expand Up @@ -112,21 +111,6 @@ impl App {
}
});

let bandwidth = Arc::new(Mutex::new(Bandwidth::new().ok()));

thread::spawn({
let bandwidth = bandwidth.clone();
move || loop {
thread::sleep(Duration::from_secs(1));
{
let mut bandwidth = bandwidth.lock().unwrap();
if bandwidth.is_some() {
let _ = bandwidth.as_mut().unwrap().refresh();
}
}
}
});

Self {
running: true,
help: Help::new(),
Expand All @@ -146,7 +130,7 @@ impl App {
packet_window_size: 0,
update_filters: false,
data_channel_sender: sender,
bandwidth,
bandwidth: Bandwidth::new(),
show_packet_infos_popup: false,
packet_index: None,
alert: Alert::new(packets.clone()),
Expand Down Expand Up @@ -638,7 +622,6 @@ impl App {

pub fn render_stats_mode(&mut self, frame: &mut Frame, block: Rect) {
let stats = self.stats.lock().unwrap();
let mut bandwidth = self.bandwidth.lock().unwrap();

let (bandwidth_block, stats_block) = {
let chunks = Layout::default()
Expand Down Expand Up @@ -675,13 +658,11 @@ impl App {

stats.render(frame, stats_block);

if bandwidth.is_some() {
bandwidth.as_mut().unwrap().render(
frame,
bandwidth_block,
&self.interface.selected_interface.name.clone(),
);
}
self.bandwidth.render(
frame,
bandwidth_block,
&self.interface.selected_interface.name.clone(),
);
}

fn render_packet_infos_popup(&self, frame: &mut Frame) {
Expand Down
118 changes: 65 additions & 53 deletions oryx-tui/src/bandwidth.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::{Read, Seek};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Style, Stylize};
Expand All @@ -11,8 +14,6 @@ use ratatui::{
Frame,
};

use crate::app::AppResult;

#[derive(Clone, Debug)]
pub struct BandwidthBuffer {
incoming_max: usize,
Expand Down Expand Up @@ -46,76 +47,87 @@ impl BandwidthBuffer {

#[derive(Debug)]
pub struct Bandwidth {
fd: File,
current: HashMap<String, (usize, usize)>,
pub map: HashMap<String, BandwidthBuffer>,
map: Arc<Mutex<HashMap<String, BandwidthBuffer>>>,
}

impl Bandwidth {
pub fn new() -> AppResult<Self> {
let mut fd = File::open("/proc/net/dev")?;
let mut current: HashMap<String, (usize, usize)> = HashMap::new();
let mut map: HashMap<String, BandwidthBuffer> = HashMap::new();
pub fn new() -> Self {
let map: Arc<Mutex<HashMap<String, BandwidthBuffer>>> =
Arc::new(Mutex::new(HashMap::new()));

let mut buffer = String::new();
fd.read_to_string(&mut buffer)?;
let mut lines = buffer.lines();
thread::spawn({
let map = map.clone();
move || {
//TODO: handle error
let mut fd = File::open("/proc/net/dev").unwrap();
let mut current: HashMap<String, (usize, usize)> = HashMap::new();

lines.next();
lines.next();
let mut buffer = String::new();
fd.read_to_string(&mut buffer).unwrap();
let mut lines = buffer.lines();

for line in lines {
let splits: Vec<&str> = line.split_whitespace().collect();
lines.next();
lines.next();

let mut interface_name = splits[0].to_string();
interface_name.pop();
for line in lines {
let splits: Vec<&str> = line.split_whitespace().collect();

let bandwidth_buffer = BandwidthBuffer::new(20);
let mut interface_name = splits[0].to_string();
interface_name.pop();

let received: usize = splits[1].parse()?;
let sent: usize = splits[9].parse()?;
let bandwidth_buffer = BandwidthBuffer::new(20);

current.insert(interface_name.clone(), (received, sent));
let received: usize = splits[1].parse().unwrap();
let sent: usize = splits[9].parse().unwrap();

map.insert(interface_name, bandwidth_buffer);
}
current.insert(interface_name.clone(), (received, sent));

Ok(Self { fd, current, map })
}
{
let mut map = map.lock().unwrap();
map.insert(interface_name, bandwidth_buffer);
}
}

pub fn refresh(&mut self) -> AppResult<()> {
self.fd.seek(std::io::SeekFrom::Start(0))?;
let mut buffer = String::new();
self.fd.read_to_string(&mut buffer)?;
loop {
thread::sleep(Duration::from_secs(1));
fd.seek(std::io::SeekFrom::Start(0)).unwrap();
let mut buffer = String::new();
fd.read_to_string(&mut buffer).unwrap();

let mut lines = buffer.lines();
let mut lines = buffer.lines();

lines.next();
lines.next();
lines.next();
lines.next();

for line in lines {
let splits: Vec<&str> = line.split_whitespace().collect();
for line in lines {
let splits: Vec<&str> = line.split_whitespace().collect();

let mut interface_name = splits[0].to_string();
interface_name.pop();
let mut interface_name = splits[0].to_string();
interface_name.pop();

let received: usize = splits[1].parse()?;
let sent: usize = splits[9].parse()?;
let received: usize = splits[1].parse().unwrap();
let sent: usize = splits[9].parse().unwrap();

if let Some(bandwidth_buffer) = self.map.get_mut(&interface_name) {
let current = self.current.get_mut(&interface_name).unwrap();
bandwidth_buffer.push((
received.saturating_sub(current.0) / 1024,
sent.saturating_sub(current.1) / 1024,
));
current.0 = received;
current.1 = sent;
let mut map = map.lock().unwrap();
if let Some(bandwidth_buffer) = map.get_mut(&interface_name) {
let current = current.get_mut(&interface_name).unwrap();
bandwidth_buffer.push((
received.saturating_sub(current.0) / 1024,
sent.saturating_sub(current.1) / 1024,
));
current.0 = received;
current.1 = sent;
}
}
}
}
}
Ok(())
});

Self { map }
}

pub fn render(&self, frame: &mut Frame, bandwidth_block: Rect, network_interface: &str) {
let map = self.map.lock().unwrap();
let (incoming_block, outgoing_block) = {
let chunks = Layout::default()
.direction(Direction::Horizontal)
Expand All @@ -125,7 +137,7 @@ impl Bandwidth {
(chunks[0], chunks[1])
};
let (incoming_max_val, incoming_unit) =
if let Some(bandwidth_buffer) = self.map.get(network_interface) {
if let Some(bandwidth_buffer) = map.get(network_interface) {
match bandwidth_buffer.incoming_max {
n if (1024usize.pow(2)..1024usize.pow(3)).contains(&n) => {
((n / 1024usize.pow(2)) as f64, "GB")
Expand All @@ -138,7 +150,7 @@ impl Bandwidth {
};

let (outgoing_max_val, outgoing_unit) =
if let Some(bandwidth_buffer) = self.map.get(network_interface) {
if let Some(bandwidth_buffer) = map.get(network_interface) {
match bandwidth_buffer.outgoing_max {
n if (1024usize.pow(2)..1024usize.pow(3)).contains(&n) => {
((n / 1024usize.pow(2)) as f64, "GB")
Expand All @@ -151,7 +163,7 @@ impl Bandwidth {
};

let incoming_data = {
if let Some(v) = self.map.get(network_interface) {
if let Some(v) = map.get(network_interface) {
let values = v.get();
let x: Vec<(f64, f64)> = values
.iter()
Expand All @@ -174,7 +186,7 @@ impl Bandwidth {
};

let outgoing_data = {
if let Some(v) = self.map.get(network_interface) {
if let Some(v) = map.get(network_interface) {
let values = v.get();
let x: Vec<(f64, f64)> = values
.iter()
Expand Down

0 comments on commit 1bf37eb

Please sign in to comment.