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
// Copyright (c) Facebook, Inc. and its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// View Module defines how to render below inside terminal.
///
/// ## High level architecture
/// ```text
///  ------------------------------------------------------------
/// |                      Status Bar                            |
///  ------------------------------------------------------------
///  ------------------------------------------------------------
/// |                      System View                           |
///  ------------------------------------------------------------
///  ------------------------------------------------------------
/// |                      Stats View                            |
///  ------------------------------------------------------------
/// ```
/// * Status Bar: Displays datetime, elapsed time, hostname, and below version.
/// * System View: Displays overall system stats including cpu, mem, io, iface, transport, and network.
/// * Stats View: Display the detailed stats. Please check the stats view section for more details.
///
/// ### Stats View
/// ```text
///  ------------------------------------------------------------
/// |                         Tabs                               |
/// | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
/// |                 Column name in Bold                        |
/// |                 Selectable Stats View                      |
///  ------------------------------------------------------------
/// |                 Command Palette                            |
///  ------------------------------------------------------------
/// ```
/// * Tabs: Defines the topics of stats view. Each stats view by default will show only the general stats:
///   a combination of all important stats from each topic. User can use `tab` or `shift-tab` to switch
///   between different tabs to see the detailed view of that topic. For example, for cgroup view, the `general` tab
///   will only show pressure status of cpu_some, memory_full, io_full. But the `pressure` tab will show all
///   pressure related stats including cpu_some, memory_some, memory_full, io_some, io_full.
///
/// * Column names: The column names line also called title line in below_derive. It defines the table column of
///   the following selectable view. A user can press `,` or `.` to switch between different columns and press `s`
///   or `S` to sort in ascending or descending order.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, SystemTime};

use anyhow::Result;
use crossterm::{event::DisableMouseCapture, execute};
use cursive::event::Event;
use cursive::views::{LinearLayout, OnEventView, Panel, ResizedView, StackView};
use cursive::Cursive;
use cursive::CursiveRunnable;
use cursive::{
    theme::{BaseColor, Color, PaletteColor},
    view::Identifiable,
};
use toml::value::Value;

use common::logutil::get_last_log_to_display;
use common::open_source_shim;
use common::util::{
    get_belowrc_cmd_section_key, get_belowrc_filename, get_belowrc_view_section_key,
};
use model::{CgroupModel, Model, NetworkModel, ProcessModel, SystemModel};
use store::Advance;
extern crate render as base_render;

open_source_shim!();

mod cgroup_tabs;
pub mod cgroup_view;
pub mod command_palette;
mod core_tabs;
mod core_view;
mod default_styles;
mod filter_popup;
mod help_menu;
mod process_tabs;
mod process_view;
mod render;
pub mod stats_view;
mod status_bar;
mod system_view;
mod tab_view;

pub struct View {
    inner: CursiveRunnable,
}

macro_rules! advance {
    ($c:ident, $adv:ident, $dir:expr) => {
        match $adv.advance($dir) {
            Some(data) => {
                $c.user_data::<ViewState>()
                    .expect("No user data set")
                    .update(data);
            }
            None => view_warn!(
                $c,
                "Data is not available{}",
                if $dir == Direction::Forward {
                    " yet."
                } else {
                    "."
                }
            ),
        }
    };
}

// Raise warning message in current view.
macro_rules! view_warn {
    ($c:ident, $($args:tt)*) => {{
        let state = $c
            .user_data::<crate::ViewState>()
            .expect("No user data set")
            .main_view_state
            .clone();
        let msg = format!($($args)*);
        match state {
            crate::MainViewState::Cgroup => crate::cgroup_view::ViewType::cp_warn($c, &msg),
            crate::MainViewState::Process | crate::MainViewState::ProcessZoomedIntoCgroup => {
                crate::process_view::ViewType::cp_warn($c, &msg)
            }
            crate::MainViewState::Core => crate::core_view::ViewType::cp_warn($c, &msg),
        }
    }};
}

// controllers depends on Advance
pub mod controllers;
pub mod viewrc;
// Jump popup depends on view_warn
mod jump_popup;

#[derive(Clone, Debug, PartialEq)]
pub enum MainViewState {
    Cgroup,
    Process,
    ProcessZoomedIntoCgroup,
    Core,
}

#[derive(Clone)]
pub enum ViewMode {
    Live(Rc<RefCell<Advance>>),
    Pause(Rc<RefCell<Advance>>),
    Replay(Rc<RefCell<Advance>>),
}

// Invoked either when the data view was explicitly advanced, or
// periodically (during live mode)
fn refresh(c: &mut Cursive) {
    status_bar::refresh(c);
    system_view::refresh(c);
    let current_state = c
        .user_data::<ViewState>()
        .expect("No data stored in Cursive object!")
        .main_view_state
        .clone();
    match current_state {
        MainViewState::Cgroup => cgroup_view::CgroupView::refresh(c),
        MainViewState::Process | MainViewState::ProcessZoomedIntoCgroup => {
            process_view::ProcessView::refresh(c)
        }
        MainViewState::Core => core_view::CoreView::refresh(c),
    }
}

