Skip to content

Commit

Permalink
migrate to anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
timglabisch committed Jul 5, 2023
1 parent 23132f9 commit 6bf878e
Show file tree
Hide file tree
Showing 10 changed files with 29 additions and 79 deletions.
43 changes: 1 addition & 42 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion mehsh_check/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ edition = "2018"
[dependencies]
structopt = "0.3.*"
futures = "0.3.*"
failure = "0.1.*"
bytes = "1.*"
rand = "*"
chrono = "0.4.*"
Expand Down
6 changes: 2 additions & 4 deletions mehsh_check/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::analyzer_event::analyzer_event_subscriber_udp_metric::AnalyzerEventSu
use crate::broadcast::BroadcastEvent;
use crate::http::http_analyzer::HttpAnalyzer;
use crate::http::http_check::HttpCheck;
use failure::Error;
use mehsh_common::config::Config;
use std::path::PathBuf;
use structopt::StructOpt;
Expand All @@ -24,7 +23,6 @@ pub mod udp_echo;
pub mod maintenance_mode;

#[macro_use]
extern crate failure;
extern crate mehsh_common;

#[derive(StructOpt, Debug)]
Expand Down Expand Up @@ -56,15 +54,15 @@ fn main() {
Err(err) => {
eprintln!("{:?}", &err);

for cause in err.iter_causes() {
for cause in err.chain().into_iter() {
println!("{:?}", cause);
}
}
Ok(_) => {}
}
}

