Skip to content

Commit

Permalink
feat: Adding better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
sousandrei committed Sep 17, 2022
1 parent f43b693 commit 0230dd1
Show file tree
Hide file tree
Showing 10 changed files with 40 additions and 29 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ hyperlocal = "0.7"
serde = {version = "1.0.116", features = ["derive"]}
serde_json = "1.0.57"
tokio = {version = "0.2.22", features = ["full"]}
tracing = "0.1"
tracing-subscriber = "0.2"
5 changes: 3 additions & 2 deletions src/api/create.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use hyper::{Body, Request, Response, StatusCode};
use tracing::error;

use super::VmInput;
use crate::{vm, State};
Expand All @@ -9,7 +10,7 @@ pub async fn handler(req: Request<Body>, state: State) -> Result<Response<Body>,
let body: VmInput = match serde_json::from_slice(body_bytes) {
Ok(j) => j,
Err(e) => {
eprintln!("{}", e);
error!("{}", e);

let mut error = Response::default();
*error.status_mut() = StatusCode::BAD_REQUEST;
Expand All @@ -21,7 +22,7 @@ pub async fn handler(req: Request<Body>, state: State) -> Result<Response<Body>,
match vm::spawn(&body.vm_name, state).await {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e);
error!("{}", e);

let mut error = Response::default();
*error.status_mut() = StatusCode::BAD_REQUEST;
Expand Down
3 changes: 2 additions & 1 deletion src/api/delete.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use hyper::{Body, Request, Response, StatusCode};
use tracing::error;

use super::VmInput;
use crate::{vm, State};
Expand All @@ -9,7 +10,7 @@ pub async fn handler(req: Request<Body>, state: State) -> Result<Response<Body>,
let body: VmInput = match serde_json::from_slice(body_bytes) {
Ok(j) => j,
Err(e) => {
eprintln!("{}", e);
error!("{}", e);

let mut error = Response::default();
*error.status_mut() = StatusCode::BAD_REQUEST;
Expand Down
3 changes: 2 additions & 1 deletion src/api/kill.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use hyper::{Body, Request, Response, StatusCode};
use tracing::error;

use super::VmInput;
use crate::State;
Expand All @@ -9,7 +10,7 @@ pub async fn handler(req: Request<Body>, state: State) -> Result<Response<Body>,
let body: VmInput = match serde_json::from_slice(body_bytes) {
Ok(j) => j,
Err(e) => {
eprintln!("{}", e);
error!("{}", e);

let mut error = Response::default();
*error.status_mut() = StatusCode::BAD_REQUEST;
Expand Down
13 changes: 6 additions & 7 deletions src/io.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::PathBuf;
use tracing::{error, info, warn};

pub fn create_folder(path: PathBuf) -> Result<(), std::io::Error> {
validate_path(&path)?;

if let Ok(_) = check_exists(&path) {
println!("Path create successfully [{}]", path.display());
info!("Path create successfully [{}]", path.display());
fs::create_dir(path)?;
return Ok(());
}
Expand All @@ -20,12 +21,12 @@ pub fn create_folder(path: PathBuf) -> Result<(), std::io::Error> {

match fs::read_dir(&path) {
Ok(entries) => {
println!("Using folder [{}]", path.display());
info!("Using folder [{}]", path.display());
if entries.peekable().peek().is_some() {
println!("Warning: tmp dir not empty [{}]", path.display());
warn!("Warning: tmp dir not empty [{}]", path.display());
}
}
Err(e) => println!("Cannot read dir: {}", e),
Err(e) => error!("Cannot read dir [{}]", e),
};

Ok(())
Expand All @@ -38,9 +39,6 @@ pub fn copy_file(src: PathBuf, dest: PathBuf) -> Result<(), std::io::Error> {
validate_path(&dest)?;
check_exists(&dest)?;

println!("src: {:?}", src);
println!("dest: {:?}", dest);

match fs::copy(src, dest) {
Ok(_) => Ok(()),
Err(e) => Err(e),
Expand Down Expand Up @@ -87,6 +85,7 @@ fn check_exists(path: &PathBuf) -> Result<(), std::io::Error> {
Ok(())
}

//TODO: figure out testing
// #[cfg(test)]
// mod test {
// #[test]
Expand Down
10 changes: 9 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use clap::{load_yaml, App};
use hyper::service::{make_service_fn, service_fn};
use hyper::Server;
use serde::{Deserialize, Serialize};
use std::env;
use std::sync::{Arc, Mutex};
use tracing::info;

mod api;
mod error;
Expand Down Expand Up @@ -38,6 +40,12 @@ impl Clone for State {

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if let Err(_) = env::var("RUST_LOG") {
env::set_var("RUST_LOG", "info");
}

tracing_subscriber::fmt::init();

let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();

Expand Down Expand Up @@ -68,7 +76,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

let server = Server::bind(&addr).serve(service);

println!("Listening on http://{}", addr);
info!("Listening on http://{}", addr);

server.await?;

Expand Down
4 changes: 3 additions & 1 deletion src/tmp.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::io::ErrorKind;
use std::path::PathBuf;
use tracing::error;

use crate::io;

//TODO: better error handling
pub fn init(path: &str) -> Result<(), std::io::Error> {
let path = PathBuf::from(path);

Expand All @@ -11,7 +13,7 @@ pub fn init(path: &str) -> Result<(), std::io::Error> {
Err(e) => match e.kind() {
ErrorKind::AlreadyExists => Ok(()),
_ => {
println!("{:?}", e.kind());
error!("{:?}", e.kind());
Err(e)
}
},
Expand Down
18 changes: 5 additions & 13 deletions src/vm/child.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::process::Stdio;
use tokio::process::Command;
use tokio::time::{delay_for, Duration};
use tracing::info;

use crate::error::RuntimeError;
use crate::vm::http;
Expand All @@ -22,13 +23,8 @@ pub async fn spawn_process(
delay_for(Duration::from_millis(10)).await;

set_kernel(vm_name, &state.assets_dir).await?;
println!("kernel");

set_drive(vm_name, &state.tmp_dir).await?;
println!("drive");

start_machine(vm_name).await?;
println!("start");

Ok(child)
}
Expand All @@ -41,8 +37,7 @@ pub async fn set_kernel(vm_name: &str, assets_dir: &str) -> Result<(), RuntimeEr
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
});

println!("{}", url);
println!("{}", body);
info!("Set Kernel [{}]", vm_name);

http::send_request(vm_name, url, &body.to_string()).await
}
Expand All @@ -57,8 +52,7 @@ pub async fn set_drive(vm_name: &str, tmp_dir: &str) -> Result<(), RuntimeError>
"is_read_only": false
});

println!("{}", url);
println!("{}", body);
info!("Set Drive [{}]", vm_name);

http::send_request(vm_name, url, &body.to_string()).await
}
Expand All @@ -69,8 +63,7 @@ pub async fn start_machine(vm_name: &str) -> Result<(), RuntimeError> {
"action_type": "InstanceStart",
});

println!("{}", url);
println!("{}", body);
info!("Starting [{}]", vm_name);

http::send_request(vm_name, url, &body.to_string()).await
}
Expand All @@ -81,8 +74,7 @@ pub async fn stop_machine(vm_name: &str) -> Result<(), RuntimeError> {
"action_type": "SendCtrlAltDel",
});

println!("{}", url);
println!("{}", body);
info!("Stopping [{}]", vm_name);

http::send_request(vm_name, url, &body.to_string()).await
}
3 changes: 2 additions & 1 deletion src/vm/http.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use hyper::{Body, Client, Method, Request};
use hyperlocal::{UnixClientExt, Uri};
use std::path::Path;
use tracing::info;

use crate::error::RuntimeError;

Expand Down Expand Up @@ -28,7 +29,7 @@ pub async fn send_request(vm_name: &str, url: &str, body: &str) -> Result<(), Ru
Err(_) => return Err(RuntimeError::new("error getting response")),
};

println!("Response: {}", res.status());
info!("{} {}", path.display(), res.status());

Ok(())
}
8 changes: 6 additions & 2 deletions src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod http;
mod socket;

use tokio::task;
use tracing::{error, info};

use crate::error::RuntimeError;
use crate::State;
Expand Down Expand Up @@ -41,7 +42,10 @@ pub async fn spawn(name: &str, state: State) -> Result<(), RuntimeError> {
}

if let Err(_) = child.await {
println!("ok")
error!(
"Failed to start machine, proceeding to teardown [{}]",
&name
);
};

drive::delete_drive(&name, &state.tmp_dir).unwrap();
Expand All @@ -52,7 +56,7 @@ pub async fn spawn(name: &str, state: State) -> Result<(), RuntimeError> {
index => vms.remove(index),
};

println!("{} terminated", name);
info!("Terminated [{}]", name);
});

Ok(())
Expand Down

0 comments on commit 0230dd1

Please sign in to comment.