Commit 3c1cc14b authored by Heinz N. Gies's avatar Heinz N. Gies

Improve logging

parent 3a86ae52
......@@ -9,6 +9,7 @@ dependencies = [
"serde_json 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"slog 2.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
"slog-async 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"slog-scope 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"slog-term 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"uuid 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
......@@ -94,6 +95,11 @@ dependencies = [
"unicode-normalization 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "crossbeam"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "dtoa"
version = "0.4.1"
......@@ -261,6 +267,16 @@ dependencies = [
"thread_local 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "slog-scope"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"slog 2.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "slog-term"
version = "2.0.1"
......@@ -428,6 +444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum clap 2.24.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6b8f69e518f967224e628896b54e41ff6acfb4dcfefc5076325c36525dac900f"
"checksum clippy 0.0.140 (registry+https://github.com/rust-lang/crates.io-index)" = "c94943cf8c69a405dd21a0f2ce2311f1c8777a9e54422baaae2397b688d26c89"
"checksum clippy_lints 0.0.140 (registry+https://github.com/rust-lang/crates.io-index)" = "116a24807a7704264f3bfcfcdc23a6d5196c2b37483281aa70c8e08c23a1b7d3"
"checksum crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0c5ea215664ca264da8a9d9c3be80d2eaf30923c259d03e870388eb927508f97"
"checksum dtoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "80c8b71fd71146990a9742fc06dcbbde19161a267e0ad4e572c35162f4578c90"
"checksum isatty 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "fa500db770a99afe2a0f2229be2a3d09c7ed9d7e4e8440bf71253141994e240f"
"checksum itoa 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eb2f404fbc66fd9aac13e998248505e7ecb2ad8e44ab6388684c5fb11c6c251c"
......@@ -452,6 +469,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum serde_json 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "48b04779552e92037212c3615370f6bd57a40ebba7f20e554ff9f55e41a69a7b"
"checksum slog 2.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "057f354e538bfb65380f06810d2ab85933872563b20f53daa8144e5beae3aa3b"
"checksum slog-async 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "afbebab3918ccc36e83dca6879dbe554fc2874d1c26e3dd5debf646a5ee60936"
"checksum slog-scope 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3b719bbab7e785c9bc2790be278822e7e8d60fbe4592954774b7b41449f7524c"
"checksum slog-term 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e98b9b40c26b62acbc114bc24feb3eb080dc6c8bc78461935474ded369a3a2ee"
"checksum strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d15c810519a91cf877e7e36e63fe068815c678181439f2f29e2562147c3694"
"checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad"
......
......@@ -4,16 +4,17 @@ version = "0.1.0"
authors = ["Heinz N. Gies <heinz@project-fifo.net>"]
[dependencies]
serde = "1.0.8"
serde_json = "1.0.2"
serde_derive = "1.0.8"
serde = "1"
serde_json = "1"
serde_derive = "1"
uuid = { version = "0.5", features = ["serde", "v4"] }
toml = "0.4"
clippy = {version = "*", optional = true}
slog = "2.0.6"
slog-term = "2.0.1"
slog-async = "2.0.1"
clippy = { version = "*", optional = true }
slog = "2"
slog-term = "2"
slog-async = "2"
slog-scope = "2"
[dependencies.clap]
version = "2.24.2"
version = "2"
features = ["yaml"]
\ No newline at end of file
......@@ -17,8 +17,7 @@ pub struct Settings {
#[derive(Debug)]
pub struct Config {
pub settings: Settings,
pub logger: slog::Logger
pub settings: Settings
}
fn default_conf_dir() -> String {
......@@ -26,14 +25,15 @@ fn default_conf_dir() -> String {
}
impl Config {
pub fn new(logger: slog::Logger) -> Result<Self, Box<Error>> {
pub fn new() -> Result<Self, Box<Error>> {
debug!("Loading config file"; "config" => CONFIG);
let mut file = File::open(CONFIG)?;
let mut contents = String::new();
file.read_to_string(&mut contents).expect(
"Failed to read config file.",
);
let settings: Settings = toml::from_str(contents.as_str())?;
Ok(Config{settings: settings, logger: logger})
Ok(Config{settings: settings})
}
// add code here
}
\ No newline at end of file
......@@ -80,15 +80,18 @@ impl<'a> JDB<'a> {
pub fn open(config: &'a Config) -> Result<Self, Box<Error>> {
let mut idx_file = PathBuf::from(config.settings.conf_dir.as_str());
idx_file.push("index");
debug!("Opening jdb"; "index" => idx_file.to_string_lossy().as_ref());
match File::open(idx_file) {
Ok(file) => {
let index: Index = serde_json::from_reader(file)?;
debug!("Found {} entries", index.entries.len());
Ok(JDB {
index: index,
config: config,
})
}
Err(_) => {
warn!("No database found creating new one.");
let entries: Vec<IdxEntry> = Vec::new();
let index: Index = Index {
version: 0,
......@@ -109,6 +112,7 @@ impl<'a> JDB<'a> {
/// Inserts a config into the database, writes the config file
/// and adds it to the index.
pub fn insert(self: &'a mut JDB<'a>, config: JailConfig) -> Result<IdxEntry, Box<Error>> {
debug!("Inserting new vm"; "vm" => &config.uuid);
match self.find(&config.uuid) {
None => {
let mut path = PathBuf::from(self.config.settings.conf_dir.as_str());
......@@ -137,13 +141,17 @@ impl<'a> JDB<'a> {
root: root.clone(),
})
}
Some(_) => Err(ConflictError::bx(config.uuid.as_str())),
Some(_) => {
warn!("Doublicate entry {}", config.uuid);
Err(ConflictError::bx(config.uuid.as_str()))
}
}
}
/// Removes a jail with a given uuid from the index and removes it's
/// config file.
pub fn remove(self: &'a mut JDB<'a>, uuid: &str) -> Result<usize, Box<Error>> {
debug!("Removing vm"; "vm" => uuid);
match self.find(uuid) {
None => Err(NotFoundError::bx(uuid)),
Some(index) => {
......@@ -177,6 +185,7 @@ impl<'a> JDB<'a> {
/// Reads the config file for a given entry
fn config(self: &'a JDB<'a>, entry: &IdxEntry) -> Result<JailConfig, Box<Error>> {
debug!("Loading vm config"; "vm" => &entry.uuid);
let mut config_path = PathBuf::from(self.config.settings.conf_dir.as_str());
config_path.push(entry.uuid.clone());
config_path.set_extension("json");
......@@ -186,6 +195,7 @@ impl<'a> JDB<'a> {
}
/// Saves the database
fn save(self: &'a JDB<'a>) -> Result<usize, Box<Error>> {
debug!("Saving database");
let mut path = PathBuf::from(self.config.settings.conf_dir.as_str());
path.push("index");
let file = File::create(path)?;
......
......@@ -21,9 +21,12 @@ extern crate toml;
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate slog_scope;
use slog::Drain;
use std::result;
use std::error::Error;
use std::io;
......@@ -38,6 +41,41 @@ use config::Config;
pub mod errors;
use errors::{GenericError, NotFoundError};
/// Custom Drain logic
struct RuntimeLevelFilter<D> {
drain: D,
level: u64
}
impl<D> Drain for RuntimeLevelFilter<D>
where
D: Drain,
{
type Ok = Option<D::Ok>;
type Err = Option<D::Err>;
fn log(
&self,
record: &slog::Record,
values: &slog::OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let current_level = match self.level {
1 => slog::Level::Critical,
2 => slog::Level::Error,
3 => slog::Level::Warning,
4 => slog::Level::Info,
5 => slog::Level::Debug,
6 => slog::Level::Trace,
_ => return Ok(None),
};
if record.level().is_at_least(current_level) {
self.drain.log(record, values).map(Some).map_err(Some)
} else {
Ok(None)
}
}
}
fn main() {
use clap::App;
let yaml = load_yaml!("cli.yml");
......@@ -47,11 +85,15 @@ fn main() {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let drain = RuntimeLevelFilter {
drain: drain,
level: matches.occurrences_of("v"),
}.fuse();
let root = slog::Logger::root(drain, o!());
let _guard = slog_scope::set_global_logger(root);
let config: Config = Config::new(root).unwrap();
let config: Config = Config::new().unwrap();
let r = if matches.is_present("startup") {
match matches.subcommand() {
("", None) => startup(&config),
......@@ -72,12 +114,12 @@ fn main() {
_ => unreachable!(),
}
};
crit!("Execution done");
match r {
Ok(0) => (),
Ok(exit_code) => std::process::exit(exit_code),
Err(e) => {
crit!(config.logger, "error: {}", e);
println!("error: {}", e);
crit!("error: {}", e);
std::process::exit(1)
}
}
......@@ -119,19 +161,20 @@ fn create(conf: &Config, _matches: &clap::ArgMatches) -> Result<i32, Box<Error>>
fn destroy(conf: &Config, matches: &clap::ArgMatches) -> Result<i32, Box<Error>> {
let mut db = JDB::open(conf)?;
let uuid = value_t!(matches, "uuid", String).unwrap();
debug!("Destroying jail {}", uuid);
match db.get(uuid.as_str()) {
Some(entry) => {
let origin = zfs::origin(entry.root.as_str());
match zfs::destroy(entry.root.as_str()) {
Ok(_) => debug!(conf.logger, "zfs dataset deleted: {}", entry.root),
Err(e) => warn!(conf.logger, "failed to delete dataset: {}", e),
Ok(_) => debug!("zfs dataset deleted: {}", entry.root),
Err(e) => warn!("failed to delete dataset: {}", e),
};
match origin {
Ok(origin) => {
zfs::destroy(origin.as_str())?;
debug!(conf.logger, "zfs snapshot deleted: {}", origin)
},
Err(e) => warn!(conf.logger, "failed to delete origin: {}", e),
debug!("zfs snapshot deleted: {}", origin)
}
Err(e) => warn!("failed to delete origin: {}", e),
}
}
None => return Err(NotFoundError::bx("Could not find VM")),
......
......@@ -16,6 +16,7 @@ pub struct ZFSEntry {
/// reads the zfs datasets in a pool
pub fn list(pool: &str) -> Result<Vec<ZFSEntry>, Box<Error>> {
debug!("Listing ZFS datasets"; "pool" => pool);
let output = Command::new("zfs")
.args(&["list", "-p", "-H", "-r", "-d1", pool])
.output()
......@@ -33,6 +34,7 @@ pub fn list(pool: &str) -> Result<Vec<ZFSEntry>, Box<Error>> {
/// reads the zfs datasets in a pool
pub fn get(dataset: &str) -> Result<ZFSEntry, Box<Error>> {
debug!("Reading ZFS dataset"; "dataset" => dataset);
let output = Command::new("zfs")
.args(&["list", "-p", "-H", dataset])
.output()
......@@ -47,6 +49,7 @@ pub fn get(dataset: &str) -> Result<ZFSEntry, Box<Error>> {
/// reads the zfs datasets in a pool
pub fn origin(dataset: &str) -> Result<String, Box<Error>> {
debug!("Fetching ZFS origin"; "dataset" => dataset);
let output = Command::new("zfs")
.args(&["get", "-p", "-H", "origin", dataset])
.output()
......@@ -67,6 +70,7 @@ pub fn origin(dataset: &str) -> Result<String, Box<Error>> {
}
/// create a zfs datasets in a pool
pub fn create(dataset: &str) -> Result<i32, Box<Error>> {
debug!("Creating ZFS dataset"; "dataset" => dataset);
let output = Command::new("zfs")
.args(&["create", dataset])
.output()
......@@ -83,6 +87,7 @@ pub fn snapshot(dataset: &str, snapshot: &str) -> Result<String, Box<Error>> {
let mut snap = String::from(dataset);
snap.push('@');
snap.push_str(snapshot);
debug!("Creating ZFS snapshot"; "snapshot" => snap.as_str());
let output = Command::new("zfs")
.args(&["snapshot", snap.as_str()])
.output()
......@@ -96,6 +101,7 @@ pub fn snapshot(dataset: &str, snapshot: &str) -> Result<String, Box<Error>> {
/// clones a zfs snapshot
pub fn clone(snapshot: &str, dataset: &str) -> Result<i32, Box<Error>> {
debug!("Cloning ZFS snapshot"; "snapshot" => snapshot, "dataset" => dataset);
let output = Command::new("zfs")
.args(&["clone", snapshot, dataset])
.output()
......@@ -108,6 +114,7 @@ pub fn clone(snapshot: &str, dataset: &str) -> Result<i32, Box<Error>> {
}
/// destroy the zfs datasets in a pool
pub fn destroy(dataset: &str) -> Result<i32, Box<Error>> {
debug!("Destroying ZFS dataset"; "dataset" => dataset);
let output = Command::new("zfs")
.args(&["destroy", dataset])
.output()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment