pueue/shared/state.rs

359 lines
12 KiB
Rust
Raw Normal View History

2020-10-04 16:14:41 +00:00
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use anyhow::Result;
use chrono::prelude::*;
use log::{debug, error, info};
use serde_derive::{Deserialize, Serialize};
2019-11-11 14:59:01 +00:00
2019-11-30 15:59:42 +00:00
use crate::settings::Settings;
2020-04-26 14:23:30 +00:00
use crate::task::{Task, TaskResult, TaskStatus};
2019-11-11 14:59:01 +00:00
pub type SharedState = Arc<Mutex<State>>;
2020-05-10 22:49:51 +00:00
#[derive(Clone, Debug, Deserialize, Serialize)]
2019-11-11 14:59:01 +00:00
pub struct State {
2019-12-16 03:50:09 +00:00
max_id: usize,
pub settings: Settings,
2019-11-27 21:59:12 +00:00
pub running: bool,
2019-12-16 03:50:09 +00:00
pub tasks: BTreeMap<usize, Task>,
2020-05-10 22:49:51 +00:00
/// Represents whether the group is currently paused or running
pub groups: HashMap<String, bool>,
2019-11-11 14:59:01 +00:00
}
impl State {
2019-11-30 15:59:42 +00:00
pub fn new(settings: &Settings) -> State {
2020-05-10 23:30:29 +00:00
// Create a default group state.
2020-05-10 22:49:51 +00:00
let mut groups = HashMap::new();
for group in settings.daemon.groups.keys() {
groups.insert(group.into(), true);
}
2019-12-12 00:55:12 +00:00
let mut state = State {
2019-11-11 22:02:13 +00:00
max_id: 0,
2019-11-30 15:59:42 +00:00
settings: settings.clone(),
2019-11-27 21:59:12 +00:00
running: true,
2019-11-13 23:15:46 +00:00
tasks: BTreeMap::new(),
2020-05-11 17:10:05 +00:00
groups,
2019-11-13 16:29:36 +00:00
};
2019-12-12 00:55:12 +00:00
state.restore();
2020-05-10 22:49:51 +00:00
state.save();
2019-12-12 00:55:12 +00:00
state
2019-11-11 22:02:13 +00:00
}
2019-12-16 03:50:09 +00:00
pub fn add_task(&mut self, mut task: Task) -> usize {
2019-11-13 16:29:26 +00:00
task.id = self.max_id;
2019-11-13 23:15:46 +00:00
self.tasks.insert(self.max_id, task);
2019-11-11 14:59:01 +00:00
self.max_id += 1;
2019-11-30 15:59:42 +00:00
self.save();
2019-11-21 00:14:32 +00:00
self.max_id - 1
2019-11-11 14:59:01 +00:00
}
2019-12-16 03:50:09 +00:00
pub fn change_status(&mut self, id: usize, new_status: TaskStatus) {
2019-11-13 23:15:46 +00:00
if let Some(ref mut task) = self.tasks.get_mut(&id) {
task.status = new_status;
2019-11-30 15:59:42 +00:00
self.save();
2019-11-11 14:59:01 +00:00
};
}
pub fn set_enqueue_at(&mut self, id: usize, enqueue_at: Option<DateTime<Local>>) {
if let Some(ref mut task) = self.tasks.get_mut(&id) {
task.enqueue_at = enqueue_at;
}
}
2020-05-10 23:30:29 +00:00
/// Check if the given group already exists.
/// If it doesn't exist yet, create a state entry and a new settings entry.
2020-05-11 17:10:05 +00:00
pub fn create_group(&mut self, group: &str) -> Result<()> {
if self.settings.daemon.groups.get(group).is_none() {
2020-05-11 00:14:02 +00:00
self.settings.daemon.groups.insert(group.into(), 1);
2020-05-10 22:49:51 +00:00
}
2020-05-11 17:10:05 +00:00
if self.groups.get(group).is_none() {
2020-05-10 22:49:51 +00:00
self.groups.insert(group.into(), true);
}
2020-05-11 00:14:02 +00:00
self.save();
self.settings.save()
}
/// Remove a group.
/// Also go through all tasks and set the removed group to `None`.
2020-05-11 17:10:05 +00:00
pub fn remove_group(&mut self, group: &str) -> Result<()> {
2020-05-11 00:14:02 +00:00
self.settings.daemon.groups.remove(group);
self.groups.remove(group);
// Reset all tasks with removed group to the default
for (_, task) in self.tasks.iter_mut() {
if let Some(group_name) = &task.group {
if group_name == group {
task.group = None;
}
}
}
self.save();
self.settings.save()
2020-05-10 22:49:51 +00:00
}
/// Set the running status for all groups including the default queue
pub fn set_status_for_all_groups(&mut self, status: bool) {
self.running = status;
let keys = self.groups.keys().cloned().collect::<Vec<String>>();
for key in keys {
2020-05-14 12:57:59 +00:00
self.groups.insert(key, status);
}
self.save()
}
2020-05-13 17:11:17 +00:00
/// Get all task ids of a specific group
pub fn task_ids_in_group_with_stati(
2020-05-13 17:11:17 +00:00
&mut self,
group: &Option<String>,
stati: Vec<TaskStatus>,
2020-05-13 17:11:17 +00:00
) -> Vec<usize> {
self.tasks
.iter()
.filter(|(_, task)| stati.contains(&task.status))
2020-05-14 12:54:36 +00:00
.filter(|(_, task)| group == &task.group)
2020-05-13 17:11:17 +00:00
.map(|(id, _)| *id)
.collect()
}
2019-11-21 14:10:24 +00:00
/// This checks, whether the given task_ids are in the specified statuses.
/// The first result is the list of task_ids that match these statuses.
/// The second result is the list of task_ids that don't match these statuses.
2019-11-21 00:14:32 +00:00
///
/// Additionally, a list of task_ids can be specified to only run the check
/// on a subset of all tasks.
2019-11-21 14:11:35 +00:00
pub fn tasks_in_statuses(
&mut self,
statuses: Vec<TaskStatus>,
task_ids: Option<Vec<usize>>,
2019-12-16 03:50:09 +00:00
) -> (Vec<usize>, Vec<usize>) {
2019-11-21 00:14:32 +00:00
let task_ids = match task_ids {
Some(ids) => ids,
None => self.tasks.keys().cloned().collect(),
};
let mut matching = Vec::new();
let mut mismatching = Vec::new();
2019-11-21 14:10:24 +00:00
// Filter all task id's that match the provided statuses.
2019-11-21 00:14:32 +00:00
for task_id in task_ids.iter() {
2020-05-10 23:30:29 +00:00
// Check whether the task exists and save all non-existing task ids.
match self.tasks.get(&task_id) {
None => {
mismatching.push(*task_id);
continue;
}
Some(task) => {
2020-05-10 23:30:29 +00:00
// Check whether the task status matches the specified statuses.
if statuses.contains(&task.status) {
matching.push(*task_id);
} else {
mismatching.push(*task_id);
}
}
};
2019-11-21 00:14:32 +00:00
}
(matching, mismatching)
}
2019-11-21 14:10:24 +00:00
2019-11-25 00:49:31 +00:00
pub fn reset(&mut self) {
self.backup();
2019-11-22 14:30:47 +00:00
self.max_id = 0;
self.tasks = BTreeMap::new();
2020-05-15 15:55:49 +00:00
self.set_status_for_all_groups(true);
2019-11-30 15:59:42 +00:00
}
2020-05-10 23:30:29 +00:00
/// Convenience wrapper around save_to_file.
2019-11-30 15:59:42 +00:00
pub fn save(&mut self) {
self.save_to_file(false);
}
2020-05-10 23:30:29 +00:00
/// Save the current current state in a file with a timestamp.
/// At the same time remove old state logs from the log directory.
/// This function is called, when large changes to the state are applied, e.g. clean/reset.
pub fn backup(&mut self) {
self.save_to_file(true);
2019-12-12 00:55:12 +00:00
if let Err(error) = self.rotate() {
error!("Failed to rotate files: {:?}", error);
};
}
2019-12-12 00:55:12 +00:00
/// Save the current state to disk.
2020-05-10 23:30:29 +00:00
/// We do this to restore in case of a crash.
/// If log == true, the file will be saved with a time stamp.
///
/// In comparison to the daemon -> client communication, the state is saved
2020-05-10 23:30:29 +00:00
/// as JSON for better readability and debug purposes.
2019-12-12 00:55:12 +00:00
fn save_to_file(&mut self, log: bool) {
2019-11-30 15:59:42 +00:00
let serialized = serde_json::to_string(&self);
if let Err(error) = serialized {
error!("Failed to serialize state: {:?}", error);
return;
}
let serialized = serialized.unwrap();
2020-10-15 17:39:50 +00:00
let path = Path::new(&self.settings.shared.pueue_directory);
2020-05-11 17:10:05 +00:00
let (temp, real) = if log {
2019-12-12 00:55:12 +00:00
let path = path.join("log");
let now: DateTime<Utc> = Utc::now();
let time = now.format("%Y-%m-%d_%H-%M-%S");
2020-05-11 17:14:10 +00:00
(
2020-05-15 15:55:49 +00:00
path.join(format!("{}_state.json.partial", time)),
2020-05-11 17:14:10 +00:00
path.join(format!("{}_state.json", time)),
)
} else {
2020-05-11 17:10:05 +00:00
(path.join("state.json.partial"), path.join("state.json"))
};
2020-05-10 23:30:29 +00:00
// Write to temporary log file first, to prevent loss due to crashes.
2019-11-30 15:59:42 +00:00
if let Err(error) = fs::write(&temp, serialized) {
2019-12-14 19:25:11 +00:00
error!(
"Failed to write log to directory. File permissions? Error: {:?}",
error
);
2019-11-30 15:59:42 +00:00
return;
}
2020-05-10 23:30:29 +00:00
// Overwrite the original with the temp file, if everything went fine.
2020-05-15 15:55:49 +00:00
if let Err(error) = fs::rename(&temp, &real) {
2019-12-14 19:25:11 +00:00
error!(
"Failed to overwrite old log file. File permissions? Error: {:?}",
error
);
return;
2019-11-30 15:59:42 +00:00
}
2020-05-15 15:55:49 +00:00
if log {
debug!("State backup created at: {:?}", real);
} else {
debug!("State saved at: {:?}", real);
}
2019-11-22 14:30:47 +00:00
}
2019-11-30 15:59:42 +00:00
2020-05-10 23:30:29 +00:00
/// Restore the last state from a previous session.
/// The state is stored as json in the log directory.
2019-12-12 00:55:12 +00:00
fn restore(&mut self) {
2020-10-15 17:39:50 +00:00
let path = Path::new(&self.settings.shared.pueue_directory).join("state.json");
2019-11-30 15:59:42 +00:00
// Ignore if the file doesn't exist. It doesn't have to.
if !path.exists() {
2019-12-14 19:25:11 +00:00
info!(
"Couldn't find state from previous session at location: {:?}",
path
);
2019-11-30 15:59:42 +00:00
return;
}
info!("Start restoring state");
2019-11-30 15:59:42 +00:00
2020-05-10 23:30:29 +00:00
// Try to load the file.
2019-11-30 15:59:42 +00:00
let data = fs::read_to_string(&path);
if let Err(error) = data {
error!("Failed to read previous state log: {:?}", error);
return;
}
let data = data.unwrap();
2020-05-10 23:30:29 +00:00
// Try to deserialize the state file.
2019-11-30 15:59:42 +00:00
let deserialized: Result<State, serde_json::error::Error> = serde_json::from_str(&data);
if let Err(error) = deserialized {
error!("Failed to deserialize previous state log: {:?}", error);
return;
}
let mut state = deserialized.unwrap();
2020-05-10 22:49:51 +00:00
// Restore the state from the file.
// While restoring the tasks, check for any invalid/broken stati.
for (task_id, task) in state.tasks.iter_mut() {
2020-05-10 22:49:51 +00:00
// Handle ungraceful shutdowns while executing tasks.
if task.status == TaskStatus::Running || task.status == TaskStatus::Paused {
2020-03-27 12:36:05 +00:00
info!(
"Setting task {} with previous status {:?} to new status {:?}",
task.id,
task.status,
2020-04-26 14:23:30 +00:00
TaskResult::Killed
2020-03-27 12:36:05 +00:00
);
2020-04-26 14:23:30 +00:00
task.status = TaskStatus::Done;
task.result = Some(TaskResult::Killed);
}
2020-05-10 22:49:51 +00:00
// Crash during editing of the task command.
if task.status == TaskStatus::Locked {
task.status = TaskStatus::Stashed;
}
2020-05-10 22:49:51 +00:00
// If there are any queued tasks, pause the daemon.
// This should prevent any unwanted execution of tasks due to a system crash.
if task.status == TaskStatus::Queued {
info!("Pausing daemon to prevent unwanted execution of previous tasks");
state.running = false;
}
2019-11-30 15:59:42 +00:00
self.tasks.insert(*task_id, task.clone());
}
2020-05-10 22:49:51 +00:00
if !self.running {
// If the daemon isn't running, stop all groups.
for group in self.settings.daemon.groups.keys() {
self.groups.insert(group.into(), false);
}
} else {
// If the daemon running, apply all running group states from the previous state.
for (group, running) in state.groups.iter() {
if self.groups.contains_key(group) {
self.groups.insert(group.into(), *running);
}
}
}
2020-05-10 23:39:10 +00:00
// Go trough all tasks and set all groups that are no longer
// listed in the configuration file to the default.
for (_, task) in self.tasks.iter_mut() {
if let Some(group) = &task.group {
if !self.groups.contains_key(group) {
task.group = None;
}
}
}
2019-11-30 15:59:42 +00:00
self.running = state.running;
self.max_id = state.max_id;
}
2020-05-10 23:30:29 +00:00
/// Remove old logs that aren't needed any longer.
2019-12-12 00:55:12 +00:00
fn rotate(&mut self) -> Result<()> {
2020-10-15 17:39:50 +00:00
let path = Path::new(&self.settings.shared.pueue_directory);
2019-12-12 00:55:12 +00:00
let path = path.join("log");
2020-05-10 22:49:51 +00:00
// Get all log files in the directory with their respective system time.
2019-12-12 00:55:12 +00:00
let mut entries: BTreeMap<SystemTime, PathBuf> = BTreeMap::new();
let mut directory_list = fs::read_dir(path)?;
while let Some(Ok(entry)) = directory_list.next() {
let path = entry.path();
let metadata = entry.metadata()?;
let time = metadata.modified()?;
entries.insert(time, path);
}
2020-05-10 22:49:51 +00:00
// Remove all files above the threshold.
// Old files are removed first (implictly by the BTree order).
2019-12-12 00:55:12 +00:00
let mut number_entries = entries.len();
let mut iter = entries.iter();
while number_entries > 10 {
if let Some((_, path)) = iter.next() {
fs::remove_file(path)?;
number_entries -= 1;
}
}
Ok(())
}
2019-11-11 14:59:01 +00:00
}