Merge branch 'feat/id_newtype' into dev

This commit is contained in:
Jack Wills
2022-10-07 20:16:05 +00:00
11 changed files with 230 additions and 184 deletions
+65 -20
View File
@@ -11,6 +11,45 @@ const ONE_KB: f64 = 1000.0;
const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0;
const ONE_GB: f64 = ONE_MB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0;
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct ContainerId(String);
impl From<String> for ContainerId {
fn from(x: String) -> Self {
Self(x)
}
}
impl From<&String> for ContainerId {
fn from(x: &String) -> Self {
Self(x.clone())
}
}
impl From<&str> for ContainerId {
fn from(x: &str) -> Self {
Self(x.to_owned())
}
}
impl ContainerId {
pub fn get(&self) -> &str {
self.0.as_str()
}
}
impl Ord for ContainerId {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl PartialOrd for ContainerId {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct StatefulList<T> { pub struct StatefulList<T> {
pub state: ListState, pub state: ListState,
@@ -70,7 +109,7 @@ impl<T> StatefulList<T> {
pub fn get_state_title(&self) -> String { pub fn get_state_title(&self) -> String {
if self.items.is_empty() { if self.items.is_empty() {
String::from("") String::new()
} else { } else {
let len = self.items.len(); let len = self.items.len();
let c = self let c = self
@@ -97,10 +136,10 @@ pub enum State {
impl State { impl State {
pub const fn get_color(self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Running => Color::Green, Self::Paused => Color::Yellow,
Self::Removing => Color::LightRed, Self::Removing => Color::LightRed,
Self::Restarting => Color::LightGreen, Self::Restarting => Color::LightGreen,
Self::Paused => Color::Yellow, Self::Running => Color::Green,
_ => Color::Red, _ => Color::Red,
} }
} }
@@ -165,19 +204,19 @@ impl fmt::Display for State {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum DockerControls { pub enum DockerControls {
Pause, Pause,
Unpause,
Restart, Restart,
Stop,
Start, Start,
Stop,
Unpause,
} }
impl DockerControls { impl DockerControls {
pub const fn get_color(self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Pause => Color::Yellow,
Self::Restart => Color::Magenta,
Self::Start => Color::Green, Self::Start => Color::Green,
Self::Stop => Color::Red, Self::Stop => Color::Red,
Self::Restart => Color::Magenta,
Self::Pause => Color::Yellow,
Self::Unpause => Color::Blue, Self::Unpause => Color::Blue,
} }
} }
@@ -198,10 +237,10 @@ impl fmt::Display for DockerControls {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let disp = match self { let disp = match self {
Self::Pause => "pause", Self::Pause => "pause",
Self::Unpause => "unpause",
Self::Restart => "restart", Self::Restart => "restart",
Self::Stop => "stop",
Self::Start => "start", Self::Start => "start",
Self::Stop => "stop",
Self::Unpause => "unpause",
}; };
write!(f, "{}", disp) write!(f, "{}", disp)
} }
@@ -214,7 +253,7 @@ pub trait Stats {
/// Struct for frequently updated CPU stats /// Struct for frequently updated CPU stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Debug, Clone, Copy)] #[derive(Debug, Default, Clone, Copy)]
pub struct CpuStats { pub struct CpuStats {
value: f64, value: f64,
} }
@@ -267,7 +306,7 @@ impl fmt::Display for CpuStats {
/// Struct for frequently updated memory usage stats /// Struct for frequently updated memory usage stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Debug, Clone, Copy, Eq)] #[derive(Debug, Default, Clone, Copy, Eq)]
pub struct ByteStats { pub struct ByteStats {
value: u64, value: u64,
} }
@@ -298,6 +337,8 @@ impl ByteStats {
self.value = value; self.value = value;
} }
} }
#[allow(clippy::cast_precision_loss)]
impl Stats for ByteStats { impl Stats for ByteStats {
fn get_value(&self) -> f64 { fn get_value(&self) -> f64 {
self.value as f64 self.value as f64
@@ -307,7 +348,7 @@ impl Stats for ByteStats {
/// convert from bytes to kB, MB, GB etc /// convert from bytes to kB, MB, GB etc
impl fmt::Display for ByteStats { impl fmt::Display for ByteStats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let as_f64 = self.value as f64; let as_f64 = self.get_value();
let p = match as_f64 { let p = match as_f64 {
x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB),
x if x >= ONE_MB => format!("{y:.2} MB", y = as_f64 / ONE_MB), x if x >= ONE_MB => format!("{y:.2} MB", y = as_f64 / ONE_MB),
@@ -326,7 +367,7 @@ pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State);
pub struct ContainerItem { pub struct ContainerItem {
pub cpu_stats: VecDeque<CpuStats>, pub cpu_stats: VecDeque<CpuStats>,
pub docker_controls: StatefulList<DockerControls>, pub docker_controls: StatefulList<DockerControls>,
pub id: String, pub id: ContainerId,
pub image: String, pub image: String,
pub last_updated: u64, pub last_updated: u64,
pub logs: StatefulList<ListItem<'static>>, pub logs: StatefulList<ListItem<'static>>,
@@ -341,21 +382,23 @@ pub struct ContainerItem {
impl ContainerItem { impl ContainerItem {
/// Create a new container item /// Create a new container item
pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { pub fn new(id: ContainerId, status: String, image: String, state: State, name: String) -> Self {
let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state)); let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state));
docker_controls.start(); docker_controls.start();
let mut logs = StatefulList::new(vec![]);
logs.end();
Self { Self {
cpu_stats: VecDeque::with_capacity(60), cpu_stats: VecDeque::with_capacity(60),
docker_controls, docker_controls,
id, id,
image, image,
last_updated: 0, last_updated: 0,
logs: StatefulList::new(vec![]), logs,
mem_limit: ByteStats::new(0), mem_limit: ByteStats::default(),
mem_stats: VecDeque::with_capacity(60), mem_stats: VecDeque::with_capacity(60),
name, name,
rx: ByteStats::new(0), rx: ByteStats::default(),
tx: ByteStats::new(0), tx: ByteStats::default(),
state, state,
status, status,
} }
@@ -365,7 +408,7 @@ impl ContainerItem {
fn max_cpu_stats(&self) -> CpuStats { fn max_cpu_stats(&self) -> CpuStats {
match self.cpu_stats.iter().max() { match self.cpu_stats.iter().max() {
Some(value) => *value, Some(value) => *value,
None => CpuStats::new(0.0), None => CpuStats::default(),
} }
} }
@@ -373,11 +416,12 @@ impl ContainerItem {
fn max_mem_stats(&self) -> ByteStats { fn max_mem_stats(&self) -> ByteStats {
match self.mem_stats.iter().max() { match self.mem_stats.iter().max() {
Some(value) => *value, Some(value) => *value,
None => ByteStats::new(0), None => ByteStats::default(),
} }
} }
/// Convert cpu stats into a vec for the charts function /// Convert cpu stats into a vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_cpu_dataset(&self) -> Vec<(f64, f64)> { fn get_cpu_dataset(&self) -> Vec<(f64, f64)> {
self.cpu_stats self.cpu_stats
.iter() .iter()
@@ -387,6 +431,7 @@ impl ContainerItem {
} }
/// Convert mem stats into a Vec for the charts function /// Convert mem stats into a Vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_mem_dataset(&self) -> Vec<(f64, f64)> { fn get_mem_dataset(&self) -> Vec<(f64, f64)> {
self.mem_stats self.mem_stats
.iter() .iter()
+57 -60
View File
@@ -66,12 +66,12 @@ impl AppData {
pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) {
self.sorted_by = x; self.sorted_by = x;
self.sort_containers(); self.sort_containers();
self.containers.state.select(
self.containers self.containers
.items .state
.iter() .select(self.containers.items.iter().position(|i| {
.position(|i| Some(i.id.clone()) == self.get_selected_container_id()), self.get_selected_container_id()
); .map_or(false, |id| i.id == id)
}));
} }
/// Generate a default app_state /// Generate a default app_state
pub fn default(args: CliArgs) -> Self { pub fn default(args: CliArgs) -> Self {
@@ -163,20 +163,14 @@ impl AppData {
} }
/// Find the id of the currently selected container. /// Find the id of the currently selected container.
/// If any containers on system, will always return a string. /// If any containers on system, will always return a ContainerId
/// Only returns None when no containers found. /// Only returns None when no containers found.
pub fn get_selected_container_id(&self) -> Option<String> { pub fn get_selected_container_id(&self) -> Option<ContainerId> {
let mut output = None; let mut output = None;
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
let id = self if let Some(x) = self.containers.items.get(index) {
.containers output = Some(x.id.clone());
.items }
.iter()
.skip(index)
.take(1)
.map(|i| i.id.clone())
.collect::<String>();
output = Some(id);
} }
output output
} }
@@ -265,10 +259,10 @@ impl AppData {
/// Get the title for log panel for selected container /// Get the title for log panel for selected container
/// will be "logs x/x" /// will be "logs x/x"
pub fn get_log_title(&self) -> String { pub fn get_log_title(&self) -> String {
self.get_selected_log_index().map_or_else( self.get_selected_log_index()
|| String::from(""), .map_or("".to_owned(), |index| {
|index| self.containers.items[index].logs.get_state_title(), self.containers.items[index].logs.get_state_title()
) })
} }
/// select next selected log line /// select next selected log line
@@ -307,7 +301,9 @@ impl AppData {
} }
} }
pub fn initialised(&mut self, all_ids: &[(bool, String)]) -> bool {
/// Check if the initial parsing has been completed, by making sure that all ids given (which are running) have a non empty cpu_stats vecdec
pub fn initialised(&mut self, all_ids: &[(bool, ContainerId)]) -> bool {
let count_is_running = all_ids.iter().filter(|i| i.0).count(); let count_is_running = all_ids.iter().filter(|i| i.0).count();
let number_with_cpu_status = self let number_with_cpu_status = self
.containers .containers
@@ -329,17 +325,18 @@ impl AppData {
let mut output = Columns::new(); let mut output = Columns::new();
let count = |x: &String| x.chars().count(); let count = |x: &String| x.chars().count();
// Should probably find a refactor here somewhere
for container in &self.containers.items { for container in &self.containers.items {
let cpu_count = count( let cpu_count = count(
&container &container
.cpu_stats .cpu_stats
.back() .back()
.unwrap_or(&CpuStats::new(0.0)) .unwrap_or(&CpuStats::default())
.to_string(), .to_string(),
); );
let mem_count = count(&format!( let mem_count = count(&format!(
"{} / {}", "{} / {}",
container.mem_stats.back().unwrap_or(&ByteStats::new(0)), container.mem_stats.back().unwrap_or(&ByteStats::default()),
container.mem_limit container.mem_limit
)); ));
@@ -379,7 +376,7 @@ impl AppData {
} }
/// Get all containers ids /// Get all containers ids
pub fn get_all_ids(&self) -> Vec<String> { pub fn get_all_ids(&self) -> Vec<ContainerId> {
self.containers self.containers
.items .items
.iter() .iter()
@@ -387,15 +384,15 @@ impl AppData {
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
/// find container given id /// return a mutable container by given id
fn get_container_by_id(&mut self, id: &str) -> Option<&mut ContainerItem> { fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
self.containers.items.iter_mut().find(|i| i.id == id) self.containers.items.iter_mut().find(|i| &i.id == id)
} }
/// Update container mem, cpu, & network stats, in single function so only need to call .lock() once /// Update container mem, cpu, & network stats, in single function so only need to call .lock() once
pub fn update_stats( pub fn update_stats(
&mut self, &mut self,
id: &str, id: &ContainerId,
cpu_stat: Option<f64>, cpu_stat: Option<f64>,
mem_stat: Option<u64>, mem_stat: Option<u64>,
mem_limit: u64, mem_limit: u64,
@@ -424,18 +421,18 @@ impl AppData {
} }
/// Update, or insert, containers /// Update, or insert, containers
pub fn update_containers(&mut self, containers: &mut [ContainerSummary]) { pub fn update_containers(&mut self, all_containers: &mut [ContainerSummary]) {
let all_ids = self.get_all_ids(); let all_ids = self.get_all_ids();
if !containers.is_empty() && self.containers.state.selected().is_none() { if !all_containers.is_empty() && self.containers.state.selected().is_none() {
self.containers.start(); self.containers.start();
} }
for (index, id) in all_ids.iter().enumerate() { for (index, id) in all_ids.iter().enumerate() {
if !containers if !all_containers
.iter() .iter()
.filter_map(|i| i.id.as_ref()) .filter_map(|i| i.id.as_ref())
.any(|x| x == id) .any(|x| x == id.get())
{ {
// If removed container is currently selected, then change selected to previous // If removed container is currently selected, then change selected to previous
// This will default to 0 in any edge cases // This will default to 0 in any edge cases
@@ -448,63 +445,61 @@ impl AppData {
} }
} }
} }
// Trim a &String and return String
let trim_owned = |x: &String| x.trim().to_owned();
for i in containers.iter_mut() { for i in all_containers {
if let Some(id) = i.id.as_ref() { if let Some(id) = i.id.as_ref() {
// maybe if no name then continue? let name = i.names.as_mut().map_or("".to_owned(), |names| {
let name = i.names.as_mut().map_or("".to_owned(), |n| { names.first_mut().map_or("".to_owned(), |f| {
n.get_mut(0).map_or("".to_owned(), |f| {
if f.starts_with('/') { if f.starts_with('/') {
f.remove(0); f.remove(0);
} }
f.clone() (*f).to_string()
}) })
}); });
let state = State::from( let state = State::from(
i.state i.state
.as_ref() .as_ref()
.map_or("dead".to_owned(), |f| f.trim().to_owned()), .map_or("dead".to_owned(), trim_owned),
); );
let status = i let status = i
.status .status
.as_ref() .as_ref()
.map_or("".to_owned(), |f| f.trim().to_owned()); .map_or("".to_owned(), trim_owned);
let image = i let image = i
.image .image
.as_ref() .as_ref()
.map_or("".to_owned(), std::clone::Clone::clone); .map_or("".to_owned(), std::clone::Clone::clone);
if let Some(current_container) = self.get_container_by_id(id) { let id = ContainerId::from(id);
if current_container.name != name { // If container info already in containers Vec, then just update details
current_container.name = name; if let Some(item) = self.get_container_by_id(&id) {
if item.name != name {
item.name = name;
}; };
if current_container.status != status { if item.status != status {
current_container.status = status; item.status = status;
}; };
if current_container.state != state { if item.state != state {
current_container.docker_controls.items = DockerControls::gen_vec(state); item.docker_controls.items = DockerControls::gen_vec(state);
// Update the list state, needs to be None if the gen_vec returns an empty vec // Update the list state, needs to be None if the gen_vec returns an empty vec
match state { match state {
State::Removing | State::Restarting | State::Unknown => { State::Removing | State::Restarting | State::Unknown => {
current_container.docker_controls.state.select(None); item.docker_controls.state.select(None);
} }
_ => current_container.docker_controls.start(), _ => item.docker_controls.start(),
}; };
current_container.state = state; item.state = state;
}; };
if current_container.image != image { if item.image != image {
// limit image name to 64 chars? item.image = image;
// current_container.image = image.chars().into_iter().take(64).collect();
current_container.image = image;
}; };
// else container not known, so make new ContainerItem and push into containers Vec
} else { } else {
// limit image name to 64 chars? let container = ContainerItem::new(id, status, image, state, name);
// let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name);
let mut container = ContainerItem::new(id.clone(), status, image, state, name);
container.logs.end();
self.containers.items.push(container); self.containers.items.push(container);
} }
} }
@@ -512,7 +507,7 @@ impl AppData {
} }
/// update logs of a given container, based on id /// update logs of a given container, based on id
pub fn update_log_by_id(&mut self, output: &[String], id: &str) { pub fn update_log_by_id(&mut self, output: &[String], id: &ContainerId) {
let tz = Self::get_systemtime(); let tz = Self::get_systemtime();
let color = self.args.color; let color = self.args.color;
let raw = self.args.raw; let raw = self.args.raw;
@@ -521,7 +516,7 @@ impl AppData {
container.last_updated = tz; container.last_updated = tz;
let current_len = container.logs.items.len(); let current_len = container.logs.items.len();
for i in output.iter() { for i in output {
let lines = if color { let lines = if color {
log_sanitizer::colorize_logs(i) log_sanitizer::colorize_logs(i)
} else if raw { } else if raw {
@@ -532,6 +527,8 @@ impl AppData {
container.logs.items.push(ListItem::new(lines)); container.logs.items.push(ListItem::new(lines));
} }
// Set the logs selected row for each container
// Either when no long currently selected, or currently selected (before updated) is already at end
if container.logs.state.selected().is_none() if container.logs.state.selected().is_none()
|| container.logs.state.selected().map_or(1, |f| f + 1) == current_len || container.logs.state.selected().map_or(1, |f| f + 1) == current_len
{ {
+3 -3
View File
@@ -5,10 +5,10 @@ use std::fmt;
#[allow(unused)] #[allow(unused)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum AppError { pub enum AppError {
DockerCommand(DockerControls),
DockerConnect, DockerConnect,
DockerInterval, DockerInterval,
InputPoll, InputPoll,
DockerCommand(DockerControls),
MouseCapture(bool), MouseCapture(bool),
Terminal, Terminal,
} }
@@ -17,15 +17,15 @@ pub enum AppError {
impl fmt::Display for AppError { impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Self::DockerCommand(s) => write!(f, "Unable to {} container", s),
Self::DockerConnect => write!(f, "Unable to access docker daemon"), Self::DockerConnect => write!(f, "Unable to access docker daemon"),
Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"), Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"),
Self::InputPoll => write!(f, "Unable to poll user input"), Self::InputPoll => write!(f, "Unable to poll user input"),
Self::Terminal => write!(f, "Unable to draw to terminal"),
Self::DockerCommand(s) => write!(f, "Unable to {} container", s),
Self::MouseCapture(x) => { Self::MouseCapture(x) => {
let reason = if *x { "en" } else { "dis" }; let reason = if *x { "en" } else { "dis" };
write!(f, "Unbale to {}able mouse capture", reason) write!(f, "Unbale to {}able mouse capture", reason)
} }
Self::Terminal => write!(f, "Unable to draw to terminal"),
} }
} }
} }
+7 -5
View File
@@ -1,10 +1,12 @@
use crate::app_data::ContainerId;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum DockerMessage { pub enum DockerMessage {
Update, Update,
Start(String), Start(ContainerId),
Restart(String), Restart(ContainerId),
Pause(String), Pause(ContainerId),
Unpause(String), Unpause(ContainerId),
Stop(String), Stop(ContainerId),
Quit, Quit,
} }
+31 -31
View File
@@ -16,7 +16,7 @@ use tokio::{sync::mpsc::Receiver, task::JoinHandle};
use uuid::Uuid; use uuid::Uuid;
use crate::{ use crate::{
app_data::{AppData, DockerControls}, app_data::{AppData, ContainerId, DockerControls},
app_error::AppError, app_error::AppError,
parse_args::CliArgs, parse_args::CliArgs,
ui::GuiState, ui::GuiState,
@@ -26,8 +26,8 @@ pub use message::DockerMessage;
#[derive(Debug, Clone, Eq, Hash, PartialEq)] #[derive(Debug, Clone, Eq, Hash, PartialEq)]
enum SpawnId { enum SpawnId {
Stats((String, Binate)), Stats((ContainerId, Binate)),
Log(String), Log(ContainerId),
} }
/// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time
@@ -63,6 +63,7 @@ pub struct DockerData {
impl DockerData { impl DockerData {
/// Use docker stats to caluclate current cpu usage /// Use docker stats to caluclate current cpu usage
#[allow(clippy::cast_precision_loss)]
fn calculate_usage(stats: &Stats) -> f64 { fn calculate_usage(stats: &Stats) -> f64 {
let mut cpu_percentage = 0.0; let mut cpu_percentage = 0.0;
let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage;
@@ -78,9 +79,8 @@ impl DockerData {
.cpu_stats .cpu_stats
.cpu_usage .cpu_usage
.percpu_usage .percpu_usage
.clone() .as_ref()
.unwrap_or_default() .map_or(0, std::vec::Vec::len) as u64
.len() as u64
}) as f64; }) as f64;
if system_delta > 0.0 && cpu_delta > 0.0 { if system_delta > 0.0 && cpu_delta > 0.0 {
cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0; cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0;
@@ -94,7 +94,7 @@ impl DockerData {
/// remove if from spawns hashmap when complete /// remove if from spawns hashmap when complete
async fn update_container_stat( async fn update_container_stat(
docker: Arc<Docker>, docker: Arc<Docker>,
id: String, id: ContainerId,
app_data: Arc<Mutex<AppData>>, app_data: Arc<Mutex<AppData>>,
is_running: bool, is_running: bool,
spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>, spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>,
@@ -102,7 +102,7 @@ impl DockerData {
) { ) {
let mut stream = docker let mut stream = docker
.stats( .stats(
&id, id.get(),
Some(StatsOptions { Some(StatsOptions {
stream: false, stream: false,
one_shot: !is_running, one_shot: !is_running,
@@ -122,10 +122,11 @@ impl DockerData {
let cpu_stats = Self::calculate_usage(&stats); let cpu_stats = Self::calculate_usage(&stats);
let (rx, tx) = if let Some(key) = op_key { let (rx, tx) = if let Some(key) = op_key {
match stats.networks.unwrap_or_default().get(&key) { stats
Some(data) => (data.rx_bytes, data.tx_bytes), .networks
None => (0, 0), .unwrap_or_default()
} .get(&key)
.map_or((0, 0), |f| (f.rx_bytes, f.tx_bytes))
} else { } else {
(0, 0) (0, 0)
}; };
@@ -149,13 +150,12 @@ impl DockerData {
} }
/// Update all stats, spawn each container into own tokio::spawn thread /// Update all stats, spawn each container into own tokio::spawn thread
fn update_all_container_stats(&mut self, all_ids: &[(bool, String)]) { fn update_all_container_stats(&mut self, all_ids: &[(bool, ContainerId)]) {
for (is_running, id) in all_ids.iter() { for (is_running, id) in all_ids {
let docker = Arc::clone(&self.docker); let docker = Arc::clone(&self.docker);
let app_data = Arc::clone(&self.app_data); let app_data = Arc::clone(&self.app_data);
let spawns = Arc::clone(&self.spawns); let spawns = Arc::clone(&self.spawns);
let key = SpawnId::Stats((id.clone(), self.binate)); let key = SpawnId::Stats((id.clone(), self.binate));
let spawn_key = key.clone(); let spawn_key = key.clone();
self.spawns.lock().entry(key).or_insert_with(|| { self.spawns.lock().entry(key).or_insert_with(|| {
tokio::spawn(Self::update_container_stat( tokio::spawn(Self::update_container_stat(
@@ -174,7 +174,7 @@ impl DockerData {
/// Get all current containers, handle into ContainerItem in the app_data struct rather than here /// Get all current containers, handle into ContainerItem in the app_data struct rather than here
/// Just make sure that items sent are guaranteed to have an id /// Just make sure that items sent are guaranteed to have an id
/// Will ignore any container that contains `oxker` as an entry point /// Will ignore any container that contains `oxker` as an entry point
pub async fn update_all_containers(&mut self) -> Vec<(bool, String)> { pub async fn update_all_containers(&mut self) -> Vec<(bool, ContainerId)> {
let containers = self let containers = self
.docker .docker
.list_containers(Some(ListContainersOptions::<String> { .list_containers(Some(ListContainersOptions::<String> {
@@ -185,13 +185,13 @@ impl DockerData {
.unwrap_or_default(); .unwrap_or_default();
let mut output = containers let mut output = containers
.iter() .into_iter()
.filter_map(|f| match f.id { .filter_map(|f| match f.id {
Some(_) => { Some(_) => {
if f.command.as_ref().map_or(false, |c| c.contains("oxker")) { if f.command.as_ref().map_or(false, |c| c.contains("oxker")) {
None None
} else { } else {
Some(f.clone()) Some(f)
} }
} }
None => None, None => None,
@@ -205,13 +205,13 @@ impl DockerData {
// Just get the containers that are currently running, or being restarted, no point updating info on paused or dead containers // Just get the containers that are currently running, or being restarted, no point updating info on paused or dead containers
output output
.iter() .into_iter()
.filter_map(|i| { .filter_map(|i| {
i.id.as_ref().map(|id| { i.id.map(|id| {
( (
i.state == Some("running".to_owned()) i.state == Some("running".to_owned())
|| i.state == Some("restarting".to_owned()), || i.state == Some("restarting".to_owned()),
id.clone(), ContainerId::from(id),
) )
}) })
}) })
@@ -223,7 +223,7 @@ impl DockerData {
/// remove if from spawns hashmap when complete /// remove if from spawns hashmap when complete
async fn update_log( async fn update_log(
docker: Arc<Docker>, docker: Arc<Docker>,
id: String, id: ContainerId,
timestamps: bool, timestamps: bool,
since: u64, since: u64,
app_data: Arc<Mutex<AppData>>, app_data: Arc<Mutex<AppData>>,
@@ -232,11 +232,11 @@ impl DockerData {
let options = Some(LogsOptions::<String> { let options = Some(LogsOptions::<String> {
stdout: true, stdout: true,
timestamps, timestamps,
since: since as i64, since: i64::try_from(since).unwrap_or_default(),
..Default::default() ..Default::default()
}); });
let mut logs = docker.logs(&id, options); let mut logs = docker.logs(id.get(), options);
let mut output = vec![]; let mut output = vec![];
while let Some(value) = logs.next().await { while let Some(value) = logs.next().await {
@@ -252,8 +252,8 @@ impl DockerData {
} }
/// Update all logs, spawn each container into own tokio::spawn thread /// Update all logs, spawn each container into own tokio::spawn thread
fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { fn init_all_logs(&mut self, all_ids: &[(bool, ContainerId)]) {
for (_, id) in all_ids.iter() { for (_, id) in all_ids {
let docker = Arc::clone(&self.docker); let docker = Arc::clone(&self.docker);
let app_data = Arc::clone(&self.app_data); let app_data = Arc::clone(&self.app_data);
let spawns = Arc::clone(&self.spawns); let spawns = Arc::clone(&self.spawns);
@@ -349,7 +349,7 @@ impl DockerData {
match message { match message {
DockerMessage::Pause(id) => { DockerMessage::Pause(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.pause_container(&id).await.is_err() { if docker.pause_container(id.get()).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Pause)); .set_error(AppError::DockerCommand(DockerControls::Pause));
@@ -358,7 +358,7 @@ impl DockerData {
} }
DockerMessage::Restart(id) => { DockerMessage::Restart(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.restart_container(&id, None).await.is_err() { if docker.restart_container(id.get(), None).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Restart)); .set_error(AppError::DockerCommand(DockerControls::Restart));
@@ -368,7 +368,7 @@ impl DockerData {
DockerMessage::Start(id) => { DockerMessage::Start(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker if docker
.start_container(&id, None::<StartContainerOptions<String>>) .start_container(id.get(), None::<StartContainerOptions<String>>)
.await .await
.is_err() .is_err()
{ {
@@ -380,7 +380,7 @@ impl DockerData {
} }
DockerMessage::Stop(id) => { DockerMessage::Stop(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.stop_container(&id, None).await.is_err() { if docker.stop_container(id.get(), None).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Stop)); .set_error(AppError::DockerCommand(DockerControls::Stop));
@@ -389,7 +389,7 @@ impl DockerData {
} }
DockerMessage::Unpause(id) => { DockerMessage::Unpause(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.unpause_container(&id).await.is_err() { if docker.unpause_container(id.get()).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Unpause)); .set_error(AppError::DockerCommand(DockerControls::Unpause));
+1
View File
@@ -137,6 +137,7 @@ impl InputHandler {
} }
/// Handle any keyboard button events /// Handle any keyboard button events
#[allow(clippy::too_many_lines)]
async fn button_press(&mut self, key_code: KeyCode) { async fn button_press(&mut self, key_code: KeyCode) {
let show_error = self.app_data.lock().show_error; let show_error = self.app_data.lock().show_error;
let show_info = self.gui_state.lock().show_help; let show_info = self.gui_state.lock().show_help;
+3 -3
View File
@@ -4,7 +4,7 @@ use clap::Parser;
use tracing::error; use tracing::error;
#[derive(Parser, Debug, Clone, Copy)] #[derive(Parser, Debug, Clone, Copy)]
// #[command(help_template = FULL_TEMPLATE)] #[allow(clippy::struct_excessive_bools)]
#[command(version, about)] #[command(version, about)]
pub struct CliArgs { pub struct CliArgs {
/// Docker update interval in ms, minimum effectively 1000 /// Docker update interval in ms, minimum effectively 1000
@@ -15,11 +15,11 @@ pub struct CliArgs {
#[clap(short = 't')] #[clap(short = 't')]
pub timestamp: bool, pub timestamp: bool,
/// Attempt to colorize the logs /// Attempt to colorize the logs, conflicts with "-r"
#[clap(short = 'c', conflicts_with = "raw")] #[clap(short = 'c', conflicts_with = "raw")]
pub color: bool, pub color: bool,
/// Show raw logs, default is to remove ansi formatting /// Show raw logs, default is to remove ansi formatting, conflicts with "-c"
#[clap(short = 'r', conflicts_with = "color")] #[clap(short = 'r', conflicts_with = "color")]
pub raw: bool, pub raw: bool,
+5 -5
View File
@@ -10,11 +10,11 @@ pub mod log_sanitizer {
pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> { pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from( vec![Spans::from(
categorise_text(input) categorise_text(input)
.into_iter() .iter()
.map(|i| { .map(|i| {
let fg_color = color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)); let style = Style::default()
let bg_color = color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)); .bg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)))
let style = Style::default().bg(bg_color).fg(fg_color); .fg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)));
if i.blink.is_some() { if i.blink.is_some() {
style.add_modifier(Modifier::SLOW_BLINK); style.add_modifier(Modifier::SLOW_BLINK);
} }
@@ -41,7 +41,7 @@ pub mod log_sanitizer {
/// Remove all ansi formatting from a given string and create tui-rs spans /// Remove all ansi formatting from a given string and create tui-rs spans
pub fn remove_ansi<'a>(input: &str) -> Vec<Spans<'a>> { pub fn remove_ansi<'a>(input: &str) -> Vec<Spans<'a>> {
let mut output = String::from(""); let mut output = String::new();
for i in categorise_text(input) { for i in categorise_text(input) {
output.push_str(i.text); output.push_str(i.text);
} }
+45 -50
View File
@@ -51,9 +51,6 @@ fn generate_block<'a>(
panel: SelectablePanel, panel: SelectablePanel,
) -> Block<'a> { ) -> Block<'a> {
gui_state.lock().update_map(Region::Panel(panel), area); gui_state.lock().update_map(Region::Panel(panel), area);
let mut block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded);
let current_selected_panel = gui_state.lock().selected_panel; let current_selected_panel = gui_state.lock().selected_panel;
let title = match panel { let title = match panel {
SelectablePanel::Containers => { SelectablePanel::Containers => {
@@ -66,9 +63,12 @@ fn generate_block<'a>(
SelectablePanel::Logs => { SelectablePanel::Logs => {
format!(" {} {} ", panel.title(), app_data.lock().get_log_title()) format!(" {} {} ", panel.title(), app_data.lock().get_log_title())
} }
SelectablePanel::Commands => String::from(""), SelectablePanel::Commands => String::new(),
}; };
block = block.title(title); let mut block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.title(title);
if current_selected_panel == panel { if current_selected_panel == panel {
block = block.border_style(Style::default().fg(Color::LightCyan)); block = block.border_style(Style::default().fg(Color::LightCyan));
} }
@@ -109,10 +109,7 @@ pub fn commands<B: Backend>(
&mut app_data.lock().containers.items[i].docker_controls.state, &mut app_data.lock().containers.items[i].docker_controls.state,
); );
} else { } else {
let debug_text = String::from(""); let paragraph = Paragraph::new("").block(block).alignment(Alignment::Center);
let paragraph = Paragraph::new(debug_text)
.block(block)
.alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
} }
@@ -138,7 +135,7 @@ pub fn containers<B: Backend>(
let mems = format!( let mems = format!(
"{:>1} / {:>1}", "{:>1} / {:>1}",
i.mem_stats.back().unwrap_or(&ByteStats::new(0)), i.mem_stats.back().unwrap_or(&ByteStats::default()),
i.mem_limit i.mem_limit
); );
@@ -155,7 +152,7 @@ pub fn containers<B: Backend>(
format!( format!(
"{}{:>width$}", "{}{:>width$}",
MARGIN, MARGIN,
i.cpu_stats.back().unwrap_or(&CpuStats::new(0.0)), i.cpu_stats.back().unwrap_or(&CpuStats::default()),
width = &widths.cpu.1 width = &widths.cpu.1
), ),
state_style, state_style,
@@ -168,7 +165,7 @@ pub fn containers<B: Backend>(
format!( format!(
"{}{:>width$}", "{}{:>width$}",
MARGIN, MARGIN,
i.id.chars().take(8).collect::<String>(), i.id.get().chars().take(8).collect::<String>(),
width = &widths.id.1 width = &widths.id.1
), ),
blue, blue,
@@ -194,8 +191,7 @@ pub fn containers<B: Backend>(
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if items.is_empty() { if items.is_empty() {
let debug_text = String::from("no containers running"); let paragraph = Paragraph::new("no containers running")
let paragraph = Paragraph::new(debug_text)
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
@@ -222,8 +218,7 @@ pub fn logs<B: Backend>(
let init = app_data.lock().init; let init = app_data.lock().init;
if !init { if !init {
let parsing_logs = format!("parsing logs {}", loading_icon); let paragraph = Paragraph::new(format!("parsing logs {}", loading_icon))
let paragraph = Paragraph::new(parsing_logs)
.style(Style::default()) .style(Style::default())
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
@@ -247,8 +242,7 @@ pub fn logs<B: Backend>(
&mut app_data.lock().containers.items[index].logs.state, &mut app_data.lock().containers.items[index].logs.state,
); );
} else { } else {
let debug_text = String::from("no logs found"); let paragraph = Paragraph::new("no logs found")
let paragraph = Paragraph::new(debug_text)
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
@@ -343,6 +337,7 @@ fn make_chart<'a, T: Stats + Display>(
} }
/// Draw heading bar at top of program, always visible /// Draw heading bar at top of program, always visible
#[allow(clippy::too_many_lines)]
pub fn heading_bar<B: Backend>( pub fn heading_bar<B: Backend>(
area: Rect, area: Rect,
columns: &Columns, columns: &Columns,
@@ -407,7 +402,7 @@ pub fn heading_bar<B: Backend>(
width = width - block.2 width = width - block.2
), ),
}; };
let count = text.chars().count() as u16; let count = u16::try_from(text.chars().count()).unwrap_or_default();
let status = Paragraph::new(text) let status = Paragraph::new(text)
.block(block.0) .block(block.0)
.alignment(Alignment::Left); .alignment(Alignment::Left);
@@ -437,12 +432,15 @@ pub fn heading_bar<B: Backend>(
let suffix = if info_visible { "exit" } else { "show" }; let suffix = if info_visible { "exit" } else { "show" };
let info_text = format!("( h ) {} help {}", suffix, MARGIN); let info_text = format!("( h ) {} help {}", suffix, MARGIN);
let info_width = info_text.chars().count() as u16; let info_width = info_text.chars().count();
let column_width = area.width - info_width; let column_width = usize::from(area.width) - info_width;
let column_width = if column_width > 0 { column_width } else { 1 }; let column_width = if column_width > 0 { column_width } else { 1 };
let splits = if has_containers { let splits = if has_containers {
vec![Constraint::Min(column_width), Constraint::Min(info_width)] vec![
Constraint::Min(column_width.try_into().unwrap_or_default()),
Constraint::Min(info_width.try_into().unwrap_or_default()),
]
} else { } else {
vec![Constraint::Percentage(100)] vec![Constraint::Percentage(100)]
}; };
@@ -540,20 +538,21 @@ pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.border_style(Style::default().fg(Color::Black)); .border_style(Style::default().fg(Color::Black));
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::MiddleCentre,
);
let split_popup = Layout::default() let split_popup = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints( .constraints(
[ [
Constraint::Max(NAME_TEXT.lines().count() as u16), Constraint::Max(NAME_TEXT.lines().count().try_into().unwrap_or_default()),
Constraint::Max(description_text.lines().count() as u16), Constraint::Max(
Constraint::Max(help_text.lines().count() as u16), description_text
.lines()
.count()
.try_into()
.unwrap_or_default(),
),
Constraint::Max(help_text.lines().count().try_into().unwrap_or_default()),
] ]
.as_ref(), .as_ref(),
) )
@@ -604,12 +603,7 @@ pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: AppError, seconds: Option<
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::MiddleCentre,
);
f.render_widget(Clear, area); f.render_widget(Clear, area);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
@@ -633,32 +627,33 @@ pub fn info<B: Backend>(f: &mut Frame<'_, B>, text: String) {
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::BottomRight);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::BottomRight,
);
f.render_widget(Clear, area); f.render_widget(Clear, area);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
/// draw a box in the one of the BoxLocations, based on max line width + number of lines /// draw a box in the one of the BoxLocations, based on max line width + number of lines
fn popup(text_lines: u16, text_width: u16, r: Rect, box_location: BoxLocation) -> Rect { fn popup(text_lines: usize, text_width: usize, r: Rect, box_location: BoxLocation) -> Rect {
// Make sure blank_space can't be an negative, as will crash // Make sure blank_space can't be an negative, as will crash
let blank_vertical = if r.height > text_lines { let blank_vertical = if usize::from(r.height) > text_lines {
(r.height - text_lines) / 2 (usize::from(r.height) - text_lines) / 2
} else { } else {
1 1
}; };
let blank_horizontal = if r.width > text_width { let blank_horizontal = if usize::from(r.width) > text_width {
(r.width - text_width) / 2 (usize::from(r.width) - text_width) / 2
} else { } else {
1 1
}; };
let v_constraints = box_location.get_vertical_constraints(blank_vertical, text_lines); let v_constraints = box_location.get_vertical_constraints(
let h_constraints = box_location.get_horizontal_constraints(blank_horizontal, text_width); blank_vertical.try_into().unwrap_or_default(),
text_lines.try_into().unwrap_or_default(),
);
let h_constraints = box_location.get_horizontal_constraints(
blank_horizontal.try_into().unwrap_or_default(),
text_width.try_into().unwrap_or_default(),
);
let indexes = box_location.get_indexes(); let indexes = box_location.get_indexes();
+4 -4
View File
@@ -251,22 +251,22 @@ impl GuiState {
self.selected_panel = self.selected_panel.prev(); self.selected_panel = self.selected_panel.prev();
} }
/// Advance loading animation /// Insert a new loading_uuid into hashset, and advance the animation by one frame
pub fn next_loading(&mut self, uuid: Uuid) { pub fn next_loading(&mut self, uuid: Uuid) {
self.loading_icon = self.loading_icon.next(); self.loading_icon = self.loading_icon.next();
self.is_loading.insert(uuid); self.is_loading.insert(uuid);
} }
/// if is_loading, return loading animation frame, else single space /// If is_loading has any entries, return the current loading_icon, else an emtpy string
pub fn get_loading(&mut self) -> String { pub fn get_loading(&mut self) -> String {
if self.is_loading.is_empty() { if self.is_loading.is_empty() {
String::from(" ") String::new()
} else { } else {
self.loading_icon.to_string() self.loading_icon.to_string()
} }
} }
/// set is_loading to false, but keep animation frame at same state /// Remove a loading_uuid from the is_loading hashset
pub fn remove_loading(&mut self, uuid: Uuid) { pub fn remove_loading(&mut self, uuid: Uuid) {
self.is_loading.remove(&uuid); self.is_loading.remove(&uuid);
} }
+8 -2
View File
@@ -148,7 +148,7 @@ fn ui<B: Backend>(
) { ) {
// set max height for container section, needs +4 to deal with docker commands list and borders // set max height for container section, needs +4 to deal with docker commands list and borders
let height = app_data.lock().get_container_len(); let height = app_data.lock().get_container_len();
let height = if height < 12 { (height + 4) as u16 } else { 12 }; let height = if height < 12 { height + 4 } else { 12 };
let column_widths = app_data.lock().get_width(); let column_widths = app_data.lock().get_width();
let has_containers = !app_data.lock().containers.items.is_empty(); let has_containers = !app_data.lock().containers.items.is_empty();
@@ -168,7 +168,13 @@ fn ui<B: Backend>(
// Split into 3, containers+controls, logs, then graphs // Split into 3, containers+controls, logs, then graphs
let upper_main = Layout::default() let upper_main = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([Constraint::Max(height as u16), Constraint::Percentage(50)].as_ref()) .constraints(
[
Constraint::Max(height.try_into().unwrap_or_default()),
Constraint::Percentage(50),
]
.as_ref(),
)
.split(whole_layout[1]); .split(whole_layout[1]);
let top_split = if has_containers { let top_split = if has_containers {