fn try_main(opt: Opt, rt: Runtime) -> Result<(), Error> {
fn try_main(opt: Opt, rt: Runtime) -> Result<(), ::anyhow::Error> {
let name_self = opt.name.replace(
"[hostname]",
hostname::get()
Expand Down
5 changes: 2 additions & 3 deletions mehsh_check/src/udp_echo/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::udp_echo::analyzer::AnalyzerEvent;
use crate::udp_echo::packet::Packet;
use failure::Error;
use futures::channel::mpsc::Sender;
use futures::future;
use mehsh_common::config::ConfigCheck;
Expand All @@ -23,7 +22,7 @@ impl Client {
pub async fn new(
check: ConfigCheck,
client_analyzer_sender: Sender<AnalyzerEvent>,
) -> Result<Self, Error> {
) -> Result<Self, ::anyhow::Error> {
let host = format!("{}:4232", check.to.ip.to_string());
let remote_socket: SocketAddr = host.parse()?;
Ok(Client {
Expand All @@ -34,7 +33,7 @@ impl Client {
})
}

pub async fn run(self) -> Result<(), Error> {
pub async fn run(self) -> Result<(), ::anyhow::Error> {
let remote_socket = self.remote_socket;
let local_socket: SocketAddr = "0.0.0.0:0".parse()?;

Expand Down
10 changes: 5 additions & 5 deletions mehsh_check/src/udp_echo/packet.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use bytes::{Buf, BufMut, BytesMut};
use failure::Error;
use std::mem::size_of;
use anyhow::anyhow;

const PACKAGE_MAGIC: u32 = 326134347;

Expand Down Expand Up @@ -50,25 +50,25 @@ impl Packet {
buf.to_vec()
}

pub fn new_from_raw(data: &[u8]) -> Result<Self, Error> {
pub fn new_from_raw(data: &[u8]) -> Result<Self, ::anyhow::Error> {
if data.len() < PACKAGE_SIZE {
return Err(format_err!("invalid packet size"));
return Err(anyhow!("invalid packet size"));
}

let mut buf = &data[..];

let magic_byte = buf.get_u32();

if magic_byte != PACKAGE_MAGIC {
return Err(format_err!("invalid packet magic"));
return Err(anyhow!("invalid packet magic"));
}

let version = buf.get_u32();
let id = buf.get_u64();
let packet_type = match buf.get_u16() {
1 => PacketType::Req,
2 => PacketType::Resp,
_ => return Err(format_err!("unknown packet type")),
_ => return Err(anyhow!("unknown packet type")),
};

Ok(Packet {
Expand Down
7 changes: 3 additions & 4 deletions mehsh_check/src/udp_echo/server.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::udp_echo::packet::Packet;
use failure::Error;
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use tokio;
Expand All @@ -11,15 +10,15 @@ pub struct Server {
}

impl Server {
pub async fn new(host: &str) -> Result<Self, Error> {
pub async fn new(host: &str) -> Result<Self, ::anyhow::Error> {
let socket: SocketAddrV4 = host.parse()?;
Ok(Server {
socket: UdpSocket::bind(socket).await?,
buf: vec![0; 100],
})
}

pub async fn run(mut self) -> Result<(), Error> {
pub async fn run(mut self) -> Result<(), ::anyhow::Error> {
loop {
match self.run_loop().await {
Err(e) => {
Expand All @@ -30,7 +29,7 @@ impl Server {
}
}

async fn run_loop(&mut self) -> Result<(), Error> {
async fn run_loop(&mut self) -> Result<(), ::anyhow::Error> {
let (size, target): (usize, SocketAddr) = self.socket.recv_from(&mut self.buf).await?;

let recv_packet = Packet::new_from_raw(&self.buf[0..size]).expect("could not read package");
Expand Down
2 changes: 1 addition & 1 deletion mehsh_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2018"

[dependencies]
toml = "0.5"
failure = "0.1.*"
anyhow = "*"
serde = { version = "1.0", features = ["derive"] }
bytes = "0.5.3"
rand = "*"
20 changes: 10 additions & 10 deletions mehsh_common/src/config/allow_addr.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use failure::Error;
use std::net::Ipv4Addr;
use anyhow::anyhow;

#[derive(Debug, Clone, PartialEq)]
pub enum AllowAddrPort {
Expand Down Expand Up @@ -32,7 +32,7 @@ impl AllowIp {
}

impl AllowAddrPort {
pub fn new_from_str(s: &str) -> Result<Self, Error> {
pub fn new_from_str(s: &str) -> Result<Self, ::anyhow::Error> {
if s == "*" {
return Ok(AllowAddrPort::AnyPort);
}
Expand All @@ -44,35 +44,35 @@ impl AllowAddrPort {
let parts: Vec<_> = s.split('-').map(|s| s.to_string()).collect();

if parts.len() != 2 {
return Err(format_err!("could not decode addr port {}", s));
return Err(anyhow!("could not decode addr port {}", s));
}

let min = {
if let Ok(k) = parts[0].parse() {
Ok(k)
} else {
Err(format_err!("could not decode (min) addr port {}", s))
Err(anyhow!("could not decode (min) addr port {}", s))
}
}?;

let max = {
if let Ok(k) = parts[1].parse() {
Ok(k)
} else {
Err(format_err!("could not decode (max) addr port {}", s))
Err(anyhow!("could not decode (max) addr port {}", s))
}
}?;

if parts[0] > parts[1] {
return Err(format_err!("range mismatch {}", s));
return Err(anyhow!("range mismatch {}", s));
}

Ok(AllowAddrPort::Range(min, max))
}
}

impl AllowAddr {
fn parse_v4(data: &str) -> Result<Self, Error> {
fn parse_v4(data: &str) -> Result<Self, ::anyhow::Error> {
let parts: Vec<_> = data
.trim_start_matches("v4:")
.split(':')
Expand All @@ -90,15 +90,15 @@ impl AllowAddr {
));
}

Err(format_err!("nöpe"))
Err(anyhow!("nöpe"))
}

pub fn new_from_str(data: &str) -> Result<Self, Error> {
pub fn new_from_str(data: &str) -> Result<Self, ::anyhow::Error> {
if data.starts_with("v4:") {
return Self::parse_v4(data);
}

Err(format_err!("could not parse '{}' the identifier should start with 'v4:', 'v6:', 'server:' or 'group:'", data))
Err(anyhow!("could not parse '{}' the identifier should start with 'v4:', 'v6:', 'server:' or 'group:'", data))
}
}

Expand Down
11 changes: 5 additions & 6 deletions mehsh_common/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::config::allow_addr::AllowIp;
use failure::Error;
use serde::Deserialize;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
Expand Down Expand Up @@ -156,7 +155,7 @@ impl Config {
pub fn new_from_bytes(
self_server_identifier: ServerIdentifier,
content: &[u8],
) -> Result<Self, Error> {
) -> Result<Self, ::anyhow::Error> {
let raw_config = toml::from_slice::<RawConfig>(content)?;

let servers = raw_config
Expand Down Expand Up @@ -194,7 +193,7 @@ impl Config {
})
}

pub fn all_analyisis(&self) -> Result<Vec<ConfigAnalysis>, Error> {
pub fn all_analyisis(&self) -> Result<Vec<ConfigAnalysis>, ::anyhow::Error> {
let mut buf = HashMap::new();
match &self.analysis {
None => {}
Expand Down Expand Up @@ -231,7 +230,7 @@ impl Config {
Ok(buf.into_iter().map(|(_k, v)| v).collect::<Vec<_>>())
}

pub fn all_checks(&self) -> Result<Vec<ConfigCheck>, Error> {
pub fn all_checks(&self) -> Result<Vec<ConfigCheck>, ::anyhow::Error> {
let mut buf = HashMap::new();
match &self.check {
None => {}
Expand Down Expand Up @@ -270,7 +269,7 @@ impl Config {
pub fn new_from_file(
self_server_identifier: ServerIdentifier,
filename: PathBuf,
) -> Result<Self, Error> {
) -> Result<Self, ::anyhow::Error> {
let mut content = Vec::new();
File::open(filename)?.read_to_end(&mut content)?;

Expand All @@ -293,7 +292,7 @@ impl Config {
&self.server_self
}

pub fn resolve_idents<I>(&self, raw_identifier: I) -> Result<Vec<Ident>, Error>
pub fn resolve_idents<I>(&self, raw_identifier: I) -> Result<Vec<Ident>, ::anyhow::Error>
where
I: AsRef<str> + Sized,
{
Expand Down
3 changes: 0 additions & 3 deletions mehsh_common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#![allow(dead_code)]

#[macro_use]
extern crate failure;

pub mod config;

0 comments on commit 6bf878e

Please sign in to comment.