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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use bollard::models::ContainerSummary;
use core::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use tui::widgets::{ListItem, ListState};
mod container_state;
use crate::{app_error::AppError, parse_args::CliArgs, ui::log_sanitizer, ENTRY_POINT};
pub use container_state::*;
/// Global app_state, stored in an Arc<Mutex>
#[derive(Debug, Clone)]
pub struct AppData {
containers: StatefulList<ContainerItem>,
error: Option<AppError>,
sorted_by: Option<(Header, SortedOrder)>,
pub args: CliArgs,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SortedOrder {
Asc,
Desc,
}
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum Header {
State,
Status,
Cpu,
Memory,
Id,
Name,
Image,
Rx,
Tx,
}
/// Convert Header enum into strings to display
impl fmt::Display for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let disp = match self {
Self::State => "state",
Self::Status => "status",
Self::Cpu => "cpu",
Self::Memory => "memory/limit",
Self::Id => "id",
Self::Name => "name",
Self::Image => "image",
Self::Rx => "↓ rx",
Self::Tx => "↑ tx",
};
write!(f, "{disp:>x$}", x = f.width().unwrap_or(1))
}
}
impl AppData {
/// Change the sorted order, also set the selected container state to match new order
fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) {
self.sorted_by = x;
self.sort_containers();
self.containers
.state
.select(self.containers.items.iter().position(|i| {
self.get_selected_container_id()
.map_or(false, |id| i.id == id)
}));
}
/// Current time as unix timestamp
#[allow(clippy::expect_used)]
fn get_systemtime() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("In our known reality, this error should never occur")
.as_secs()
}
/// Generate a default app_state
pub fn default(args: CliArgs) -> Self {
Self {
args,
containers: StatefulList::new(vec![]),
error: None,
sorted_by: None,
}
}
/// Container sort related methods
/// Remove the sorted header & order, and sort by default - created datetime
pub fn reset_sorted(&mut self) {
self.set_sorted(None);
}
/// Sort containers based on a given header, if headings match, and already ascending, remove sorting
pub fn set_sort_by_header(&mut self, selected_header: Header) {
let mut output = Some((selected_header, SortedOrder::Asc));
if let Some((current_header, order)) = self.get_sorted() {
if current_header == selected_header {
match order {
SortedOrder::Desc => output = None,
SortedOrder::Asc => output = Some((selected_header, SortedOrder::Desc)),
}
}
}
self.set_sorted(output);
}
pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> {
self.sorted_by
}
/// Sort the containers vec, based on a heading, either ascending or descending,
/// If not sort set, then sort by created time
pub fn sort_containers(&mut self) {
if let Some((head, ord)) = self.sorted_by {
match head {
Header::State => match ord {
SortedOrder::Asc => self
.containers
.items
.sort_by(|a, b| b.state.order().cmp(&a.state.order())),
SortedOrder::Desc => self
.containers
.items
.sort_by(|a, b| a.state.order().cmp(&b.state.order())),
},
Header::Status => match ord {
SortedOrder::Asc => self
.containers
.items
.sort_by(|a, b| a.status.cmp(&b.status)),
SortedOrder::Desc => self
.containers
.items
.sort_by(|a, b| b.status.cmp(&a.status)),
},
Header::Cpu => match ord {
SortedOrder::Asc => self
.containers
.items
.sort_by(|a, b| a.cpu_stats.back().cmp(&b.cpu_stats.back())),
SortedOrder::Desc => self
.containers
.items
.sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())),
},
Header::Memory => match ord {
SortedOrder::Asc => self
.containers
.items
.sort_by(|a, b| a.mem_stats.back().cmp(&b.mem_stats.back())),
SortedOrder::Desc => self
.containers
.items
.sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())),
},
Header::Id => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.id.cmp(&b.id)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.id.cmp(&a.id)),
},
Header::Image => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)),
SortedOrder::Desc => {
self.containers.items.sort_by(|a, b| b.image.cmp(&a.image));
}
},
Header::Name => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.name.cmp(&b.name)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.name.cmp(&a.name)),
},
Header::Rx => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.rx.cmp(&b.rx)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.rx.cmp(&a.rx)),
},
Header::Tx => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.tx.cmp(&b.tx)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.tx.cmp(&a.tx)),
},
}
} else {
self.containers
.items
.sort_by(|a, b| a.created.cmp(&b.created));
}
}
/// Container state methods
/// Just get the total number of containers
pub fn get_container_len(&self) -> usize {
self.containers.items.len()
}
/// Get title for containers section
pub fn container_title(&self) -> String {
self.containers.get_state_title()
}
/// Select the first container
pub fn containers_start(&mut self) {
self.containers.start();
}
// select the last container
pub fn containers_end(&mut self) {
self.containers.end();
}
/// Select the next container
pub fn containers_next(&mut self) {
self.containers.next();
}
// select the previous container
pub fn containers_previous(&mut self) {
self.containers.previous();
}
/// Get Container items
pub const fn get_container_items(&self) -> &Vec<ContainerItem> {
&self.containers.items
}
/// Get Option of the current selected container
pub fn get_selected_container(&self) -> Option<&ContainerItem> {
self.containers
.state
.selected()
.and_then(|i| self.containers.items.get(i))
}
/// Get mutable Option of the current selected container
fn get_mut_selected_container(&mut self) -> Option<&mut ContainerItem> {
self.containers
.state
.selected()
.and_then(|i| self.containers.items.get_mut(i))
}
/// Get ListState of containers
pub fn get_container_state(&mut self) -> &mut ListState {
&mut self.containers.state
}
/// Selected DockerCommand methods
/// Get the current selected docker command
/// So know which command to execute
pub fn selected_docker_command(&self) -> Option<DockerControls> {
self.get_selected_container().and_then(|i| {
i.docker_controls.state.selected().and_then(|x| {
i.docker_controls
.items
.get(x)
.map(std::borrow::ToOwned::to_owned)
})
})
}
/// Get mutable Option of the currently selected container DockerControls state
pub fn get_control_state(&mut self) -> Option<&mut ListState> {
self.get_mut_selected_container()
.map(|i| &mut i.docker_controls.state)
}
/// Get mutable Option of the currently selected container DockerControls items
pub fn get_control_items(&mut self) -> Option<&mut Vec<DockerControls>> {
self.get_mut_selected_container()
.map(|i| &mut i.docker_controls.items)
}
/// Change selected choice of docker commands of selected container
pub fn docker_command_next(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.docker_controls.next();
}
}
/// Change selected choice of docker commands of selected container
pub fn docker_command_previous(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.docker_controls.previous();
}
}
/// Change selected choice of docker commands of selected container
pub fn docker_command_start(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.docker_controls.start();
}
}
/// Change selected choice of docker commands of selected container
pub fn docker_command_end(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.docker_controls.end();
}
}
/// Logs related methods
/// Get the title for log panel for selected container, will be either
/// 1) "logs x/x - container_name" where container_name is 32 chars max
/// 2) "logs - container_name" when no logs found, again 32 chars max
/// 3) "" no container currently selected - aka no containers on system
pub fn get_log_title(&self) -> String {
self.get_selected_container().map_or_else(String::new, |y| {
let logs_len = y.logs.get_state_title();
let mut name = y.name.clone();
name.truncate(32);
if logs_len.is_empty() {
format!("- {name} ")
} else {
format!("{logs_len} - {name}")
}
})
}
/// select next selected log line
pub fn log_next(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.logs.next();
}
}
/// select previous selected log line
pub fn log_previous(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.logs.previous();
}
}
/// select last selected log line
pub fn log_end(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.logs.end();
}
}
/// select first selected log line
pub fn log_start(&mut self) {
if let Some(i) = self.get_mut_selected_container() {
i.logs.start();
}
}
/// Chart data related methods
/// Get mutable Option of the currently selected container chart data
pub fn get_chart_data(&mut self) -> Option<(CpuTuple, MemTuple)> {
self.containers
.state
.selected()
.and_then(|i| self.containers.items.get_mut(i))
.map(|i| i.get_chart_data())
}
/// Logs related methods
/// Get mutable Vec of current containers logs
pub fn get_logs(&mut self) -> Vec<ListItem<'static>> {
self.containers
.state
.selected()
.and_then(|i| self.containers.items.get_mut(i))
.map_or(vec![], |i| i.logs.to_vec())
}
/// Get mutable Option of the currently selected container Logs state
pub fn get_log_state(&mut self) -> Option<&mut ListState> {
self.containers
.state
.selected()
.and_then(|i| self.containers.items.get_mut(i))
.map(|i| i.logs.state())
}
/// Error realted methods
/// return single app_state error
pub const fn get_error(&self) -> Option<AppError> {
self.error
}
/// remove single app_state error
pub fn remove_error(&mut self) {
self.error = None;
}
/// insert single app_state error
pub fn set_error(&mut self, error: AppError) {
self.error = Some(error);
}
/// Check if the selected container is a dockerised version of oxker
/// So that can disallow commands to be send
/// Is a shabby way of implementing this
pub fn is_oxker(&self) -> bool {
self.get_selected_container().map_or(false, |i| i.is_oxker)
}
/// 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 number_with_cpu_status = self
.containers
.items
.iter()
.filter(|i| !i.cpu_stats.is_empty())
.count();
count_is_running == number_with_cpu_status
}
/// Find the widths for the strings in the containers panel.
/// So can display nicely and evenly
pub fn get_width(&self) -> Columns {
let mut columns = Columns::new();
let count = |x: &String| u8::try_from(x.chars().count()).unwrap_or(12);
// Should probably find a refactor here somewhere
for container in &self.containers.items {
let cpu_count = count(
&container
.cpu_stats
.back()
.unwrap_or(&CpuStats::default())
.to_string(),
);
let rx_count = count(&container.rx.to_string());
let tx_count = count(&container.tx.to_string());
let image_count = count(&container.image);
let name_count = count(&container.name);
let state_count = count(&container.state.to_string());
let status_count = count(&container.status);
let mem_current_count = count(
&container
.mem_stats
.back()
.unwrap_or(&ByteStats::default())
.to_string(),
);
let mem_limit_count = count(&container.mem_limit.to_string());
if cpu_count > columns.cpu.1 {
columns.cpu.1 = cpu_count;
};
if image_count > columns.image.1 {
columns.image.1 = image_count;
};
if mem_current_count > columns.mem.1 {
columns.mem.1 = mem_current_count;
};
if mem_limit_count > columns.mem.2 {
columns.mem.2 = mem_limit_count;
};
if name_count > columns.name.1 {
columns.name.1 = name_count;
};
if state_count > columns.state.1 {
columns.state.1 = state_count;
};
if status_count > columns.status.1 {
columns.status.1 = status_count;
};
if rx_count > columns.net_rx.1 {
columns.net_rx.1 = rx_count;
};
if tx_count > columns.net_tx.1 {
columns.net_tx.1 = tx_count;
};
}
columns
}
/// Update related methods
/// return a mutable container by given id
fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
self.containers.items.iter_mut().find(|i| &i.id == id)
}
/// Find the id of the currently selected container.
/// If any containers on system, will always return a ContainerId
/// Only returns None when no containers found.
pub fn get_selected_container_id(&self) -> Option<ContainerId> {
self.get_selected_container().map(|i| i.id.clone())
}
/// Update container mem, cpu, & network stats, in single function so only need to call .lock() once
/// Will also, if a sort is set, sort the containers
pub fn update_stats(
&mut self,
id: &ContainerId,
cpu_stat: Option<f64>,
mem_stat: Option<u64>,
mem_limit: u64,
rx: u64,
tx: u64,
) {
if let Some(container) = self.get_container_by_id(id) {
if container.cpu_stats.len() >= 60 {
container.cpu_stats.pop_front();
}
if container.mem_stats.len() >= 60 {
container.mem_stats.pop_front();
}
if let Some(cpu) = cpu_stat {
container.cpu_stats.push_back(CpuStats::new(cpu));
}
if let Some(mem) = mem_stat {
container.mem_stats.push_back(ByteStats::new(mem));
}
container.rx.update(rx);
container.tx.update(tx);
container.mem_limit.update(mem_limit);
}
// need to benchmark this?
// if self.get_sorted().is_some() {
self.sort_containers();
// }
}
/// Update, or insert, containers
pub fn update_containers(&mut self, all_containers: &mut [ContainerSummary]) {
let all_ids = self
.containers
.items
.iter()
.map(|i| i.id.clone())
.collect::<Vec<_>>();
// Only sort it no containers currently set, as afterwards the order is fixed
if self.containers.items.is_empty() {
all_containers.sort_by(|a, b| a.created.cmp(&b.created));
}
if !all_containers.is_empty() && self.containers.state.selected().is_none() {
self.containers.start();
}
for (index, id) in all_ids.iter().enumerate() {
if !all_containers
.iter()
.filter_map(|i| i.id.as_ref())
.any(|x| x == id.get())
{
// If removed container is currently selected, then change selected to previous
// This will default to 0 in any edge cases
if self.containers.state.selected().is_some() {
self.containers.previous();
}
// Check is some, else can cause out of bounds error, if containers get removed before a docker update
if self.containers.items.get(index).is_some() {
self.containers.items.remove(index);
}
}
}
// Trim a &String and return String
let trim_owned = |x: &String| x.trim().to_owned();
for i in all_containers {
if let Some(id) = i.id.as_ref() {
let name = i.names.as_mut().map_or(String::new(), |names| {
names.first_mut().map_or(String::new(), |f| {
if f.starts_with('/') {
f.remove(0);
}
(*f).to_string()
})
});
let is_oxker = i
.command
.as_ref()
.map_or(false, |i| i.starts_with(ENTRY_POINT));
let state = State::from(i.state.as_ref().map_or("dead".to_owned(), trim_owned));
let status = i.status.as_ref().map_or(String::new(), trim_owned);
let image = i
.image
.as_ref()
.map_or(String::new(), std::clone::Clone::clone);
let id = ContainerId::from(id);
let created = i.created.map_or(0, |i| u64::try_from(i).unwrap_or(0));
// If container info already in containers Vec, then just update details
if let Some(item) = self.get_container_by_id(&id) {
if item.name != name {
item.name = name;
};
if item.status != status {
item.status = status;
};
if item.state != 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
match state {
State::Removing | State::Restarting | State::Unknown => {
item.docker_controls.state.select(None);
}
_ => item.docker_controls.start(),
};
item.state = state;
};
if item.image != image {
item.image = image;
};
} else {
// container not known, so make new ContainerItem and push into containers Vec
let container =
ContainerItem::new(created, id, image, is_oxker, name, state, status);
self.containers.items.push(container);
}
}
}
}
/// update logs of a given container, based on id
pub fn update_log_by_id(&mut self, logs: Vec<String>, id: &ContainerId) {
let color = self.args.color;
let raw = self.args.raw;
let timestamp = self.args.timestamp;
if let Some(container) = self.get_container_by_id(id) {
container.last_updated = Self::get_systemtime();
let current_len = container.logs.len();
for mut i in logs {
let tz = LogsTz::from(&i);
// Strip the timestamp if `-t` flag set
if !timestamp {
i = i.replace(&tz.to_string(), "");
}
let lines = if color {
log_sanitizer::colorize_logs(&i)
} else if raw {
log_sanitizer::raw(&i)
} else {
log_sanitizer::remove_ansi(&i)
};
container.logs.insert(ListItem::new(lines), tz);
}
// 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()
|| container.logs.state().selected().map_or(1, |f| f + 1) == current_len
{
container.logs.end();
}
}
}
}