refactored db

4-update-check
plazmoid 4 years ago
parent 1497af9c39
commit 0b667882f1
  1. 2
      .gitignore
  2. 3
      Cargo.toml
  3. 10
      bin/u_server/Cargo.toml
  4. 11
      bin/u_server/src/db.rs
  5. 6
      bin/u_server/src/db/mod.rs
  6. 17
      bin/u_server/src/handlers.rs
  7. 26
      bin/u_server/src/main.rs
  8. 17
      lib/u_db/Cargo.toml
  9. 2
      lib/u_db/diesel.toml
  10. 4
      lib/u_db/migrations/2020-10-24-111622_create_all/down.sql
  11. 0
      lib/u_db/migrations/2020-10-24-111622_create_all/up.sql
  12. 7
      lib/u_db/src/lib.rs
  13. 27
      lib/u_db/src/models/agent.rs
  14. 3
      lib/u_db/src/models/mod.rs
  15. 0
      lib/u_db/src/schema.rs
  16. 6
      lib/u_lib/Cargo.toml
  17. 4
      lib/u_lib/src/api.rs
  18. 76
      lib/u_lib/src/contracts/agent.rs
  19. 30
      lib/u_lib/src/contracts/messaging.rs
  20. 4
      lib/u_lib/src/contracts/mod.rs
  21. 2
      lib/u_lib/src/lib.rs

2
.gitignore vendored

