Skip to content

Commit

Permalink
Feature/logs (#4)
Browse files Browse the repository at this point in the history
* add fancy checkbox

* add log settinsg

* switched executable icon

* added logger trait and struct

* :)

* smome little fixes :

* working on ssh and ptcec

* added log help

* bump version

* icon
  • Loading branch information
mono424 authored Jan 18, 2023
1 parent 0f88b70 commit fd31f08
Show file tree
Hide file tree
Showing 19 changed files with 596 additions and 73 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "drawbridge",
"private": true,
"version": "0.0.3",
"version": "0.0.4",
"type": "module",
"scripts": {
"dev": "vite dev",
Expand Down
20 changes: 19 additions & 1 deletion src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "drawbridge"
version = "0.0.3"
version = "0.0.4"
description = "A Tauri App"
authors = ["Khadim Fall"]
license = ""
Expand All @@ -19,7 +19,7 @@ serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.2", features = ["dialog-open", "dialog-save", "shell-open", "updater", "window-all"] }
tonic = "0.8.3"
tokio = { version = "1.24.1", features = ["macros", "rt-multi-thread"] }
tokio = { version = "1.24.1", features = ["macros", "rt-multi-thread", "process"] }
prost = "0.11.5"
tokio-stream = "0.1.11"
futures = "0.3.25"
Expand All @@ -28,6 +28,8 @@ directories = "4.0.1"
base64 = "0.21.0"
regex = "1.7.1"
rust-embed = "6.4.2"
humantime = "2.1.0"
rand = "0.8.5"

[features]
# by default Tauri runs in production mode
Expand Down
Binary file modified src-tauri/public/win/icon.ico
Binary file not shown.
4 changes: 3 additions & 1 deletion src-tauri/src/driver.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use async_trait::async_trait;

use crate::logger;

pub mod connect;
pub mod ssh;
pub mod ptcec;

#[async_trait]
pub trait Driver {
async fn run(&self, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>>;
async fn run(&self, args: Vec<String>, log: Option<logger::Logger>) -> Result<(), Box<dyn std::error::Error>>;
}

pub fn get_driver(driver_name: String) -> Option<Box<dyn Driver>> {
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/src/driver/connect.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use async_trait::async_trait;
use serde_json::Value;

use crate::storage;
use crate::{storage, logger};

use super::{Driver, ptcec, ssh};

pub struct ConnectDriver {}

#[async_trait]
impl Driver for ConnectDriver {
async fn run(&self, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
async fn run(&self, args: Vec<String>, logger: Option<logger::Logger>) -> Result<(), Box<dyn std::error::Error>> {
if args.len() != 3 {
println!("Invalid number of arguments. Please use: drawbridge connect <remote-id>");
std::process::exit(1);
Expand Down Expand Up @@ -40,7 +40,7 @@ impl Driver for ConnectDriver {
r["engine"].as_str().unwrap().to_string(),
r["mode"].as_str().unwrap().to_string(),
r["token"].as_str().unwrap().to_string(),
]).await;
], logger).await;
}

if driver_name.eq("ssh") {
Expand All @@ -52,7 +52,7 @@ impl Driver for ConnectDriver {
r["url"].as_str().unwrap().to_string(),
r["runCommand"].as_str().unwrap().to_string(),
r["privateKeyFile"].as_str().unwrap().to_string(),
]).await;
], logger).await;
}

println!("Driver {} not found.", driver_name);
Expand Down
83 changes: 73 additions & 10 deletions src-tauri/src/driver/ptcec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,37 @@ use tonic::transport::Channel;
use tonic::{Request, metadata::AsciiMetadataValue};
use proto::pub_client::PubClient;
use proto::{ StreamEngineInitRequest, StreamEngineRequest, stream_engine_request };
use std::sync::{Arc};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::mpsc;
use tokio::io::{stdin, AsyncBufReadExt, BufReader};
use tokio_stream::StreamExt;
use std::str::{self};
use tokio_stream::wrappers::ReceiverStream;
use tokio::sync::Mutex;

pub mod proto {
tonic::include_proto!("proto");
}

use crate::logger;

use super::Driver;

pub struct PtcecDriver {}

#[async_trait]
impl Driver for PtcecDriver {
async fn run(&self, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
async fn run(&self, args: Vec<String>, logger: Option<logger::Logger>) -> Result<(), Box<dyn std::error::Error>> {
if args.len() != 6 {
println!("Invalid number of arguments. Please use: drawbridge ptcec <url> <engine> <mode> <token>");
std::process::exit(1);
}
return ptcec_run(args[2].clone(), args[3].clone(), args[4].clone(), args[5].clone(), gen_session_id()).await;
return ptcec_run(args[2].clone(), args[3].clone(), args[4].clone(), args[5].clone(), gen_session_id(), logger).await;
}
}

async fn ptcec_run(url: String, engine: String, mode: String, token: String, session_id: String) -> Result<(), Box<dyn std::error::Error>> {
async fn ptcec_run(url: String, engine: String, mode: String, token: String, session_id: String, logger: Option<logger::Logger>) -> Result<(), Box<dyn std::error::Error>> {
let channel = Channel::from_shared(url).unwrap().connect().await?;
let mut auth_header = "Basic ".to_owned();
auth_header.push_str(&token);
Expand All @@ -44,7 +48,17 @@ async fn ptcec_run(url: String, engine: String, mode: String, token: String, ses

let (tx, rx) = mpsc::channel(80);

// Logger
let logger_o_ptr = Arc::new(Mutex::new(logger));
let logger_ptr_a = Arc::clone(&logger_o_ptr);

// Initialize
let mut guard = logger_ptr_a.lock().await; {
if guard.is_some() {
if guard.as_mut().unwrap().debug_info(&format!("Initialize PTCEC with Engine={} Mode={} SessionId={}", &engine, &mode, &session_id).to_string()).is_err() {/* ignored */}
}
drop(guard);
}
let init_req = StreamEngineRequest {
data: Some(stream_engine_request::Data::Init(StreamEngineInitRequest{
engine: engine,
Expand All @@ -54,15 +68,49 @@ async fn ptcec_run(url: String, engine: String, mode: String, token: String, ses
};
tx.send(init_req).await.unwrap();


let logger_ptr_b = Arc::clone(&logger_o_ptr);
tokio::spawn(async move {
let stdin = stdin();
let mut reader = BufReader::new(stdin);
let mut line = String::new();
loop {
reader.read_line(&mut line).await.unwrap();
tx.send(StreamEngineRequest {
match reader.read_line(&mut line).await {
Err(e) => {
let mut guard = logger_ptr_b.lock().await; {
if guard.is_some() {
if guard.as_mut().unwrap().debug_error(&format!("Failed to read stdin: {}", e)).is_err() {/* ignored */}
}
drop(guard);
};
break;
},
_ => (),
}

let mut guard = logger_ptr_a.lock().await; {
if guard.is_some() {
let mut logline = line.clone();
logline.pop();
if guard.as_mut().unwrap().debug_outgoing(&logline).is_err() {/* ignored */}
}
drop(guard);
}

match tx.send(StreamEngineRequest {
data: Some(stream_engine_request::Data::Stdin(line.as_bytes().to_vec())),
}).await.unwrap();
}).await {
Err(e) => {
let mut guard = logger_ptr_b.lock().await; {
if guard.is_some() {
if guard.as_mut().unwrap().debug_error(&format!("Failed to send to remote: {}", e)).is_err() {/* ignored */}
}
drop(guard);
};
break;
},
_ => (),
}
line.clear();
}
});
Expand All @@ -73,12 +121,27 @@ async fn ptcec_run(url: String, engine: String, mode: String, token: String, ses
.await
.unwrap()
.into_inner();


let logger_ptr_c = Arc::clone(&logger_o_ptr);
while let Some(item) = stream.next().await {
match str::from_utf8(item.unwrap().stdout.as_ref()) {
Ok(v) => println!("{}", v),
Err(_) => {/* ignored */},
Ok(v) => {
let mut guard = logger_ptr_c.lock().await;
if guard.is_some() {
if guard.as_mut().unwrap().debug_incomming(&v.clone()).is_err() {/* ignored */}
}
drop(guard);
println!("{}", v)
},
Err(e) => {
let mut guard = logger_ptr_c.lock().await; {
if guard.is_some() {
if guard.as_mut().unwrap().debug_error(&format!("Failed to parse stdout: {}", e)).is_err() {/* ignored */}
}
drop(guard);
};
break;
},
};
}

Expand Down
Loading

0 comments on commit fd31f08

Please sign in to comment.