Created
December 30, 2017 17:30
-
-
Save amiceli/18c914c153e22547351e77e75f8255b8 to your computer and use it in GitHub Desktop.
docker-stat-example-rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate regex; | |
extern crate serde; | |
extern crate serde_json; | |
extern crate tiny_http; | |
#[macro_use] | |
extern crate serde_derive; | |
use serde_json::Error; | |
use std::process::Command; | |
use regex::Regex; | |
use std::collections::HashMap; | |
#[derive(Serialize, Deserialize)] | |
struct DockerStat { | |
container: String, | |
cpu: String, | |
memory: HashMap<String, String>, | |
} | |
fn main() { | |
use tiny_http::{Server, Response}; | |
let server = Server::http("0.0.0.0:8000").unwrap(); | |
for request in server.incoming_requests() { | |
let response = Response::from_string("hello world"); | |
request.respond(response); | |
} | |
} | |
fn docker_stats() { | |
let output = get_docker_stats(); | |
parse_docker_state(output); | |
} | |
// get docker stats as json formatted string | |
fn get_docker_stats() -> String { | |
let output = | |
Command::new("sh") | |
.arg("scripts/docker-stats.sh") | |
.output() | |
.expect("Failed to get docker stats"); | |
let stdout = output.stdout; | |
let s = match String::from_utf8(stdout) { | |
Ok(v) => v, | |
Err(e) => panic!("Invalid UTF-8 sequence: {}", e), | |
}; | |
return s; | |
} | |
// Parse json docker stats into Structure List | |
fn parse_docker_state (docker_state_as_str: String) -> String { | |
let list = Vec(DockerStat); | |
for line in docker_state_as_str.split('\n') { | |
let json = replace_multiple_whitespace(line); | |
let res = output_to_struct(json); | |
let stat = res.ok(); | |
match stat { | |
None => println!("ok"), | |
Some(docker_stat) => { | |
println!("{}", docker_stat.container) | |
} | |
} | |
} | |
return String::from(""); | |
} | |
// docker stats json line to DockerStat structure | |
fn output_to_struct(line:String) -> Result<DockerStat, Error> { | |
let docker_stat: DockerStat = serde_json::from_str(&line)?; | |
Ok(docker_stat) | |
} | |
// remove multiple whitespace in string | |
fn replace_multiple_whitespace (before : &str) -> String { | |
let re = Regex::new(r" +").unwrap(); | |
let after = re.replace_all(before, " "); | |
return after.to_string(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment