|
| 1 | +use figment::{ |
| 2 | + providers::{Format, Json, Toml}, |
| 3 | + Figment, |
| 4 | +}; |
| 5 | +use netem_trace::{model::DuplicateTraceConfig, DuplicatePattern, DuplicateTrace}; |
| 6 | +use rand::{rngs::StdRng, SeedableRng}; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | + |
| 9 | +use crate::{ |
| 10 | + core::DeviceFactory, |
| 11 | + devices::{duplicate, Packet}, |
| 12 | + error::Error, |
| 13 | +}; |
| 14 | + |
| 15 | +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] |
| 16 | +#[derive(Debug, Clone)] |
| 17 | +pub struct DuplicateDeviceBuildConfig { |
| 18 | + pub pattern: DuplicatePattern, |
| 19 | + pub seed: Option<u64>, |
| 20 | +} |
| 21 | + |
| 22 | +impl DuplicateDeviceBuildConfig { |
| 23 | + pub fn into_factory<P: Packet>( |
| 24 | + self, |
| 25 | + ) -> impl DeviceFactory<duplicate::DuplicateDevice<P, StdRng>> { |
| 26 | + move |handle| { |
| 27 | + let _guard = handle.enter(); |
| 28 | + let rng = StdRng::seed_from_u64(self.seed.unwrap_or(42)); |
| 29 | + duplicate::DuplicateDevice::new(self.pattern, rng) |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] |
| 35 | +#[derive(Debug, Clone)] |
| 36 | +pub struct DuplicateReplayDeviceBuildConfig { |
| 37 | + pub trace: String, |
| 38 | + pub seed: Option<u64>, |
| 39 | +} |
| 40 | + |
| 41 | +impl DuplicateReplayDeviceBuildConfig { |
| 42 | + fn get_trace(&self) -> Result<Box<dyn DuplicateTrace>, Error> { |
| 43 | + let file_path = std::path::Path::new(&self.trace); |
| 44 | + if let Some(ext) = file_path.extension() { |
| 45 | + if ext == "json" { |
| 46 | + let trace: Box<dyn DuplicateTraceConfig> = Figment::new() |
| 47 | + .merge(Json::file(file_path)) |
| 48 | + .extract() |
| 49 | + .map_err(|e| Error::ConfigError(e.to_string()))?; |
| 50 | + return Ok(trace.into_model()); |
| 51 | + } else if ext == "toml" { |
| 52 | + let trace: Box<dyn DuplicateTraceConfig> = Figment::new() |
| 53 | + .merge(Toml::file(file_path)) |
| 54 | + .extract() |
| 55 | + .map_err(|e| Error::ConfigError(e.to_string()))?; |
| 56 | + return Ok(trace.into_model()); |
| 57 | + } |
| 58 | + } |
| 59 | + Err(Error::ConfigError(format!( |
| 60 | + "Unknown trace file format: {:?}", |
| 61 | + file_path |
| 62 | + ))) |
| 63 | + } |
| 64 | + |
| 65 | + pub fn into_factory<P: Packet>( |
| 66 | + self, |
| 67 | + ) -> impl DeviceFactory<duplicate::DuplicateReplayDevice<P, StdRng>> { |
| 68 | + move |handle| { |
| 69 | + let _guard = handle.enter(); |
| 70 | + let trace = self.get_trace()?; |
| 71 | + let rng = StdRng::seed_from_u64(self.seed.unwrap_or(42)); |
| 72 | + duplicate::DuplicateReplayDevice::new(trace, rng) |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments