use std::{
net::{SocketAddr, ToSocketAddrs},
num::{NonZeroU32, NonZeroUsize},
time::Duration,
};
use byte_unit::{Byte, ByteUnit};
use metrics::{counter, gauge, register_counter};
use rand::{rngs::StdRng, SeedableRng};
use serde::Deserialize;
use tokio::net::UdpSocket;
use tracing::{debug, info, trace};
use crate::{
block::{self, chunk_bytes, construct_block_cache, Block},
payload,
signals::Shutdown,
throttle::{self, Throttle},
};
use super::General;
#[derive(Debug, Deserialize, PartialEq)]
pub struct Config {
pub seed: [u8; 32],
pub addr: String,
pub variant: payload::Config,
pub bytes_per_second: byte_unit::Byte,
pub block_sizes: Option<Vec<byte_unit::Byte>>,
pub maximum_prebuild_cache_size_bytes: byte_unit::Byte,
#[serde(default)]
pub throttle: throttle::Config,
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Creation of payload blocks failed: {0}")]
Block(#[from] block::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Debug)]
pub struct Udp {
addr: SocketAddr,
throttle: Throttle,
block_cache: Vec<Block>,
metric_labels: Vec<(String, String)>,
shutdown: Shutdown,
}
impl Udp {
#[allow(clippy::cast_possible_truncation)]
pub fn new(general: General, config: &Config, shutdown: Shutdown) -> Result<Self, Error> {
let mut rng = StdRng::from_seed(config.seed);
let block_sizes: Vec<NonZeroUsize> = config
.block_sizes
.clone()
.unwrap_or_else(|| {
vec![
Byte::from_unit(1.0 / 32.0, ByteUnit::MB).unwrap(),
Byte::from_unit(1.0 / 16.0, ByteUnit::MB).unwrap(),
Byte::from_unit(1.0 / 8.0, ByteUnit::MB).unwrap(),
Byte::from_unit(1.0 / 4.0, ByteUnit::MB).unwrap(),
Byte::from_unit(1.0 / 2.0, ByteUnit::MB).unwrap(),
Byte::from_unit(1_f64, ByteUnit::MB).unwrap(),
Byte::from_unit(2_f64, ByteUnit::MB).unwrap(),
Byte::from_unit(4_f64, ByteUnit::MB).unwrap(),
]
})
.iter()
.map(|sz| NonZeroUsize::new(sz.get_bytes() as usize).expect("bytes must be non-zero"))
.collect();
let mut labels = vec![
("component".to_string(), "generator".to_string()),
("component_name".to_string(), "udp".to_string()),
];
if let Some(id) = general.id {
labels.push(("id".to_string(), id));
}
let bytes_per_second = NonZeroU32::new(config.bytes_per_second.get_bytes() as u32).unwrap();
gauge!(
"bytes_per_second",
f64::from(bytes_per_second.get()),
&labels
);
let block_chunks = chunk_bytes(
&mut rng,
NonZeroUsize::new(config.maximum_prebuild_cache_size_bytes.get_bytes() as usize)
.expect("bytes must be non-zero"),
&block_sizes,
)?;
let block_cache = construct_block_cache(&mut rng, &config.variant, &block_chunks, &labels);
let addr = config
.addr
.to_socket_addrs()
.expect("could not convert to socket")
.next()
.unwrap();
Ok(Self {
addr,
block_cache,
throttle: Throttle::new_with_config(config.throttle, bytes_per_second, labels.clone()),
metric_labels: labels,
shutdown,
})
}
pub async fn spin(mut self) -> Result<(), Error> {
debug!("UDP generator running");
let mut connection = Option::<UdpSocket>::None;
let mut blocks = self.block_cache.iter().cycle().peekable();
let bytes_written = register_counter!("bytes_written", &self.metric_labels);
let packets_sent = register_counter!("packets_sent", &self.metric_labels);
loop {
let blk = blocks.peek().unwrap();
let total_bytes = blk.total_bytes;
assert!(
total_bytes.get() <= 65507,
"UDP packet too large (over 65507 B)"
);
tokio::select! {
conn = UdpSocket::bind("127.0.0.1:0"), if connection.is_none() => {
match conn {
Ok(sock) => {
debug!("UDP port bound");
connection = Some(sock);
}
Err(err) => {
trace!("binding UDP port failed: {}", err);
let mut error_labels = self.metric_labels.clone();
error_labels.push(("error".to_string(), err.to_string()));
counter!("connection_failure", 1, &error_labels);
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
}
_ = self.throttle.wait_for(total_bytes), if connection.is_some() => {
let sock = connection.unwrap();
let blk = blocks.next().unwrap(); match sock.send_to(&blk.bytes, self.addr).await {
Ok(bytes) => {
bytes_written.increment(bytes as u64);
packets_sent.increment(1);
connection = Some(sock);
}
Err(err) => {
debug!("write failed: {}", err);
let mut error_labels = self.metric_labels.clone();
error_labels.push(("error".to_string(), err.to_string()));
counter!("request_failure", 1, &error_labels);
connection = None;
}
}
}
_ = self.shutdown.recv() => {
info!("shutdown signal received");
return Ok(());
},
}
}
}
}