pub struct ViewState {
    pub time_elapsed: Duration,
    /// Keep track of the lowest seen `time_elapsed` so that view can highlight abnormal
    /// elapsed times. Below will never go faster than the requested interval rate but
    /// can certainly go higher (b/c of a loaded system or other delays).
    pub lowest_time_elapsed: Duration,
    pub timestamp: SystemTime,
    pub system: Rc<RefCell<SystemModel>>,
    pub cgroup: Rc<RefCell<CgroupModel>>,
    pub process: Rc<RefCell<ProcessModel>>,
    pub network: Rc<RefCell<NetworkModel>>,
    pub main_view_state: MainViewState,
    pub mode: ViewMode,
    pub event_controllers: Rc<RefCell<HashMap<Event, controllers::Controllers>>>,
    pub cmd_controllers: Rc<RefCell<HashMap<&'static str, controllers::Controllers>>>,
}

impl ViewState {
    pub fn update(&mut self, model: Model) {
        self.time_elapsed = model.time_elapsed;
        if model.time_elapsed.as_secs() != 0 && model.time_elapsed < self.lowest_time_elapsed {
            self.lowest_time_elapsed = model.time_elapsed;
        }
        self.timestamp = model.timestamp;
        self.system.replace(model.system);
        self.cgroup.replace(model.cgroup);
        self.process.replace(model.process);
        self.network.replace(model.network);
    }

    pub fn new_with_advance(main_view_state: MainViewState, model: Model, mode: ViewMode) -> Self {
        Self {
            time_elapsed: model.time_elapsed,
            lowest_time_elapsed: model.time_elapsed,
            timestamp: model.timestamp,
            system: Rc::new(RefCell::new(model.system)),
            cgroup: Rc::new(RefCell::new(model.cgroup)),
            process: Rc::new(RefCell::new(model.process)),
            network: Rc::new(RefCell::new(model.network)),
            main_view_state,
            mode,
            event_controllers: Rc::new(RefCell::new(HashMap::new())),
            cmd_controllers: Rc::new(RefCell::new(controllers::make_cmd_controller_map())),
        }
    }

    pub fn view_mode_str(&self) -> &'static str {
        match self.mode {
            ViewMode::Live(_) => "live",
            ViewMode::Pause(_) => "live-paused",
            ViewMode::Replay(_) => "replay",
        }
    }

    pub fn is_paused(&self) -> bool {
        match self.mode {
            ViewMode::Pause(_) => true,
            _ => false,
        }
    }
}

impl View {
    pub fn new_with_advance(model: model::Model, mode: ViewMode) -> View {
        let mut inner = cursive::CursiveRunnable::new(|| {
            let backend = cursive::backends::crossterm::Backend::init().map(|termion_backend| {
                Box::new(cursive_buffered_backend::BufferedBackend::new(
                    termion_backend,
                )) as Box<(dyn cursive::backend::Backend)>
            });
            execute!(std::io::stdout(), DisableMouseCapture).expect("Failed to disable mouse.");
            backend
        });
        inner.set_user_data(ViewState::new_with_advance(
            MainViewState::Cgroup,
            model,
            mode,
        ));
        View { inner }
    }

    pub fn cb_sink(&mut self) -> &::cursive::CbSink {
        self.inner.set_fps(4);
        self.inner.cb_sink()
    }

    // Function to generate event_controller_map, we cannot make
    // event_controller_map during ViewState construction since it
    // depends on CommandPalette to construct for raising errors
    pub fn generate_event_controller_map(c: &mut Cursive, filename: String) {
        // Verify belowrc file format
        let cmdrc_opt = match std::fs::read_to_string(filename) {
            Ok(belowrc_str) => match belowrc_str.parse::<Value>() {
                Ok(belowrc) => {
                    if let Some(cmdrc) = belowrc.get(get_belowrc_cmd_section_key()) {
                        Some(cmdrc.to_owned())
                    } else {
                        None
                    }
                }
                Err(e) => {
                    view_warn!(c, "Failed to parse belowrc: {}", e);
                    None
                }
            },
            _ => None,
        };

        let event_controller_map = controllers::make_event_controller_map(c, &cmdrc_opt);

        c.user_data::<ViewState>()
            .expect("No data stored in Cursive object!")
            .event_controllers
            .replace(event_controller_map);
    }