@ -0,0 +1,2 @@
/target
**/*.rs.bk

@ -4,7 +4,8 @@ members = [
"bin/u_panel", "bin/u_panel",
"bin/u_run", "bin/u_run",
"bin/u_server", "bin/u_server",
"lib/u_lib" "lib/u_lib",
"lib/u_db"
] ]
[profile.release] [profile.release]

@ -12,13 +12,9 @@ anyhow = "*"
warp = "0.2.4" warp = "0.2.4"
[dependencies.diesel] [dependencies.diesel]
features = ["sqlite", "uuid"] features = ["sqlite"]
version = "1.4.5" version = "1.4.5"
[dependencies.uuid]
features = ["serde", "v4"]
version = "*"
[dependencies.serde] [dependencies.serde]
features = ["derive"] features = ["derive"]
version = "1.0.114" version = "1.0.114"
@ -30,3 +26,7 @@ version = "0.2.22"
[dependencies.u_lib] [dependencies.u_lib]
path = "../../lib/u_lib" path = "../../lib/u_lib"
version = "*" version = "*"
[dependencies.u_db]
path = "../../lib/u_db"
version = "*"

@ -10,9 +10,9 @@ use std::{
use crate::{ use crate::{
errors::USrvResult, errors::USrvResult,
db::IAgent db::*
}; };
use super::schema; use u_db::schema;
pub type Storage = Arc<Mutex<UDB>>; pub type Storage = Arc<Mutex<UDB>>;
@ -39,4 +39,11 @@ impl UDB {
.execute(&self.conn)?; .execute(&self.conn)?;
Ok(()) Ok(())
} }
pub fn get_agents(&self) -> USrvResult<Vec<QAgent>> {
use schema::agents;
let result = agents::table
.load::<QAgent>(&self.conn)?;
Ok(result)
}
} }

@ -1,6 +0,0 @@
pub mod db;
mod schema;
mod models;
pub use db::*;
pub use models::*;

@ -86,17 +86,22 @@ pub async fn set_jobs(
Ok(()) Ok(())
} }
*/
pub async fn ls(db: Storage) -> Result<impl Reply, Rejection> { pub async fn ls(db: Storage) -> Result<impl Reply, Rejection> {
let clients = db.clients().await; let result = db.lock().unwrap().get_agents();
/*
let mut result: Vec<Agent> = Vec::with_capacity(clients.len()); let mut result: Vec<Agent> = Vec::with_capacity(clients.len());
for cli in clients.values() { for cli in clients.values() {
result.push(cli.client_info.clone()); result.push(cli.client_info.clone());
} }
Ok(warp::reply::json( */
&ItemWrap(result).as_message() match result {
)) Ok(r) => Ok(warp::reply::json(
}*/ &ItemWrap(r).as_message()
)),
Err(e) => error!(e)
}
}
pub async fn dummy() -> Result<impl Reply, Rejection> { pub async fn dummy() -> Result<impl Reply, Rejection> {
Ok(String::from("ok")) Ok(String::from("ok"))

@ -8,11 +8,15 @@ use warp::{
Reply, Reply,
body body
}; };
#[macro_use]
extern crate log;
use env_logger; use env_logger;
use u_lib::{ use u_lib::{
MASTER_PORT, MASTER_PORT,
contracts::*, contracts::*,
network::Paths api::Paths
}; };
use db::*; use db::*;
use serde::{ use serde::{
@ -43,15 +47,15 @@ async fn main() {
let new_client = warp::post() let new_client = warp::post()
.and(warp::path(Paths::init)) .and(warp::path(Paths::init))
//.and(get_content::<IAgent>()) .and(get_content::<IAgent>())
//.and(db.clone()) .and(db.clone())
.and_then(handlers::dummy); .and_then(handlers::add_agent);
/*
let ls = warp::get()
.and(warp::path(Paths::ls))
.and(db.clone())
.and_then(handlers::ls);
let ls = warp::get()
.and(warp::path(Paths::ls))
.and(db.clone())
.and_then(handlers::ls);
/*
let get_jobs = warp::get() let get_jobs = warp::get()
.and(warp::path(Paths::get_jobs)) .and(warp::path(Paths::get_jobs))
.and(db.clone()) .and(db.clone())
@ -84,10 +88,10 @@ async fn main() {
; ;
let auth_zone = auth_token let auth_zone = auth_token
// .and(ls .and(ls
// .or(set_jobs) // .or(set_jobs)
// .or(get_job_results) // .or(get_job_results)
// ) )
; ;
let routes = auth_zone let routes = auth_zone

@ -0,0 +1,17 @@
[package]
name = "u_db"
version = "0.1.0"
authors = ["plazmoid <kronos44@mail.ru>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[dependencies.diesel]
features = ["sqlite"]
version = "1.4.5"
[dependencies.serde]
features = ["derive"]
version = "1.0.114"

@ -2,4 +2,4 @@
# see diesel.rs/guides/configuring-diesel-cli # see diesel.rs/guides/configuring-diesel-cli
[print_schema] [print_schema]
file = "src/db/schema.rs" file = "src/schema.rs"

@ -0,0 +1,4 @@
DROP TABLE agents;
DROP TABLE ip_addrs;
DROP TABLE jobs;
DROP TABLE results;

@ -0,0 +1,7 @@
#[macro_use]
extern crate diesel;
mod models;
pub mod schema;
pub use models::*;

@ -1,18 +1,18 @@
use serde::{
Serialize,
Deserialize
};
use diesel::{ use diesel::{
Insertable,
Queryable, Queryable,
Identifiable Identifiable,
}; Insertable
use serde::{
Deserialize,
Serialize
}; };
use u_lib::Uid; use crate::schema::*;
use std::time::SystemTime;
use crate::db::schema::*; type Uid = String;
//belongs_to //belongs_to
#[derive(Identifiable, Queryable, Serialize)] #[derive(Clone, Debug, Serialize, Deserialize, Identifiable, Queryable)]
#[table_name = "agents"] #[table_name = "agents"]
pub struct QAgent { pub struct QAgent {
pub alias: Option<String>, pub alias: Option<String>,
@ -21,17 +21,18 @@ pub struct QAgent {
pub id: i32, pub id: i32,
pub is_root: bool, pub is_root: bool,
pub is_root_allowed: bool, pub is_root_allowed: bool,
pub last_active: SystemTime, pub last_active: String,
pub platform: String, pub platform: String,
pub regtime: SystemTime, pub regtime: String,
pub status: Option<String>, pub status: Option<String>,
pub token: Option<String>, pub token: Option<String>,
pub username: String pub username: String
} }
#[derive(Insertable, Deserialize, Clone)] #[derive(Clone, Debug, Serialize, Deserialize, Insertable)]
#[table_name = "agents"] #[table_name = "agents"]
pub struct IAgent { pub struct IAgent {
pub alias: Option<String>,
pub agent_id: Uid, pub agent_id: Uid,
pub hostname: String, pub hostname: String,
pub is_root: bool, pub is_root: bool,

@ -0,0 +1,3 @@
mod agent;
pub use agent::*;

@ -15,4 +15,8 @@ lazy_static = "1.4.0"
tokio = { version = "0.2.22", features = ["macros", "process"] } tokio = { version = "0.2.22", features = ["macros", "process"] }
reqwest = { version = "0.10.7", features = ["json"] } reqwest = { version = "0.10.7", features = ["json"] }
futures = "0.3.5" futures = "0.3.5"
guess_host_triple = "0.1.2" guess_host_triple = "0.1.2"
[dependencies.u_db]
path = "../u_db"
version = "*"

@ -152,11 +152,11 @@ impl ClientHandler {
// method basic_path(json/query param; additional_url_param) -> return value // method basic_path(json/query param; additional_url_param) -> return value
// A - admin only // A - admin only
// client listing (A) // client listing (A)
// build_handler!(GET ls() -> Vec<QAgent>); build_handler!(GET ls() -> ItemWrap<Vec<QAgent>>);
// get jobs for client himself (A: id=client_id) // get jobs for client himself (A: id=client_id)
//build_handler!(GET get_jobs() -> JobMetaStorage); //build_handler!(GET get_jobs() -> JobMetaStorage);
// add client to server's db // add client to server's db
build_handler!(POST init(Agent) -> RawMsg); build_handler!(POST init(IAgent) -> RawMsg);
// ??? // ???
/*build_handler!(POST del() -> ()); /*build_handler!(POST del() -> ());
// set jobs for client (A) // set jobs for client (A)

@ -2,63 +2,43 @@ use std::{
collections::HashMap, collections::HashMap,
time::SystemTime time::SystemTime
}; };
use serde::{
Deserialize,
Serialize
};
use guess_host_triple::guess_host_triple;
use crate::{ use crate::{
contracts::*, contracts::*,
UID, UID,
Uid,
exec_job, exec_job,
utils::vec_to_string utils::vec_to_string
}; };
use u_db::IAgent;
#[derive(Clone, Debug, Serialize, Deserialize)] use guess_host_triple::guess_host_triple;
pub struct Agent {
pub agent_id: Uid,
pub hostname: String,
pub is_root: bool,
pub is_root_allowed: bool,
pub platform: String,
pub status: Option<String>,
pub token: Option<String>,
pub username: String
}
impl Agent {
pub async fn gather() -> Self {
async fn run_cmd_fast(cmd: String) -> String {
let job = exec_job(
JobMeta::from_shell_arc(cmd)
).await;
let job_result = match job.unwrap().data.unwrap() {
Ok(output) => output.multiline(),
Err(e) => e.to_string()
};
JobOutput::from_multiline(&job_result)
.map(|o| vec_to_string(&o.into_appropriate()))
.unwrap_or(job_result)
}
#[cfg(unix)] pub async fn gather() -> IAgent {
Agent {
agent_id: UID.clone().to_string(), async fn run_cmd_fast(cmd: String) -> String {
hostname: run_cmd_fast("hostname".to_string()).await, let job = exec_job(
is_root: &run_cmd_fast("id -u".to_string()).await == "0", JobMeta::from_shell_arc(cmd)
is_root_allowed: false, //TODO ).await;
platform: guess_host_triple().unwrap_or("Error").to_string(), let job_result = match job.unwrap().data.unwrap() {
status: None, //TODO Ok(output) => output.multiline(),
token: None, //TODO Err(e) => e.to_string()
username: run_cmd_fast("id -un".to_string()).await, };
} JobOutput::from_multiline(&job_result)
.map(|o| vec_to_string(&o.into_appropriate()))
.unwrap_or(job_result)
} }
#[cfg(unix)]
IAgent {
alias: None,
agent_id: UID.clone().to_string(),
hostname: run_cmd_fast("hostname".to_string()).await,
is_root: &run_cmd_fast("id -u".to_string()).await == "0",
is_root_allowed: false, //TODO
platform: guess_host_triple().unwrap_or("Error").to_string(),
status: None, //TODO
token: None, //TODO
username: run_cmd_fast("id -un".to_string()).await,
}
} }
@ -68,7 +48,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn test_gather() { async fn test_gather() {
let cli_info = Agent::gather().await; let cli_info = gather().await;
assert_eq!( assert_eq!(
&cli_info.username, &cli_info.username,
"root" "root"

@ -1,16 +1,15 @@
use uuid::Uuid; use uuid::Uuid;
use serde::{ use serde::{
Serialize, Serialize,
Deserialize Deserialize,
de::DeserializeOwned,
}; };
use std::{ use std::{
borrow::Cow borrow::Cow
}; };
use crate::{UID, Uid}; use crate::{UID, Uid};
pub trait ToMsg: Clone + Serialize + DeserializeOwned {
pub trait ToMsg
where Self: Clone {
fn as_message<'m>(&'m self) -> Message<'m, Self> fn as_message<'m>(&'m self) -> Message<'m, Self>
where Cow<'m, Self>: From<&'m Self> { where Cow<'m, Self>: From<&'m Self> {
Message::new(self) Message::new(self)
@ -19,13 +18,13 @@ where Self: Clone {
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Message<'cow, I> pub struct Message<'cow, I>
where I: Clone { where I: ToMsg {
pub id: Uid, pub id: Uid,
pub item: Cow<'cow, I> pub item: Cow<'cow, I>
} }
impl<'cow, I> Message<'cow, I> impl<'cow, I> Message<'cow, I>
where I: Clone where I: ToMsg
{ {
pub fn new<C>(item: C) -> Self pub fn new<C>(item: C) -> Self
where C: Into<Cow<'cow, I>> { where C: Into<Cow<'cow, I>> {
@ -44,31 +43,26 @@ impl<'cow, I> Message<'cow, I>
pub struct RawMsg(pub String); pub struct RawMsg(pub String);
// because can't impl From<ItemWrap<...>> for Cow // because can't impl From<Vec<...>> for Cow
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
struct ItemWrap<T>(T); pub struct ItemWrap<T: ToMsg>(pub T);
impl<T> ItemWrap<T> { impl<T: ToMsg> ItemWrap<T> {
pub fn into_inner(self) -> T { pub fn into_inner(self) -> T {
self.0 self.0
} }
} }
impl<T> From<T> for ItemWrap<T> { impl<T: ToMsg> ToMsg for ItemWrap<T> {}
fn from(t: T) -> Self { //impl<T: ToMsg> ToMsg for Vec<T> {}
ItemWrap(t)
}
}
impl<T: Clone> ToMsg for ItemWrap<T> {}
impl<'cow, T: Clone> From<ItemWrap<T>> for Cow<'cow, ItemWrap<T>> { impl<'cow, T: ToMsg> From<ItemWrap<T>> for Cow<'cow, ItemWrap<T>> {
fn from(obj: ItemWrap<T>) -> Cow<'cow, ItemWrap<T>> { fn from(obj: ItemWrap<T>) -> Cow<'cow, ItemWrap<T>> {
Cow::Owned(obj) Cow::Owned(obj)
} }
} }
impl<'cow, T: Clone> From<&'cow ItemWrap<T>> for Cow<'cow, ItemWrap<T>> { impl<'cow, T: ToMsg> From<&'cow ItemWrap<T>> for Cow<'cow, ItemWrap<T>> {
fn from(obj: &'cow ItemWrap<T>) -> Cow<'cow, ItemWrap<T>> { fn from(obj: &'cow ItemWrap<T>) -> Cow<'cow, ItemWrap<T>> {
Cow::Borrowed(obj) Cow::Borrowed(obj)
} }

@ -5,12 +5,12 @@ pub mod agent;
pub use { pub use {
messaging::*, messaging::*,
jobs::*, jobs::*,
agent::*
}; };
use std::{ use std::{
borrow::Cow borrow::Cow
}; };
use u_db::*;
macro_rules! to_message { macro_rules! to_message {
($($type:ty),+) => { $( ($($type:ty),+) => { $(
@ -33,4 +33,4 @@ macro_rules! to_message {
} }
} }
to_message!(Agent, RawMsg, JobMeta, JobResult); to_message!(IAgent, QAgent, RawMsg, JobMeta, JobResult);

@ -3,7 +3,7 @@ pub mod config;
pub mod utils; pub mod utils;
pub mod errors; pub mod errors;
pub mod contracts; pub mod contracts;
pub mod network; pub mod api;
pub use { pub use {
utils::*, utils::*,

Loading…
Cancel
Save