Skip to content

Commit

Permalink
separate code into lib and binary
Browse files Browse the repository at this point in the history
  • Loading branch information
sysx23 committed Jan 17, 2021
1 parent 8601d73 commit b3e9bc5
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 130 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2018"


[dependencies]
rsloglib = {path = "rsloglib"}
redis = "0.19.0"
log = "0.4.11"
stderrlog = "0.5"
Expand Down
11 changes: 11 additions & 0 deletions rsloglib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "rsloglib"
version = "0.1.0"
authors = ["Rostyslav Ivanika <Rostyslav.Ivanika@gmail.com>"]
edition = "2018"


[dependencies]
redis = "0.19.0"
log = "0.4.11"
serde = {version="1", features=["derive"]}
5 changes: 5 additions & 0 deletions rsloglib/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod slowlog;
mod slowlog_reader;

pub use slowlog::*;
pub use slowlog_reader::*;
4 changes: 2 additions & 2 deletions src/slowlog.rs → rsloglib/src/slowlog.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

use serde::Serialize;
use serde::{Serialize, Deserialize};

#[derive(Debug, Default, PartialEq, Serialize)]
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SlowlogRecord {
pub id: u64,
pub time: u64,
Expand Down
30 changes: 26 additions & 4 deletions src/slowlog_reader.rs → rsloglib/src/slowlog_reader.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
use crate::slowlog::SlowlogRecord;
use crate::ConnectionProvider;
use std::time::Duration;

#[derive(Clone)]
pub struct RedisConnectionProvider {
client: redis::Client,
timeout: u64,
}

impl From<(redis::Client, u64)> for RedisConnectionProvider {
fn from(arg: (redis::Client, u64)) -> RedisConnectionProvider {
RedisConnectionProvider {
client: arg.0,
timeout: arg.1,
}
}
}

impl RedisConnectionProvider {
pub fn get_connection(&self) -> redis::RedisResult<redis::Connection> {
self.client
.get_connection_with_timeout(Duration::from_secs(self.timeout))
}
}

pub struct SlowlogReader {
connection_provider: ConnectionProvider,
connection_provider: RedisConnectionProvider,
connection: redis::Connection,
last_id: i64,
length: u32,
uptime: u64,
}

impl std::convert::TryFrom<ConnectionProvider> for SlowlogReader {
impl std::convert::TryFrom<RedisConnectionProvider> for SlowlogReader {
type Error = redis::RedisError;
fn try_from(connection_provider: ConnectionProvider) -> Result<Self, Self::Error> {
fn try_from(connection_provider: RedisConnectionProvider) -> Result<Self, Self::Error> {
let sl_reader = SlowlogReader {
connection: connection_provider.get_connection()?,
connection_provider,
Expand Down
121 changes: 0 additions & 121 deletions src/lib.rs

This file was deleted.

101 changes: 98 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,99 @@
use std::thread::sleep;
use std::time::Duration;
use std::convert::TryFrom;

fn main(){
rslog::main();
}
mod argument_parsing;
use argument_parsing::OutputFormat;

use rsloglib::{SlowlogRecord,SlowlogReader, RedisConnectionProvider};


fn print_rec(r: &SlowlogRecord, format: &OutputFormat) {
match format {
OutputFormat::Text => {
println!(
"[{}] id: {},\tduration: {},\tclient: {},\tclient_name: {},\tcommand: {:?}",
r.time, r.id, r.duration, r.client_socket, r.client_name, r.command
)
}
OutputFormat::Json => {
println!("{}", serde_json::to_string(r).unwrap())
}
}
}

fn error_handler(e: redis::RedisError) {
match e.kind() {
redis::ErrorKind::IoError => {
log::error!("Can't establish connection to redis cluster: {}", e)
}
_ => unimplemented!("Error not handled: {}({:?})", e, e.kind()),
}
}

fn create_slowlog_reader(con_provider: RedisConnectionProvider, interval: u64) -> SlowlogReader {
log::debug!("Creating slowlog reader");
loop {
match SlowlogReader::try_from(con_provider.clone()) {
Err(e) => error_handler(e),
Ok(slr) => return slr,
}
sleep(Duration::new(interval, 0))
}
}

fn read_once(con_provider: RedisConnectionProvider, config: &argument_parsing::Config) {
match {
move || -> Result<(), redis::RedisError> {
for r in rsloglib::get_slowlog(&mut con_provider.get_connection()?, 128)?.iter() {
print_rec(r, &config.output_format)
}
Ok(())
}
}() {
Err(e) => error_handler(e),
Ok(_) => std::process::exit(0),
}
}

fn read_continiously(con_provider: RedisConnectionProvider, config: &argument_parsing::Config) {
let mut sl_reader = create_slowlog_reader(con_provider, config.interval);

loop {
match sl_reader
.get()
.map_err(|e| sl_reader.redis_error_handler(e))
{
Ok(records) => {
for r in records.iter().rev() {
print_rec(r, &config.output_format)
}
}
Err(e) => {
if let Err(e) = e {
error_handler(e)
}
}
}
sleep(Duration::new(config.interval, 0));
}
}

pub fn main() {
let config = argument_parsing::get_config()
.map_err(|e| e.exit())
.unwrap();
stderrlog::new()
.timestamp(stderrlog::Timestamp::Second)
.verbosity(config.verbosity)
.quiet(config.quiet)
.init()
.unwrap();
let redis_client = redis::Client::open((&config.hostname, config.port)).unwrap();
let connection_provider = RedisConnectionProvider::from((redis_client, config.interval));
if config.follow {
read_continiously(connection_provider, &config)
} else {
read_once(connection_provider, &config)
}
}

0 comments on commit b3e9bc5

Please sign in to comment.