fuck web, tui init

pull/1/head
plazmoid 3 years ago
parent f840865597
commit ec3f78b8cd
  1. 4
      Cargo.toml
  2. 8
      bin/u_panel/Cargo.toml
  3. 7
      bin/u_panel/src/argparse.rs
  4. 1
      bin/u_panel/src/main.rs
  5. 82
      bin/u_panel/src/tui/mod.rs
  6. 53
      bin/u_panel/src/tui/state.rs
  7. 26
      bin/u_panel/src/tui/ui.rs
  8. 14
      integration/tests/tests.rs
  9. 3
      lib/u_lib/src/errors/variants.rs
  10. 0
      scripts/get_docker_ip.sh

@ -2,8 +2,8 @@
members = [ members = [
"bin/u_agent", "bin/u_agent",
"bin/u_panel", "bin/u_panel",
"bin/u_panel/be", #"bin/u_panel/be",
"bin/u_panel/fe", #"bin/u_panel/fe",
"bin/u_run", "bin/u_run",
"bin/u_server", "bin/u_server",
"lib/u_lib", "lib/u_lib",

@ -14,5 +14,9 @@ uuid = "0.6.5"
serde_json = "1.0.4" serde_json = "1.0.4"
serde = { version = "1.0.114", features = ["derive"] } serde = { version = "1.0.114", features = ["derive"] }
tokio = "1.11.0" tokio = "1.11.0"
be = { version = "*", path = "./be" } # be = { version = "*", path = "./be" }
u_lib = { version = "*", path = "../../lib/u_lib" } u_lib = { version = "*", path = "../../lib/u_lib" }
tui = { version = "0.16", default-features = false, features = ['crossterm'] }
crossterm = "0.22.1"
anyhow = "1.0.44"
strum = { version = "0.22.0", features = ["derive"] }

@ -19,7 +19,7 @@ enum Cmd {
Agents(LD), Agents(LD),
Jobs(JobALD), Jobs(JobALD),
Jobmap(JobMapALD), Jobmap(JobMapALD),
Server, TUI,
} }
#[derive(StructOpt, Debug)] #[derive(StructOpt, Debug)]
@ -101,7 +101,7 @@ pub async fn process_cmd(args: Args) -> UResult<()> {
} }
let token = env::var("ADMIN_AUTH_TOKEN").map_err(|_| UError::WrongToken)?; let token = env::var("ADMIN_AUTH_TOKEN").map_err(|_| UError::WrongToken)?;
let cli_handler = ClientHandler::new(None).password(token); let cli_handler = ClientHandler::new(None).password(token.clone());
let printer = Printer { json: args.json }; let printer = Printer { json: args.json };
match args.cmd { match args.cmd {
Cmd::Agents(action) => match action { Cmd::Agents(action) => match action {
@ -131,7 +131,8 @@ pub async fn process_cmd(args: Args) -> UResult<()> {
JobMapALD::List { uid } => printer.print(cli_handler.get_agent_jobs(uid).await), JobMapALD::List { uid } => printer.print(cli_handler.get_agent_jobs(uid).await),
JobMapALD::Delete { uid } => printer.print(cli_handler.del(Some(uid)).await), JobMapALD::Delete { uid } => printer.print(cli_handler.del(Some(uid)).await),
}, },
Cmd::Server => be::serve().unwrap(), //Cmd::Server => be::serve().unwrap(),
Cmd::TUI => crate::tui::init_tui(token).map_err(|e| UError::TUIError(e.to_string()))?,
} }
Ok(()) Ok(())
} }

@ -1,4 +1,5 @@
mod argparse; mod argparse;
mod tui;
use argparse::{process_cmd, Args}; use argparse::{process_cmd, Args};
use std::process; use std::process;

@ -0,0 +1,82 @@
mod state;
mod ui;
use anyhow::Result;
use crossterm::event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode};
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use state::State;
use std::panic::set_hook;
use std::process::exit;
use std::{
io::{stdout, Stdout},
sync::mpsc,
thread,
time::Duration,
};
use tui::{backend::CrosstermBackend, Terminal};
type Frame<'f> = tui::Frame<'f, CrosstermBackend<Stdout>>;
pub fn init_tui(token: String) -> Result<()> {
//TODO: fix this
set_hook(Box::new(|p| {
teardown().unwrap();
eprintln!("{}", p);
exit(254);
}));
let mut state = State::new(token);
if let Err(e) = init(&mut state) {
teardown()?;
return Err(e);
}
Ok(())
}
fn init(state: &mut State) -> Result<()> {
let mut stdout = stdout();
enable_raw_mode()?;
execute!(&mut stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let (tx, rx) = mpsc::channel();
thread::spawn(move || loop {
if event::poll(Duration::from_millis(10)).unwrap() {
match event::read().unwrap() {
key @ Event::Key(_) => tx.send(key).unwrap(),
_ => (),
}
}
});
terminal.clear()?;
loop {
terminal.draw(|f| ui::draw(f, state))?;
match rx.recv()? {
Event::Key(key) => match key.code {
KeyCode::Esc => {
teardown()?;
terminal.show_cursor()?;
break;
}
KeyCode::Left => state.prev_tab(),
KeyCode::Right => state.next_tab(),
_ => (),
},
_ => unreachable!(),
}
}
Ok(())
}
fn teardown() -> Result<()> {
disable_raw_mode()?;
execute!(stdout(), LeaveAlternateScreen, DisableMouseCapture)?;
eprintln!("teardown");
Ok(())
}

@ -0,0 +1,53 @@
use std::str::FromStr;
use strum::VariantNames;
#[derive(strum::Display, strum::EnumVariantNames, strum::EnumString)]
pub enum UiTabs {
Agents,
Jobs,
Map,
}
impl UiTabs {
pub fn variants() -> &'static [&'static str] {
Self::VARIANTS
}
pub fn index(&self) -> usize {
let ss = self.to_string();
Self::VARIANTS.iter().position(|el| **el == ss).unwrap()
}
pub fn next(&self) -> Self {
let next_idx = (self.index() + 1) % Self::VARIANTS.len();
Self::from_str(Self::VARIANTS[next_idx]).unwrap()
}
pub fn prev(&self) -> Self {
let vlen = Self::VARIANTS.len();
let next_idx = (self.index() + vlen - 1) % vlen;
Self::from_str(Self::VARIANTS[next_idx]).unwrap()
}
}
pub struct State {
pub token: String,
pub active_tab: UiTabs,
}
impl State {
pub fn new(token: String) -> Self {
State {
token,
active_tab: UiTabs::Agents,
}
}
pub fn next_tab(&mut self) {
self.active_tab = self.active_tab.next()
}
pub fn prev_tab(&mut self) {
self.active_tab = self.active_tab.prev()
}
}

@ -0,0 +1,26 @@
use super::{
state::{State, UiTabs},
Frame,
};
use tui::style::{Color, Style};
use tui::text::Spans;
use tui::widgets::{Block, Borders, Tabs};
pub fn draw(f: &mut Frame, s: &mut State) {
let titles = UiTabs::variants()
.iter()
.cloned()
.map(Spans::from)
.collect();
let tabs = Tabs::new(titles)
.block(
Block::default()
.title("The whole that you need to know")
.borders(Borders::ALL),
)
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().fg(Color::Yellow))
.divider("-")
.select(s.active_tab.index());
f.render_widget(tabs, f.size())
}

@ -11,11 +11,17 @@ extern crate rstest;
#[tokio::test] #[tokio::test]
async fn test_non_auth_connection_dropped() { async fn test_non_auth_connection_dropped() {
let env_server = env::var("U_SERVER").unwrap(); let env_server = env::var("U_SERVER").unwrap();
match reqwest::get(format!("https://{}:{}", env_server, MASTER_PORT)).await { let client = reqwest::ClientBuilder::new()
.danger_accept_invalid_certs(true)
.build()
.unwrap();
match client
.get(format!("https://{}:{}", env_server, MASTER_PORT))
.send()
.await
{
Err(e) => { Err(e) => {
assert!(e assert!(e.to_string().contains("channel closed"))
.to_string()
.contains("unable to get local issuer certificate"))
} }
_ => panic!("no error occured on foreign client connection"), _ => panic!("no error occured on foreign client connection"),
} }

@ -65,6 +65,9 @@ pub enum UError {
#[error("Panicked: {0}")] #[error("Panicked: {0}")]
Panic(String), Panic(String),
#[error("UI init error: {0}")]
TUIError(String),
} }
impl UError { impl UError {

Loading…
Cancel
Save