Skip to content

Commit a6b8dae

Browse files
committed
Refactoring.
`find_mac` takes an `IpAddr` instead of `Ipv4Addr`. Deduplicate `BytesFmt` and move it to `pixie_shared::utils`. Using `BytesFmt` more often in `pixie-uefi`. Derive `From` for `pixie_uefi::os::error::Error`. Use `gloo-net` instead of `reqwest` on `pixie-web`. Fix images table alignment. Add swap partition to the test.
1 parent cdff52e commit a6b8dae

21 files changed

Lines changed: 156 additions & 518 deletions

File tree

pixie-server/src/main.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use tokio::{signal::unix::SignalKind, task::JoinHandle};
2525
///
2626
/// This function searches the address in the arp cache, if it is not available it tries to
2727
/// populate it by pinging the peer.
28-
fn find_mac(ip: Ipv4Addr) -> Result<MacAddr6> {
28+
fn find_mac(ip: IpAddr) -> Result<MacAddr6> {
2929
struct Zombie {
3030
inner: Child,
3131
}
@@ -41,8 +41,6 @@ fn find_mac(ip: Ipv4Addr) -> Result<MacAddr6> {
4141
bail!("localhost not supported");
4242
}
4343

44-
let s = ip.to_string();
45-
4644
// Repeat twice, sending a ping if looking at ip neigh the first time fails.
4745
for _ in 0..2 {
4846
let mut child = Zombie {
@@ -60,7 +58,7 @@ fn find_mac(ip: Ipv4Addr) -> Result<MacAddr6> {
6058
let line = line?;
6159
let mut parts = line.split(' ');
6260

63-
if parts.next() == Some(&s) {
61+
if parts.next().and_then(|s| s.parse().ok()) == Some(ip) {
6462
let mac = parts.nth(3).unwrap();
6563
if let Ok(mac) = mac.parse() {
6664
return Ok(mac);
@@ -69,7 +67,7 @@ fn find_mac(ip: Ipv4Addr) -> Result<MacAddr6> {
6967
}
7068

7169
let _ = Command::new("ping")
72-
.args([&s, "-c", "1", "-W", "0.1"])
70+
.args([&ip.to_string(), "-c", "1", "-W", "0.1"])
7371
.stdout(Stdio::null())
7472
.spawn()?
7573
.wait();

pixie-server/src/ping.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,9 @@ use crate::{
44
find_mac,
55
state::{State, UnitSelector},
66
};
7-
use anyhow::{bail, Result};
7+
use anyhow::Result;
88
use pixie_shared::{PING_PORT, UDP_BODY_LEN};
9-
use std::{
10-
net::{IpAddr, Ipv4Addr},
11-
sync::Arc,
12-
time::SystemTime,
13-
};
9+
use std::{net::Ipv4Addr, sync::Arc, time::SystemTime};
1410
use tokio::net::UdpSocket;
1511

1612
pub async fn main(state: Arc<State>) -> Result<()> {
@@ -23,10 +19,7 @@ pub async fn main(state: Arc<State>) -> Result<()> {
2319
x = socket.recv_from(&mut buf) => x?,
2420
_ = state.cancel_token.cancelled() => break,
2521
};
26-
let IpAddr::V4(peer_ip) = peer_addr.ip() else {
27-
bail!("IPv6 is not supported")
28-
};
29-
let peer_mac = match find_mac(peer_ip) {
22+
let peer_mac = match find_mac(peer_addr.ip()) {
3023
Ok(peer_mac) => peer_mac,
3124
Err(err) => {
3225
log::error!("Error handling ping packet: {err}");

pixie-server/src/tcp.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ use crate::{
44
find_mac,
55
state::{State, UnitSelector},
66
};
7-
use anyhow::{bail, Context, Result};
7+
use anyhow::{Context, Result};
88
use macaddr::MacAddr6;
99
use pixie_shared::{TcpRequest, ACTION_PORT};
1010
use std::{
1111
io::ErrorKind,
12-
net::{IpAddr, Ipv4Addr, SocketAddr},
12+
net::{Ipv4Addr, SocketAddr},
1313
sync::Arc,
1414
};
1515
use tokio::{
@@ -57,10 +57,7 @@ async fn handle_connection(
5757
mut stream: TcpStream,
5858
peer_addr: SocketAddr,
5959
) -> Result<()> {
60-
let IpAddr::V4(peer_ip) = peer_addr.ip() else {
61-
bail!("IPv6 is not supported")
62-
};
63-
let peer_mac = match find_mac(peer_ip) {
60+
let peer_mac = match find_mac(peer_addr.ip()) {
6461
Ok(peer_mac) => peer_mac,
6562
Err(err) => {
6663
log::error!("Error handling tcp connection: {err}");

pixie-server/src/udp.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ use crate::{
44
find_mac, find_network,
55
state::{State, UnitSelector},
66
};
7-
use anyhow::{bail, ensure, Context, Result};
7+
use anyhow::{ensure, Context, Result};
88
use pixie_shared::{
99
chunk_codec::Encoder, ChunkHash, HintPacket, RegistrationInfo, UdpRequest, ACTION_PORT,
1010
CHUNKS_PORT, HINT_PORT, UDP_BODY_LEN,
1111
};
1212
use std::{
1313
collections::BTreeSet,
14-
net::{IpAddr, Ipv4Addr, SocketAddrV4},
14+
net::{Ipv4Addr, SocketAddrV4},
1515
ops::Bound,
1616
sync::Arc,
1717
};
@@ -168,20 +168,17 @@ async fn broadcast_hint(state: &State, socket: &UdpSocket, ip: Ipv4Addr) -> Resu
168168
async fn handle_requests(state: &State, socket: &UdpSocket, tx: Sender<[u8; 32]>) -> Result<()> {
169169
let mut buf = [0; UDP_BODY_LEN];
170170
loop {
171-
let (len, addr) = tokio::select! {
171+
let (len, peer_addr) = tokio::select! {
172172
x = socket.recv_from(&mut buf) => x?,
173173
_ = state.cancel_token.cancelled() => break,
174174
};
175175
let req: postcard::Result<UdpRequest> = postcard::from_bytes(&buf[..len]);
176176
match req {
177177
Ok(UdpRequest::Discover) => {
178-
socket.send_to(&[], addr).await?;
178+
socket.send_to(&[], peer_addr).await?;
179179
}
180180
Ok(UdpRequest::ActionProgress(frac, tot)) => {
181-
let IpAddr::V4(peer_ip) = addr.ip() else {
182-
bail!("IPv6 is not supported")
183-
};
184-
match find_mac(peer_ip) {
181+
match find_mac(peer_addr.ip()) {
185182
Ok(peer_mac) => {
186183
state.set_unit_progress(UnitSelector::MacAddr(peer_mac), Some((frac, tot)));
187184
}
@@ -196,7 +193,7 @@ async fn handle_requests(state: &State, socket: &UdpSocket, tx: Sender<[u8; 32]>
196193
}
197194
}
198195
Err(e) => {
199-
log::warn!("Invalid request from {addr}: {e}");
196+
log::warn!("Invalid request from {peer_addr}: {e}");
200197
}
201198
}
202199
}

pixie-shared/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ pub mod bijection;
66
pub mod chunk_codec;
77
#[cfg(feature = "std")]
88
pub mod config;
9+
pub mod util;
910

1011
use alloc::{collections::BTreeMap, string::String, vec::Vec};
1112
use blake3::OUT_LEN;

pixie-shared/src/util.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
pub struct BytesFmt(pub u64);
2+
3+
impl core::fmt::Display for BytesFmt {
4+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5+
if self.0 < 1 << 10 {
6+
write!(f, "{} B", self.0)
7+
} else if self.0 < 1 << 20 {
8+
write!(f, "{:.2} KiB", self.0 as f64 / (1i64 << 10) as f64)
9+
} else if self.0 < 1 << 30 {
10+
write!(f, "{:.2} MiB", self.0 as f64 / (1i64 << 20) as f64)
11+
} else if self.0 < 1 << 40 {
12+
write!(f, "{:.2} GiB", self.0 as f64 / (1i64 << 30) as f64)
13+
} else {
14+
write!(f, "{:.2} TiB", self.0 as f64 / (1i64 << 40) as f64)
15+
}
16+
}
17+
}

pixie-uefi/Cargo.lock

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pixie-uefi/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ coverage = ["dep:minicov"]
1616
anstyle = { version = "1.0.11", default-features = false }
1717
blake3 = { version = "1.8.2", default-features = false, features = ["prefer_intrinsics", "no_avx512", "pure"] }
1818
core_detect = "1.0.0"
19+
derive_more = { version = "2.0.1", features = ["from"], default-features = false }
1920
futures = { version = "0.3.29", default-features = false, features = ["alloc", "async-await"] }
2021
gpt_disk_io = "0.16.2"
2122
log = "0.4.27"

pixie-uefi/src/flash.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ use futures::future::{select, Either};
1111
use log::info;
1212
use lz4_flex::decompress;
1313
use pixie_shared::{
14-
chunk_codec::Decoder, ChunkHash, Image, TcpRequest, UdpRequest, CHUNKS_PORT, MAX_CHUNK_SIZE,
14+
chunk_codec::Decoder, util::BytesFmt, ChunkHash, Image, TcpRequest, UdpRequest, CHUNKS_PORT,
15+
MAX_CHUNK_SIZE,
1516
};
1617
use uefi::proto::console::text::Color;
1718

@@ -168,7 +169,10 @@ pub async fn flash(os: UefiOS, server_addr: SocketAddrV4) -> Result<()> {
168169
let mut last_seen = Vec::new();
169170
let total_mem = os.get_total_mem();
170171
let max_chunks = (total_mem.saturating_sub(MIN_MEMORY) as usize / MAX_CHUNK_SIZE).max(128);
171-
log::debug!("Total memory: {total_mem}. Max chunks in memory: {max_chunks}");
172+
log::debug!(
173+
"Total memory: {}. Max chunks in memory: {max_chunks}",
174+
BytesFmt(total_mem)
175+
);
172176
while !chunks_info.is_empty() {
173177
let recv = Box::pin(socket.recv(&mut buf));
174178
let sleep = Box::pin(os.sleep_us(100_000));

pixie-uefi/src/os/async.rs

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)