Skip to content

Commit

Permalink
Merge pull request #71 from ifd3f/refactor/rename-to-writer-process
Browse files Browse the repository at this point in the history
Terminology change: rename "child" to "writer process"
  • Loading branch information
ifd3f committed Nov 10, 2023
2 parents c80f42e + 5c5a9c3 commit 1bd71f7
Show file tree
Hide file tree
Showing 17 changed files with 186 additions and 151 deletions.
12 changes: 0 additions & 12 deletions src/burn/mod.rs

This file was deleted.

22 changes: 11 additions & 11 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ use serde::{Deserialize, Serialize};
use valuable::Valuable;

#[cfg(target_os = "linux")]
pub fn enumerate_devices() -> impl Iterator<Item = BurnTarget> {
pub fn enumerate_devices() -> impl Iterator<Item = WriteTarget> {
use std::fs::read_dir;

let paths = read_dir("/sys/class/block").unwrap();

paths
.filter_map(|r| r.ok())
.filter_map(|d| BurnTarget::try_from(d.path().as_ref()).ok())
.filter_map(|d| WriteTarget::try_from(d.path().as_ref()).ok())
}

#[cfg(target_os = "macos")]
pub fn enumerate_devices() -> impl Iterator<Item = BurnTarget> {
pub fn enumerate_devices() -> impl Iterator<Item = WriteTarget> {
use std::{
ffi::{CStr, OsString},
os::unix::prelude::OsStrExt,
Expand Down Expand Up @@ -75,7 +75,7 @@ pub fn enumerate_devices() -> impl Iterator<Item = BurnTarget> {
_ => Type::File,
};

out.push(BurnTarget {
out.push(WriteTarget {
name: bsdname,
devnode,
size,
Expand All @@ -94,7 +94,7 @@ pub fn enumerate_devices() -> impl Iterator<Item = BurnTarget> {
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BurnTarget {
pub struct WriteTarget {
/// A user-friendly name for the disk (i.e. sda, nvme0n1, disk1s4)
pub name: String,
pub devnode: PathBuf,
Expand All @@ -104,15 +104,15 @@ pub struct BurnTarget {
pub target_type: Type,
}

impl BurnTarget {
impl WriteTarget {
#[cfg(target_os = "macos")]
fn from_dev_name(name: &OsStr) -> Result<Self, DeviceParseError> {
use std::os::unix::prelude::OsStrExt;

use format_bytes::format_bytes;

// I don't want to write more Objective C. Oh god. Please no.
let devices: Vec<BurnTarget> = enumerate_devices().collect();
let devices: Vec<WriteTarget> = enumerate_devices().collect();
let expected_if_direct_node = format_bytes!(b"/dev/{}", name.as_bytes());
let expected_if_raw_node = format_bytes!(b"/dev/r{}", name.as_bytes());

Expand Down Expand Up @@ -186,7 +186,7 @@ impl BurnTarget {
}

fn from_normal_file(path: PathBuf) -> Result<Self, DeviceParseError> {
Ok(BurnTarget {
Ok(WriteTarget {
name: path.to_string_lossy().into(),
devnode: path,
size: TargetSize(None),
Expand All @@ -197,19 +197,19 @@ impl BurnTarget {
}
}

impl PartialOrd for BurnTarget {
impl PartialOrd for WriteTarget {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.devnode.partial_cmp(&other.devnode)
}
}

impl Ord for BurnTarget {
impl Ord for WriteTarget {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.devnode.cmp(&other.devnode)
}
}

impl TryFrom<&Path> for BurnTarget {
impl TryFrom<&Path> for WriteTarget {
type Error = DeviceParseError;

fn try_from(value: &Path) -> Result<Self, Self::Error> {
Expand Down
12 changes: 6 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use burn::child::is_in_burn_mode;
use run_mode::RunMode;

mod burn;
mod byteseries;
mod compression;
mod device;
mod escalation;
mod hash;
mod logging;
mod native;
mod run_mode;
mod ui;
mod writer_process;

fn main() {
if is_in_burn_mode() {
burn::child::main();
} else {
ui::main::main();
match RunMode::detect() {
RunMode::Main => ui::main::main(),
RunMode::Writer => writer_process::child::main(),
}
}
53 changes: 53 additions & 0 deletions src/run_mode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
pub const RUN_MODE_ENV_NAME: &str = "__CALIGULA_RUN_MODE";

/// [RunMode] is a flag set in the environment variable `__CALIGULA_RUN_MODE`
/// to signal which process we are.
///
/// # Motivation
///
/// What we would ideally like to do is write code that looks like this, to
/// escalate privileges:
///
/// ```
/// let is_child_process = fork();
///
/// if is_child_process {
/// if need_to_sudo {
/// become_root();
/// }
/// run_child_procedure();
/// } else {
/// run_parent_procedure();
/// }
/// ```
///
/// Unfortunately, the best we can do is call `sudo`/`doas`/`su` on ourself,
/// and detect if we are the child process.
///
/// Thus, this "private" environment variable and detection code is here to
/// help us achieve that.
///
/// *Why is this an environment variable instead of a CLI subcommand?* It's
/// meant to be hidden from the user as much as possible. There is no reason
/// that the user should ever set the run mode.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RunMode {
Main,
Writer,
}

impl RunMode {
pub fn detect() -> Self {
match std::env::var(RUN_MODE_ENV_NAME).as_deref() {
Ok("writer") => Self::Writer,
_ => Self::Main,
}
}

pub fn as_str(&self) -> &str {
match self {
RunMode::Main => "main",
RunMode::Writer => "writer",
}
}
}
8 changes: 4 additions & 4 deletions src/ui/ask_outfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tracing::debug;

use crate::{
compression::{CompressionArg, CompressionFormat, DecompressError, AVAILABLE_FORMATS},
device::{enumerate_devices, BurnTarget, Removable},
device::{enumerate_devices, Removable, WriteTarget},
ui::cli::BurnArgs,
};

Expand Down Expand Up @@ -55,7 +55,7 @@ pub fn ask_compression(args: &BurnArgs) -> anyhow::Result<CompressionFormat> {
}

#[tracing::instrument(skip_all)]
pub fn ask_outfile(args: &BurnArgs) -> anyhow::Result<BurnTarget> {
pub fn ask_outfile(args: &BurnArgs) -> anyhow::Result<WriteTarget> {
let mut show_all_disks = args.show_all_disks;

loop {
Expand Down Expand Up @@ -101,7 +101,7 @@ pub fn confirm_write(args: &BurnArgs, begin_params: &BeginParams) -> Result<bool
}

enum ListOption {
Device(BurnTarget),
Device(WriteTarget),
Refresh,
RetryWithShowAll(bool),
}
Expand Down Expand Up @@ -132,7 +132,7 @@ impl fmt::Display for ListOption {

#[tracing::instrument]
fn enumerate_options(show_all_disks: bool) -> anyhow::Result<Vec<ListOption>> {
let mut burn_targets: Vec<BurnTarget> = enumerate_devices()
let mut burn_targets: Vec<WriteTarget> = enumerate_devices()
.filter(|d| show_all_disks || d.removable == Removable::Yes)
.collect();

Expand Down
14 changes: 9 additions & 5 deletions src/ui/burn/fancy/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ use ratatui::{
use tokio::{select, time};

use crate::{
burn::{self, state_tracking::ChildState, Handle},
logging::get_bug_report_msg,
ui::burn::{fancy::state::UIEvent, start::BeginParams},
writer_process::{self, state_tracking::WriterState, Handle},
};

use super::{
Expand All @@ -27,7 +27,7 @@ where
{
terminal: &'a mut Terminal<B>,
events: EventStream,
handle: Option<burn::Handle>,
handle: Option<writer_process::Handle>,
state: State,
}

Expand All @@ -36,7 +36,11 @@ where
B: Backend,
{
#[tracing::instrument(skip_all)]
pub fn new(params: &BeginParams, handle: burn::Handle, terminal: &'a mut Terminal<B>) -> Self {
pub fn new(
params: &BeginParams,
handle: writer_process::Handle,
terminal: &'a mut Terminal<B>,
) -> Self {
let input_file_bytes = handle.initial_info().input_file_bytes;
Self {
terminal,
Expand Down Expand Up @@ -137,12 +141,12 @@ pub fn draw(
let progress_bar = make_progress_bar(&state.child);

let final_time = match state.child {
ChildState::Finished { finish_time, .. } => finish_time,
WriterState::Finished { finish_time, .. } => finish_time,
_ => Instant::now(),
};

let error = match &state.child {
ChildState::Finished { error, .. } => error.as_ref(),
WriterState::Finished { error, .. } => error.as_ref(),
_ => None,
};

Expand Down
6 changes: 3 additions & 3 deletions src/ui/burn/fancy/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use tracing::info;

use crate::{
burn::{ipc::StatusMessage, state_tracking::ChildState},
ui::burn::start::BeginParams,
writer_process::{ipc::StatusMessage, state_tracking::WriterState},
};

use super::widgets::UIState;
Expand All @@ -21,7 +21,7 @@ pub enum UIEvent {
pub struct State {
pub input_filename: String,
pub target_filename: String,
pub child: ChildState,
pub child: WriterState,
pub ui_state: UIState,
}

Expand All @@ -31,7 +31,7 @@ impl State {
input_filename: params.input_file.to_string_lossy().to_string(),
target_filename: params.target.devnode.to_string_lossy().to_string(),
ui_state: UIState::default(),
child: ChildState::initial(now, !params.compression.is_identity(), input_file_bytes),
child: WriterState::initial(now, !params.compression.is_identity(), input_file_bytes),
}
}

Expand Down
20 changes: 10 additions & 10 deletions src/ui/burn/fancy/widgets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@ use ratatui::{
Frame,
};

use crate::burn::state_tracking::ChildState;
use crate::writer_process::state_tracking::WriterState;

#[derive(Debug, PartialEq, Clone)]
pub struct UIState {
graph_max_speed: f64,
}

pub fn make_progress_bar(state: &ChildState) -> StateProgressBar {
pub fn make_progress_bar(state: &WriterState) -> StateProgressBar {
match state {
ChildState::Burning(st) => StateProgressBar {
WriterState::Writing(st) => StateProgressBar {
bytes_written: st.write_hist.bytes_encountered(),
label_state: "Burning...",
style: Style::default().fg(Color::Yellow),
ratio: st.approximate_ratio(),
display_total_bytes: st.total_raw_bytes,
},
ChildState::Verifying {
WriterState::Verifying {
verify_hist,
total_write_bytes,
..
Expand All @@ -36,7 +36,7 @@ pub fn make_progress_bar(state: &ChildState) -> StateProgressBar {
"Verifying...",
Style::default().fg(Color::Blue).bg(Color::Yellow),
),
ChildState::Finished {
WriterState::Finished {
write_hist,
error,
total_write_bytes,
Expand All @@ -57,7 +57,7 @@ pub fn make_progress_bar(state: &ChildState) -> StateProgressBar {
impl UIState {
pub fn draw_speed_chart(
&mut self,
state: &ChildState,
state: &WriterState,
frame: &mut Frame<'_>,
area: Rect,
final_time: Instant,
Expand Down Expand Up @@ -200,7 +200,7 @@ impl Default for UIState {
pub fn make_info_table<'a>(
input_filename: &'a str,
target_filename: &'a str,
state: &'a ChildState,
state: &'a WriterState,
) -> Table<'a> {
let wdata = state.write_hist();

Expand All @@ -214,13 +214,13 @@ pub fn make_info_table<'a>(
];

match &state {
ChildState::Burning(st) => {
WriterState::Writing(st) => {
rows.push(Row::new([
Cell::from("ETA Write"),
Cell::from(format!("{}", st.eta_write())),
]));
}
ChildState::Verifying {
WriterState::Verifying {
verify_hist: vdata,
total_write_bytes,
..
Expand All @@ -234,7 +234,7 @@ pub fn make_info_table<'a>(
Cell::from(format!("{}", vdata.estimated_time_left(*total_write_bytes))),
]));
}
ChildState::Finished {
WriterState::Finished {
verify_hist: vdata, ..
} => {
if let Some(vdata) = vdata {
Expand Down
Loading

0 comments on commit 1bd71f7

Please sign in to comment.