test worken fuck me

4-update-check
plazmoid 4 years ago
parent 0908660fc9
commit 50d6d9412b
  1. 2
      lib/u_lib/src/client/client.rs
  2. 142
      lib/u_lib/src/contracts/jobs.rs
  3. 23
      lib/u_lib/src/executor.rs
  4. 2
      lib/u_lib/src/lib.rs
  5. 4
      lib/u_lib/src/utils.rs

@ -11,7 +11,7 @@ use crate::{
pub struct UClient { pub struct UClient {
pub client_info: ClientInfo, pub client_info: ClientInfo,
pub jobs: JobPool, // TODO: to futures pub jobs: Vec<JobMeta>, // TODO: to futures
} }
impl UClient { impl UClient {

@ -1,39 +1,65 @@
use std::{ use std::{
process::Command, process::Command,
time::SystemTime time::SystemTime,
cmp::PartialEq
};
use serde::{
Serialize,
Deserialize
}; };
use uuid::Uuid; use uuid::Uuid;
//use tokio::process::Command; //use tokio::process::Command;
use super::*; use super::*;
pub type JobPool = Vec<ShellJob>;
pub type JobResult = Result<Vec<u8>, Vec<u8>>;
pub struct ShellJob { pub struct Job<'meta> {
pub result: JobResult, pub result: JobResult,
pub cmd: String, pub meta: &'meta mut JobMeta,
pub args: Vec<String>
} }
impl ShellJob { impl<'meta> Job<'meta> {
pub fn from_raw(raw_cmd: String) -> Self { pub fn new(job_meta: &'meta mut JobMeta) -> Self {
let mut cmd_parts = raw_cmd
.split(" ")
.map(String::from)
.collect::<Vec<String>>();
let args: Vec<_> = cmd_parts.drain(1..).collect();
Self { Self {
cmd: cmd_parts.into_iter().nth(1).unwrap(), result: JobResult {
args, id: job_meta.id.clone(),
result: Err(b"Did not run".to_vec()) state: job_meta.state.clone(),
data: None,
},
meta: job_meta,
}
}
pub fn run(&mut self) {
match self.meta.exec_type {
JobType::Shell => {
match self.meta.state {
JobState::Queued | JobState::Pending => {
self.meta.state = JobState::Running;
},
JobState::Finished => {
if self.meta.schedule == JobSchedule::Permanent {
self.meta.state = JobState::Running;
} else {
return
} }
},
JobState::Running => return
} }
fn run(&mut self) { match &self.meta.payload {
let result = Command::new(&self.cmd) Some(box_payload) => {
.args(&self.args) let payload = String::from_utf8_lossy(box_payload).into_owned();
let mut cmd_parts = payload
.split(" ")
.map(String::from)
.collect::<Vec<String>>()
.into_iter();
let cmd = cmd_parts.nth(0).unwrap();
let args = cmd_parts.collect::<Vec<_>>();
let result = Command::new(cmd)
.args(args)
.output(); .output();
self.result = match result { self.result.data = Some(match result {
Ok(output) => { Ok(output) => {
if output.status.success() { if output.status.success() {
Ok(output.stdout.to_vec()) Ok(output.stdout.to_vec())
@ -42,14 +68,22 @@ impl ShellJob {
} }
} }
Err(e) => Err(e.to_string().into_bytes()) Err(e) => Err(e.to_string().into_bytes())
})
}
None => return
}
self.meta.state = JobState::Finished;
},
_ => unimplemented!()
} }
} }
fn get_result(&self) -> &JobResult { fn into_result(self) -> JobResult {
&self.result self.result
} }
} }
#[derive(Serialize, Deserialize, Clone)]
pub enum ManageAction { pub enum ManageAction {
Ping, Ping,
UpdateAvailable, UpdateAvailable,
@ -57,21 +91,24 @@ pub enum ManageAction {
Terminate Terminate
} }
#[derive(Serialize, Deserialize, Clone, PartialEq)]
pub enum JobSchedule { pub enum JobSchedule {
Once, Once,
Permanent, Permanent,
Terminate // to terminate jobs obvsl
//TODO: Scheduled //TODO: Scheduled
} }
#[derive(Serialize, Deserialize, Clone)]
pub enum JobState { pub enum JobState {
Dummy,
Queued, // server created a job, but client didn't get it yet Queued, // server created a job, but client didn't get it yet
Pending, // client got a job, but not running yet Pending, // client got a job, but not running yet
Running, // client is currently running a job Running, // client is currently running a job
Rerunning, // if job is cycled // Rerunning, // if job is cycled
Finished, Finished,
} }
#[derive(Serialize, Deserialize, Clone)]
pub enum JobType { pub enum JobType {
Manage(ManageAction), Manage(ManageAction),
Shell, Shell,
@ -79,33 +116,64 @@ pub enum JobType {
Binary Binary
} }
#[derive(Serialize, Deserialize, Clone)]
pub struct JobMeta { pub struct JobMeta {
id: Uuid, pub id: Uuid,
name: String, pub name: String,
created: SystemTime, pub created: SystemTime,
updated: SystemTime, pub updated: SystemTime,
state: JobState, pub state: JobState,
exec_type: JobType, pub exec_type: JobType,
append_result: bool, //true: append, false: rewrite pub schedule: JobSchedule,
payload: Option<Vec<u8>>, pub append_result: bool, //true: append, false: rewrite
pub payload: Option<Box<Vec<u8>>>,
} }
impl JobMeta { impl JobMeta {
pub fn from_shell(shell_cmd: Vec<u8>) -> Self { pub fn from_shell(shell_cmd: Vec<u8>) -> Self {
let uid = Uuid::new_v4(); let uid = Uuid::new_v4();
let str_payload_name = shell_cmd.split(b" ").collect(); //let str_payload_name: &[u8] = shell_cmd.split(|b| &[*b] == b" ").collect();
let job_name = format!("{} {}", uid.to_string()[..6], str_payload_name[0]); //let job_name = format!("{} {}", uid.to_string()[..6], str_payload_name[0]);
Self { Self {
id: uid, id: uid.clone(),
name: job_name, name: uid.to_string(),
created: SystemTime::now(), created: SystemTime::now(),
updated: SystemTime::now(), updated: SystemTime::now(),
state: JobState::Pending, state: JobState::Pending,
exec_type: JobType::Shell, exec_type: JobType::Shell,
schedule: JobSchedule::Once,
append_result: true, append_result: true,
payload: Some(shell_cmd) payload: Some(Box::new(shell_cmd))
} }
} }
pub fn from_shell_str(shell_cmd: String) -> Self {
Self::from_shell(shell_cmd.into_bytes())
}
} }
impl ToMsg for JobMeta {} impl ToMsg for JobMeta {}
#[derive(Serialize, Deserialize, Clone)]
pub struct JobResult {
id: Uuid,
data: Option<Result<Vec<u8>, Vec<u8>>>,
state: JobState
}
impl ToMsg for JobResult {}
#[cfg(test)]
mod tests {
use super::*;
use crate::execute_jobs;
#[test]
fn test_shell_job() {
let mut job = JobMeta::from_shell_str("whoami".into());
let mut jobs: Vec<Job> = vec![Job::new(&mut job)];
execute_jobs(&mut jobs);
assert_eq!(jobs.pop().unwrap().result.data.unwrap().unwrap(), b"plazmoid\n".to_vec());
}
}

@ -0,0 +1,23 @@
// list of jobs: job (cmd, args) OR rust fn OR python func + cron-like timing
// job runner (thread)
// every job runs in other thread/process
/*
use cron::Schedule as CronSchedule;
enum Schedule {
Persistent, // run forever, restart if stops (set max_retries)
Cron(CronSchedule),
Once
}
lazy_static! {
pub static ref EXECUTOR: Vec<>
}
*/
use crate::contracts::*;
pub fn execute_jobs(jobs: &mut Vec<Job>) {
jobs.iter_mut().for_each(|job| job.run())
}

@ -1,3 +1,4 @@
pub mod executor;
pub mod config; pub mod config;
pub mod contracts; pub mod contracts;
pub mod utils; pub mod utils;
@ -6,6 +7,7 @@ pub mod client;
pub use { pub use {
utils::*, utils::*,
config::*, config::*,
executor::*
}; };
#[macro_use] #[macro_use]

@ -45,3 +45,7 @@ pub fn setsig(sig: Signal, hnd: SigHandler) {
signal(sig, hnd).unwrap(); signal(sig, hnd).unwrap();
} }
} }
/*
pub fn generate_auth_token() -> String {
}*/
Loading…
Cancel
Save