utils.rs 4.6 KB

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