utils.rs 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use std::str::{self, FromStr};
  2. use std::env;
  3. use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
  4. use std::process;
  5. use log::{LogLevel, LogLevelFilter, LogRecord};
  6. use env_logger::LogBuilder;
  7. use getopts;
  8. use smoltcp::phy::{EthernetTracer, FaultInjector, TapInterface};
  9. pub fn setup_logging_with_clock<F>(since_startup: F)
  10. where F: Fn() -> u64 + Send + Sync + 'static {
  11. LogBuilder::new()
  12. .format(move |record: &LogRecord| {
  13. let elapsed = since_startup();
  14. let timestamp = format!("[{:6}.{:03}s]", elapsed / 1000, elapsed % 1000);
  15. if record.target().starts_with("smoltcp::") {
  16. format!("\x1b[0m{} ({}): {}\x1b[0m", timestamp,
  17. record.target().replace("smoltcp::", ""), record.args())
  18. } else if record.level() == LogLevel::Trace {
  19. let mut message = format!("{}", record.args());
  20. message.pop();
  21. format!("\x1b[37m{} {}\x1b[0m", timestamp,
  22. message.replace("\n", "\n "))
  23. } else {
  24. format!("\x1b[32m{} ({}): {}\x1b[0m", timestamp,
  25. record.target(), record.args())
  26. }
  27. })
  28. .filter(None, LogLevelFilter::Trace)
  29. .init()
  30. .unwrap();
  31. }
  32. pub fn setup_logging() {
  33. let startup_at = Instant::now();
  34. setup_logging_with_clock(move || {
  35. let elapsed = Instant::now().duration_since(startup_at);
  36. elapsed.as_secs() * 1000 + (elapsed.subsec_nanos() / 1000) as u64
  37. })
  38. }
  39. pub fn setup_device(more_args: &[&str])
  40. -> (FaultInjector<EthernetTracer<TapInterface>>,
  41. Vec<String>) {
  42. let mut opts = getopts::Options::new();
  43. opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
  44. opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
  45. opts.optopt("", "size-limit", "Drop packets larger than given size (octets)", "SIZE");
  46. opts.optopt("", "tx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  47. (packets per interval)", "RATE");
  48. opts.optopt("", "rx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  49. (packets per interval)", "RATE");
  50. opts.optopt("", "shaping-interval", "Sets the interval for rate limiting (ms)", "RATE");
  51. opts.optflag("h", "help", "print this help menu");
  52. let matches = opts.parse(env::args().skip(1)).unwrap();
  53. if matches.opt_present("h") || matches.free.len() != more_args.len() + 1 {
  54. let brief = format!("Usage: {} INTERFACE {} [options]",
  55. env::args().nth(0).unwrap(),
  56. more_args.join(" "));
  57. print!("{}", opts.usage(&brief));
  58. process::exit(if matches.free.len() != more_args.len() + 1 { 1 } else { 0 });
  59. }
  60. let drop_chance = u8::from_str(&matches.opt_str("drop-chance")
  61. .unwrap_or("0".to_string())).unwrap();
  62. let corrupt_chance = u8::from_str(&matches.opt_str("corrupt-chance")
  63. .unwrap_or("0".to_string())).unwrap();
  64. let size_limit = usize::from_str(&matches.opt_str("size-limit")
  65. .unwrap_or("0".to_string())).unwrap();
  66. let tx_rate_limit = u64::from_str(&matches.opt_str("tx-rate-limit")
  67. .unwrap_or("0".to_string())).unwrap();
  68. let rx_rate_limit = u64::from_str(&matches.opt_str("rx-rate-limit")
  69. .unwrap_or("0".to_string())).unwrap();
  70. let shaping_interval = u32::from_str(&matches.opt_str("shaping-interval")
  71. .unwrap_or("0".to_string())).unwrap();
  72. let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
  73. let device = TapInterface::new(&matches.free[0]).unwrap();
  74. let device = EthernetTracer::new(device, |printer| trace!("{}", printer));
  75. let mut device = FaultInjector::new(device, seed);
  76. device.set_drop_chance(drop_chance);
  77. device.set_corrupt_chance(corrupt_chance);
  78. device.set_max_packet_size(size_limit);
  79. device.set_max_tx_rate(tx_rate_limit);
  80. device.set_max_rx_rate(rx_rate_limit);
  81. device.set_bucket_interval(Duration::from_millis(shaping_interval as u64));
  82. (device, matches.free[1..].to_owned())
  83. }