Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear logfile after it is sent #120

Merged
merged 2 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions src/command/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,11 @@ fn build_result_archive(res: ResultId) -> Result<(), std::io::Error> {
let out_path = format!("./data/{}_{}.zip", res.program_id, res.timestamp);

const MAXIMUM_FILE_SIZE: u64 = 1_000_000;
let _ = truncate_to_size(&log_path, MAXIMUM_FILE_SIZE);
let _ = truncate_to_size(&res_path, MAXIMUM_FILE_SIZE);
let _ = truncate_to_size("log", MAXIMUM_FILE_SIZE);
for path in [&res_path, &log_path, &out_path, &"log".into()] {
if let Ok(true) = truncate_to_size(path, MAXIMUM_FILE_SIZE) {
log::warn!("Truncating {} from {} bytes", path, MAXIMUM_FILE_SIZE);
}
}

let _ = Command::new("zip")
.arg("-0")
Expand All @@ -221,16 +223,19 @@ fn build_result_archive(res: ResultId) -> Result<(), std::io::Error> {
Ok(())
}

/// Truncates the file at `path` to the given size
fn truncate_to_size(path: &str, n_bytes: u64) -> Result<(), std::io::Error> {
/// Truncates the file at `path` to the given size. Returns wether it actually had to truncate.
fn truncate_to_size(path: &str, n_bytes: u64) -> Result<bool, std::io::Error> {
log::info!("Truncating {:?}", &path);
let file = std::fs::File::options().write(true).open(path)?;
let size = file.metadata()?.len();
if size > n_bytes {
log::warn!("Truncating {} from {} bytes", path, size);
file.set_len(n_bytes)?;
file.sync_all()?;
Ok(true)
}
else {
Ok(false)
}
Ok(())
}

/// Stops the currently running student program
Expand Down Expand Up @@ -357,6 +362,7 @@ fn delete_result(res: ResultId) -> CommandResult {
let _ = std::fs::remove_file(res_path);
let _ = std::fs::remove_file(log_path);
let _ = std::fs::remove_file(out_path);
let _ = truncate_to_size("log", 0);

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn main() -> ! {
let _ = sl::WriteLogger::init(
sl::LevelFilter::Info,
sl::Config::default(),
std::fs::File::create(&config.log_path).unwrap(),
std::fs::OpenOptions::new().create(true).append(true).open("log").unwrap(),
);

log::info!("Scheduler started");
Expand Down
11 changes: 8 additions & 3 deletions tests/simulation/command_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,23 @@ fn simulate_archive_is_stored_correctly() -> Result<(), std::io::Error> {
let mut cobc_in = serial_port.stdout.take().unwrap();
let mut cobc_out = serial_port.stdin.take().unwrap();

simulate_test_store_archive(&mut cobc_in, &mut cobc_out)?;
simulate_test_store_archive(&mut cobc_in, &mut cobc_out, 1)?;
std::thread::sleep(std::time::Duration::from_millis(400));

assert_eq!(
0,
std::process::Command::new("diff") // check wether the archive was stored correctly
.args(["-yq", "--strip-trailing-cr", "tests/test_data", "tests/tmp/archive_is_stored_correctly/archives/1"])
.args([
"-yq",
"--strip-trailing-cr",
"tests/test_data",
"tests/tmp/archive_is_stored_correctly/archives/1"
])
.status()?
.code()
.unwrap()
);

scheduler.kill()?;
Ok(())
}
}
23 changes: 22 additions & 1 deletion tests/simulation/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,25 @@ fn logfile_is_created() -> Result<(), std::io::Error> {

assert!(std::path::Path::new("./tests/tmp/log_created/log").exists());
Ok(())
}
}

#[test]
fn logfile_is_cleared_after_sent() -> std::io::Result<()> {
let (mut scheduler, mut serial_port) = start_scheduler("log_is_cleared_after_sent")?;
let mut cobc_in = serial_port.stdout.take().unwrap();
let mut cobc_out = serial_port.stdin.take().unwrap();

simulate_test_store_archive(&mut cobc_in, &mut cobc_out, 1)?;
simulate_execute_program(&mut cobc_in, &mut cobc_out, 1, 0, 3)?;
std::thread::sleep(std::time::Duration::from_millis(100));
let _ = simulate_return_result(&mut cobc_in, &mut cobc_out, 1, 0)?;
cobc_out.write_all(&CEPPacket::ACK.serialize())?;
std::thread::sleep(std::time::Duration::from_millis(100));

scheduler.kill().unwrap();

let log_metadata = std::fs::metadata("./tests/tmp/log_is_cleared_after_sent/log")?;
assert!(log_metadata.len() < 50, "Logfile is not empty");

Ok(())
}
107 changes: 91 additions & 16 deletions tests/simulation/mod.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
mod logging;
mod command_execution;
mod logging;

use std::{io::Write, process::{Child, Stdio}};
use std::{
fmt::format,
io::{Read, Write},
process::{Child, Stdio},
};

use STS1_EDU_Scheduler::communication::CEPPacket;
use crate::software_tests::common::*;
use STS1_EDU_Scheduler::communication::CEPPacket;

fn get_config_str(unique: &str) -> String {
format!("
format!(
"
uart = \"/tmp/ttySTS1-{}\"
baudrate = 921600
heartbeat_pin = 34
update_pin = 35
heartbeat_freq = 10
log_path = \"log\"
", unique)
",
unique
)
}

pub fn start_scheduler(unique: &str) -> Result<(Child, Child), std::io::Error>{
pub fn start_scheduler(unique: &str) -> Result<(Child, Child), std::io::Error> {
let test_dir = format!("./tests/tmp/{}", unique);
let scheduler_bin = std::fs::canonicalize("./target/release/STS1_EDU_Scheduler")?;
let _ = std::fs::remove_dir_all(&test_dir);
Expand All @@ -32,33 +39,101 @@ pub fn start_scheduler(unique: &str) -> Result<(Child, Child), std::io::Error>{
.spawn()?;
std::thread::sleep(std::time::Duration::from_millis(100));

let scheduler = std::process::Command::new(scheduler_bin)
.current_dir(test_dir)
.spawn().unwrap();
let scheduler =
std::process::Command::new(scheduler_bin).current_dir(test_dir).spawn().unwrap();

Ok((scheduler, serial_port))
}
}

pub fn receive_ack(reader: &mut impl std::io::Read) -> Result<(), std::io::Error> {
let mut buffer = [0; 1];
reader.read_exact(&mut buffer).unwrap();

if buffer[0] == CEPPacket::ACK.serialize()[0] {
Ok(())
}
else {
Err(std::io::Error::new(std::io::ErrorKind::Other, format!("received {:#x} instead of ACK", buffer[0])))
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("received {:#x} instead of ACK", buffer[0]),
))
}
}

pub fn simulate_test_store_archive(cobc_in: &mut impl std::io::Read, cobc_out: &mut impl std::io::Write) -> std::io::Result<()> {
pub fn simulate_test_store_archive(
cobc_in: &mut impl std::io::Read,
cobc_out: &mut impl std::io::Write,
program_id: u16,
) -> std::io::Result<()> {
let archive = std::fs::read("tests/student_program.zip")?;
cobc_out.write_all(&CEPPacket::DATA(store_archive(1)).serialize())?;
cobc_out.write_all(&CEPPacket::DATA(store_archive(program_id)).serialize())?;
receive_ack(cobc_in)?;
cobc_out.write_all(&CEPPacket::DATA(archive).serialize())?;
receive_ack(cobc_in)?;
cobc_out.write_all(&CEPPacket::EOF.serialize())?;
receive_ack(cobc_in)?;
receive_ack(cobc_in)?;

Ok(())
}

pub fn simulate_execute_program(
cobc_in: &mut impl std::io::Read,
cobc_out: &mut impl std::io::Write,
program_id: u16,
timestamp: u32,
timeout: u16,
) -> std::io::Result<()> {
cobc_out
.write_all(&CEPPacket::DATA(execute_program(program_id, timestamp, timeout)).serialize())?;
receive_ack(cobc_in)?;
receive_ack(cobc_in)?;
Ok(())
}

pub fn simulate_return_result(
cobc_in: &mut impl std::io::Read,
cobc_out: &mut impl std::io::Write,
program_id: u16,
timestamp: u32,
) -> std::io::Result<Vec<u8>> {
cobc_out.write_all(&CEPPacket::DATA(return_result(program_id, timestamp)).serialize())?;
receive_ack(cobc_in)?;

let data = read_multi_data_packets(cobc_in, cobc_out)?;
Ok(data)
}

/// Reads a data packet from input and returns the data content (does not check CRC)
pub fn read_data_packet(input: &mut impl std::io::Read, data: &mut Vec<u8>) -> std::io::Result<()> {
let mut header = [0; 3];
input.read_exact(&mut header)?;
if header[0] != 0x8B {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Expected data header (0x8B), received {:#04x}", header[0]),
));
}

let data_len = u16::from_le_bytes([header[1], header[2]]);
input.take((data_len + 4).into()).read_to_end(data)?;

Ok(())
}

/// Reads a multi packet round without checking the CRC and returns the concatenated contents
pub fn read_multi_data_packets(input: &mut impl std::io::Read, output: &mut impl std::io::Write) -> std::io::Result<Vec<u8>> {
let mut eof_byte = [0; 1];
let mut data = Vec::new();
loop {
read_data_packet(input, &mut data)?;
output.write_all(&CEPPacket::ACK.serialize())?;

input.read_exact(&mut eof_byte)?;
if eof_byte[0] == CEPPacket::EOF.serialize()[0] {
break;
}
}

output.write_all(&CEPPacket::ACK.serialize())?;
Ok(data)
}