4-update-check
plazmoid 4 years ago
parent 4b6ce80790
commit b711eff13d
  1. 9
      bin/u-agent/src/main.rs
  2. 20
      bin/u-agent/src/network.rs
  3. 44
      bin/u-server/src/main.rs
  4. 1
      lib/u_lib/Cargo.toml
  5. 7
      lib/u_lib/src/config.rs
  6. 16
      lib/u_lib/src/contracts/client.rs
  7. 47
      lib/u_lib/src/contracts/messaging.rs
  8. 26
      lib/u_lib/src/contracts/mod.rs
  9. 3
      lib/u_lib/src/lib.rs

@ -8,26 +8,25 @@
// самоуничтожение // самоуничтожение
//mod jobs; //mod jobs;
use std::process::Command;
//use std::process::Command;
use std::thread::sleep; use std::thread::sleep;
use std::time::Duration; use std::time::Duration;
mod network; mod network;
use network::ClientHandler; use network::ClientHandler;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
//daemonize(); //daemonize();
let instance = ClientHandler::new(); let instance = ClientHandler::new();
instance.init().await; instance.init().await;
loop {
instance.list().await; instance.list().await;
/*loop {
sleep(Duration::from_secs(2)); sleep(Duration::from_secs(2));
/*Command::new("touch") /*Command::new("touch")
.arg("/tmp/win2") .arg("/tmp/win2")
.output() .output()
.unwrap();*/ .unwrap();*/
}*/ }
} }

@ -8,8 +8,6 @@ use reqwest::{
Url, Url,
Response Response
}; };
use uuid::Uuid;
use std::collections::HashMap;
pub struct ClientHandler { pub struct ClientHandler {
@ -24,10 +22,7 @@ impl ClientHandler {
client: Client::new(), client: Client::new(),
cli_info: ClientInfo::gather(), cli_info: ClientInfo::gather(),
base_url: Url::parse( base_url: Url::parse(
&format!("http://{}:{}", &format!("http://{}:{}", MASTER_SERVER, MASTER_PORT)
MASTER_SERVER,
MASTER_PORT
)
).unwrap() ).unwrap()
} }
} }
@ -35,10 +30,7 @@ impl ClientHandler {
pub async fn init(&self) { pub async fn init(&self) {
let response: Response = self.client let response: Response = self.client
.post(self.base_url.join("/new").unwrap()) .post(self.base_url.join("/new").unwrap())
.json(&Message::new( .json(&self.cli_info.as_message())
&self.cli_info.id,
self.cli_info.clone()
))
.send() .send()
.await .await
.unwrap(); .unwrap();
@ -47,7 +39,6 @@ impl ClientHandler {
response response
.json::<Message<RawMsg>>() .json::<Message<RawMsg>>()
.await .await
.unwrap()
); );
} }
@ -58,11 +49,12 @@ impl ClientHandler {
.await .await
.unwrap(); .unwrap();
let clients = response let clients = response
.json::<Message<CliStorage>>() .json::<Message<Vec<ClientInfo>>>()
.await .await
.unwrap(); .unwrap();
for cli in clients.item { println!("***********");
println!("{}: {:?}", cli.0, cli.1); for cli in clients.item.iter() {
println!("{:?}", cli);
} }
} }
} }

@ -2,13 +2,11 @@ use warp::{
Filter, Filter,
Rejection, Rejection,
Reply, Reply,
body, body
http::StatusCode
}; };
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::Arc, sync::Arc
marker::Send
}; };
use env_logger; use env_logger;
use tokio::sync::Mutex; use tokio::sync::Mutex;
@ -20,34 +18,28 @@ use u_lib::{
contracts::* contracts::*
}; };
use serde::Deserialize;
type SharedStorage = Arc<Mutex<CliStorage>>; type SharedStorage = Arc<Mutex<CliStorage>>;
fn get_content() fn get_content() -> impl Filter<
-> impl Filter<Extract = (Message<ClientInfo>,), Error = Rejection> + Clone { Extract = (Message<'static, ClientInfo>,),
Error = Rejection
> + Clone {
body::content_length_limit(1024*64).and(body::json::<Message<ClientInfo>>()) body::content_length_limit(1024*64).and(body::json::<Message<ClientInfo>>())
} }
async fn add_client(msg: Message<ClientInfo>, db: SharedStorage) -> async fn add_client(msg: Message<'_, ClientInfo>, db: SharedStorage) ->
Result<impl Reply, Rejection> { Result<impl Reply, Rejection> {
let new_cli = msg.item; let new_cli = msg.item;
let mut clients = db.lock().await; let mut clients = db.lock().await;
if clients.contains_key(&new_cli.id) { if clients.contains_key(&new_cli.id) {
Ok(warp::reply::json( Ok(warp::reply::json(
&Message::new( &RawMsg("Already exist".to_string()).into_message()
&new_cli.id,
&RawMsg("Already exist".to_string())
)
)) ))
} else { } else {
let id = new_cli.id.clone(); clients.insert(new_cli.id.clone(), new_cli.into_owned());
clients.insert(new_cli.id.clone(), new_cli);
Ok(warp::reply::json( Ok(warp::reply::json(
&Message::new( &RawMsg("Added".to_string()).into_message()
&id, )
&RawMsg("Added".to_string())
))
) )
} }
} }
@ -55,8 +47,12 @@ Result<impl Reply, Rejection> {
async fn listing(db: SharedStorage) -> async fn listing(db: SharedStorage) ->
Result<impl Reply, Rejection> { Result<impl Reply, Rejection> {
let clients = db.lock().await; let clients = db.lock().await;
let mut result: Vec<ClientInfo> = Vec::with_capacity(clients.len());
for cli in clients.values() {
result.push(cli.clone());
}
Ok(warp::reply::json( Ok(warp::reply::json(
&Message::new(&Uuid::nil(), clients) &Message::new_owned(result)
)) ))
} }
@ -69,9 +65,6 @@ async fn main() {
); );
let db = warp::any().map(move || Arc::clone(&base_db)); let db = warp::any().map(move || Arc::clone(&base_db));
let hello = warp::get().and(warp::path::param())
.map(|p: String| format!("Hello, {}", p));
let new_client = warp::post() let new_client = warp::post()
.and(warp::path("new")) .and(warp::path("new"))
.and(get_content()) .and(get_content())
@ -83,10 +76,9 @@ async fn main() {
.and(db.clone()) .and(db.clone())
.and_then(listing); .and_then(listing);
let routes = hello let routes = new_client
.or(new_client)
.or(ls) .or(ls)
.with(warp::log("warp")); .with(warp::log("warp"));
warp::serve(routes) warp::serve(routes)
.run((MASTER_SERVER.octets(), MASTER_PORT)).await; .run(([0,0,0,0], MASTER_PORT)).await;
} }

@ -11,3 +11,4 @@ serde = { version = "1.0.114", features = ["derive"] }
uuid = { version = "^0.8.1", features = ["serde", "v4"] } uuid = { version = "^0.8.1", features = ["serde", "v4"] }
nix = "0.17" nix = "0.17"
libc = "^0.2" libc = "^0.2"
lazy_static = "1.4.0"

@ -1,4 +1,9 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use uuid::Uuid;
pub const MASTER_SERVER: Ipv4Addr = Ipv4Addr::LOCALHOST; pub const MASTER_SERVER: Ipv4Addr = Ipv4Addr::new(3,9,16,40); //Ipv4Addr::LOCALHOST;
pub const MASTER_PORT: u16 = 63714; pub const MASTER_PORT: u16 = 63714;
lazy_static! {
pub static ref UID: Uuid = Uuid::new_v4();
}

@ -2,9 +2,18 @@ use serde::{
Deserialize, Deserialize,
Serialize Serialize
}; };
use std::{
collections::HashMap
};
use uuid::Uuid; use uuid::Uuid;
use super::{
ToMsg
};
use crate::UID;
pub type CliStorage = HashMap<Uuid, ClientInfo>;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientInfo { pub struct ClientInfo {
pub local_ip: String, pub local_ip: String,
pub hostname: String, pub hostname: String,
@ -19,11 +28,12 @@ impl ClientInfo {
ClientInfo { ClientInfo {
local_ip: String::from("1.2.3.4"), local_ip: String::from("1.2.3.4"),
hostname: String::from("polokonzerva"), hostname: String::from("polokonzerva"),
username: String::from("plazmoid (lol what a stupid name)"), username: String::from("plazmoid"),
os: String::from("pinux"), os: String::from("pinux"),
platform: String::from("x86_64"), platform: String::from("x86_64"),
id: Uuid::new_v4() id: *UID
} }
} }
} }
impl ToMsg for ClientInfo {}

@ -3,28 +3,51 @@ use serde::{
Serialize, Serialize,
Deserialize Deserialize
}; };
use super::ClientInfo; use std::{
use std::collections::HashMap; borrow::Cow
};
use crate::UID;
pub trait ToMsg
where Self: Clone {
fn as_message<'m>(&'m self) -> Message<'m, Self>
where Cow<'m, Self>: From<&'m Self> {
Message::new(self)
}
pub type CliStorage = HashMap<Uuid, ClientInfo>; fn into_message(self) -> Message<'static, Self> {
Message::new_owned(self)
}
}
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Message<I> { pub struct Message<'cow, I>
where I: Clone {
pub id: Uuid, pub id: Uuid,
pub item: I pub item: Cow<'cow, I>
} }
impl<I> Message<I> { impl<'cow, I> Message<'cow, I>
pub fn new(id: &Uuid, item: I) -> Self { where I: Clone {
pub fn new<C>(item: C) -> Self
where C: Into<Cow<'cow, I>> {
Self { Self {
id: id.clone(), id: *UID,
item item: item.into()
}
}
// crutch
// because Vec is stored as &[] (wtf?)
pub fn new_owned(item: I) -> Self {
Self {
id: *UID,
item: Cow::Owned(item)
} }
} }
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RawMsg(pub String); pub struct RawMsg(pub String);
#[derive(Serialize, Deserialize, Debug)] impl ToMsg for RawMsg {}
pub struct Empty;

@ -5,3 +5,29 @@ pub use {
client::*, client::*,
messaging::* messaging::*
}; };
use std::{
borrow::Cow
};
macro_rules! to_cow {
($type:ty) => {
impl<'cow> From<$type> for Cow<'cow, $type> {
#[inline]
fn from(obj: $type) -> Cow<'cow, $type> {
Cow::Owned(obj)
}
}
impl<'cow> From<&'cow $type> for Cow<'cow, $type> {
#[inline]
fn from(obj: &'cow $type) -> Cow<'cow, $type> {
Cow::Borrowed(obj)
}
}
}
}
to_cow!(ClientInfo);
to_cow!(RawMsg);

@ -4,3 +4,6 @@ pub mod utils;
pub use utils::*; pub use utils::*;
pub use config::*; pub use config::*;
#[macro_use]
extern crate lazy_static;

Loading…
Cancel
Save