    pub fn run(&mut self) -> Result<()> {
        let mut theme = self.inner.current_theme().clone();
        theme.palette[PaletteColor::Background] = Color::TerminalDefault;
        theme.palette[PaletteColor::View] = Color::TerminalDefault;
        theme.palette[PaletteColor::Primary] = Color::TerminalDefault;
        theme.palette[PaletteColor::Highlight] = Color::Dark(BaseColor::Cyan);
        theme.palette[PaletteColor::HighlightText] = Color::Dark(BaseColor::Black);
        theme.shadow = false;

        self.inner.set_theme(theme);

        self.inner
            .add_global_callback(Event::CtrlChar('z'), |c| unsafe {
                use crossterm::cursor::{Hide, Show};
                use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen};

                // The following logic is necessary on crossterm as it does not
                // disable/re-enable tty on SIGTSTP, while ncurses does.

                // Reset tty to original mode
                execute!(std::io::stdout(), LeaveAlternateScreen, Show)
                    .expect("Failed to reset tty");
                crossterm::terminal::disable_raw_mode().expect("Failed to disable tty");

                // Send signal to put process to background
                if libc::raise(libc::SIGTSTP) != 0 {
                    panic!("failed to SIGTSTP self");
                }

                // Re-enable tty
                crossterm::terminal::enable_raw_mode().expect("Failed to enable tty");
                execute!(std::io::stdout(), EnterAlternateScreen, Hide)
                    .expect("Failed to setup tty");
                // Use WindowResize event to force redraw everything.
                c.on_event(Event::WindowResize);
            });
        self.inner.add_global_callback(Event::Refresh, |c| {
            refresh(c);
        });
        self.inner.add_global_callback(Event::CtrlChar('r'), |c| {
            c.clear();
            refresh(c);
        });

        // Used to handle warning assignment to the correct view
        let init_warnings = get_last_log_to_display();

        let status_bar = status_bar::new(&mut self.inner);
        let system_view = system_view::new(&mut self.inner);
        let cgroup_view = cgroup_view::CgroupView::new(&mut self.inner);
        let process_view = process_view::ProcessView::new(&mut self.inner);
        let core_view = core_view::CoreView::new(&mut self.inner);

        self.inner
            .add_fullscreen_layer(ResizedView::with_full_screen(
                LinearLayout::vertical()
                    .child(Panel::new(status_bar))
                    .child(Panel::new(system_view))
                    .child(
                        OnEventView::new(
                            StackView::new()
                                .fullscreen_layer(ResizedView::with_full_screen(
                                    core_view.with_name("core_view_panel"),
                                ))
                                .fullscreen_layer(ResizedView::with_full_screen(
                                    process_view.with_name("process_view_panel"),
                                ))
                                .fullscreen_layer(ResizedView::with_full_screen(
                                    cgroup_view.with_name("cgroup_view_panel"),
                                ))
                                .with_name("main_view_stack"),
                        )
                        .with_name("dynamic_view"),
                    ),
            ));

        self.inner
            .focus_name("dynamic_view")
            .expect("Could not set focus at initialization!");

        // Raise warning message if failed to map the customzied command.
        Self::generate_event_controller_map(&mut self.inner, get_belowrc_filename());
        viewrc::ViewRc::process(&mut self.inner);
        if let Some(msg) = init_warnings {
            let c = &mut self.inner;
            view_warn!(c, "{}", msg);
        }
        self.inner.run();

        Ok(())
    }
}

#[cfg(test)]
pub mod fake_view {
    use cursive::views::ViewRef;

    use super::*;
    use crate::{
        cgroup_view::CgroupView, command_palette::CommandPalette, stats_view::StatsView,
        MainViewState, ViewMode, ViewState,
    };
    use common::logutil::get_logger;
    use model::Collector;
    use store::advance::new_advance_local;

    use std::cell::RefCell;
    use std::path::PathBuf;
    use std::rc::Rc;

    pub struct FakeView {
        pub inner: CursiveRunnable,
    }

    impl FakeView {
        pub fn new() -> Self {
            let time = SystemTime::now();
            let logger = get_logger();
            let advance = new_advance_local(logger.clone(), PathBuf::new(), time);
            let mut collector = Collector::new(Default::default());
            let model = collector.update_model(&logger).expect("Fail to get model");

            let mut inner = CursiveRunnable::dummy();
            inner.set_user_data(ViewState::new_with_advance(
                MainViewState::Cgroup,
                model,
                ViewMode::Live(Rc::new(RefCell::new(advance))),
            ));

            Self { inner }
        }

        pub fn add_cgroup_view(&mut self) {
            let cgroup_view = CgroupView::new(&mut self.inner);
            self.inner.add_layer(cgroup_view);
        }

        pub fn get_cmd_palette(&mut self, name: &str) -> ViewRef<CommandPalette> {
            self.inner
                .find_name::<StatsView<CgroupView>>(name)
                .expect("Failed to dereference command palette")
                .get_cmd_palette()
        }
    }
}