2019-04-04 06:58:39 +00:00
|
|
|
use failure::*;
|
|
|
|
use lazy_static::lazy_static;
|
|
|
|
use chrono::Local;
|
|
|
|
|
|
|
|
use tokio::sync::oneshot;
|
|
|
|
use futures::*;
|
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use std::collections::HashMap;
|
2019-04-08 16:43:26 +00:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
2019-04-05 10:37:35 +00:00
|
|
|
use std::io::{BufRead, BufReader};
|
|
|
|
use std::fs::File;
|
2019-04-11 05:55:02 +00:00
|
|
|
use std::panic::UnwindSafe;
|
|
|
|
|
2019-04-10 10:42:24 +00:00
|
|
|
use serde_json::{json, Value};
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-08-03 11:05:38 +00:00
|
|
|
use proxmox::tools::{
|
|
|
|
try_block,
|
2019-12-18 10:05:30 +00:00
|
|
|
fs::{create_path, replace_file, CreateOptions},
|
2019-08-03 11:05:38 +00:00
|
|
|
};
|
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
use super::UPID;
|
|
|
|
|
2019-08-03 11:05:38 +00:00
|
|
|
use crate::tools::FileLogger;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-08-21 10:28:24 +00:00
|
|
|
macro_rules! PROXMOX_BACKUP_VAR_RUN_DIR_M { () => ("/run/proxmox-backup") }
|
2019-04-08 16:43:26 +00:00
|
|
|
macro_rules! PROXMOX_BACKUP_LOG_DIR_M { () => ("/var/log/proxmox-backup") }
|
|
|
|
macro_rules! PROXMOX_BACKUP_TASK_DIR_M { () => (concat!( PROXMOX_BACKUP_LOG_DIR_M!(), "/tasks")) }
|
|
|
|
|
2019-04-09 10:15:06 +00:00
|
|
|
pub const PROXMOX_BACKUP_VAR_RUN_DIR: &str = PROXMOX_BACKUP_VAR_RUN_DIR_M!();
|
2019-04-08 16:43:26 +00:00
|
|
|
pub const PROXMOX_BACKUP_LOG_DIR: &str = PROXMOX_BACKUP_LOG_DIR_M!();
|
|
|
|
pub const PROXMOX_BACKUP_TASK_DIR: &str = PROXMOX_BACKUP_TASK_DIR_M!();
|
|
|
|
pub const PROXMOX_BACKUP_TASK_LOCK_FN: &str = concat!(PROXMOX_BACKUP_TASK_DIR_M!(), "/.active.lock");
|
|
|
|
pub const PROXMOX_BACKUP_ACTIVE_TASK_FN: &str = concat!(PROXMOX_BACKUP_TASK_DIR_M!(), "/active");
|
2019-04-04 06:58:39 +00:00
|
|
|
|
|
|
|
lazy_static! {
|
|
|
|
static ref WORKER_TASK_LIST: Mutex<HashMap<usize, Arc<WorkerTask>>> = Mutex::new(HashMap::new());
|
2019-04-09 10:15:06 +00:00
|
|
|
|
|
|
|
static ref MY_PID: i32 = unsafe { libc::getpid() };
|
2019-08-03 14:26:44 +00:00
|
|
|
static ref MY_PID_PSTART: u64 = proxmox::sys::linux::procfs::read_proc_pid_stat(*MY_PID).unwrap().starttime;
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
/// Test if the task is still running
|
|
|
|
pub fn worker_is_active(upid: &UPID) -> bool {
|
2019-04-07 11:51:46 +00:00
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
if (upid.pid == *MY_PID) && (upid.pstart == *MY_PID_PSTART) {
|
2019-10-26 09:36:01 +00:00
|
|
|
WORKER_TASK_LIST.lock().unwrap().contains_key(&upid.task_id)
|
2019-04-08 16:43:26 +00:00
|
|
|
} else {
|
2019-10-26 09:36:01 +00:00
|
|
|
use proxmox::sys::linux::procfs;
|
|
|
|
procfs::check_process_running_pstart(upid.pid, upid.pstart).is_some()
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-09 10:15:06 +00:00
|
|
|
pub fn create_task_control_socket() -> Result<(), Error> {
|
|
|
|
|
|
|
|
let socketname = format!(
|
2019-04-10 07:03:17 +00:00
|
|
|
"\0{}/proxmox-task-control-{}.sock", PROXMOX_BACKUP_VAR_RUN_DIR, *MY_PID);
|
2019-04-09 10:15:06 +00:00
|
|
|
|
2019-04-10 07:03:17 +00:00
|
|
|
let control_future = super::create_control_socket(socketname, |param| {
|
2019-04-09 10:15:06 +00:00
|
|
|
let param = param.as_object()
|
2019-10-26 09:36:01 +00:00
|
|
|
.ok_or_else(|| format_err!("unable to parse parameters (expected json object)"))?;
|
2019-04-10 10:42:24 +00:00
|
|
|
if param.keys().count() != 2 { bail!("wrong number of parameters"); }
|
2019-04-09 10:15:06 +00:00
|
|
|
|
|
|
|
let command = param.get("command")
|
2019-10-26 09:36:01 +00:00
|
|
|
.ok_or_else(|| format_err!("unable to parse parameters (missing command)"))?;
|
2019-04-09 10:15:06 +00:00
|
|
|
|
|
|
|
// this is the only command for now
|
|
|
|
if command != "abort-task" { bail!("got unknown command '{}'", command); }
|
|
|
|
|
|
|
|
let upid_str = param["upid"].as_str()
|
2019-10-26 09:36:01 +00:00
|
|
|
.ok_or_else(|| format_err!("unable to parse parameters (missing upid)"))?;
|
2019-04-09 10:15:06 +00:00
|
|
|
|
|
|
|
let upid = upid_str.parse::<UPID>()?;
|
|
|
|
|
|
|
|
if !((upid.pid == *MY_PID) && (upid.pstart == *MY_PID_PSTART)) {
|
|
|
|
bail!("upid does not belong to this process");
|
|
|
|
}
|
|
|
|
|
|
|
|
let hash = WORKER_TASK_LIST.lock().unwrap();
|
|
|
|
if let Some(ref worker) = hash.get(&upid.task_id) {
|
|
|
|
worker.request_abort();
|
|
|
|
} else {
|
|
|
|
// assume task is already stopped
|
|
|
|
}
|
|
|
|
Ok(Value::Null)
|
|
|
|
})?;
|
|
|
|
|
|
|
|
tokio::spawn(control_future);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2019-04-10 10:42:24 +00:00
|
|
|
pub fn abort_worker_async(upid: UPID) {
|
2019-08-27 07:18:39 +00:00
|
|
|
tokio::spawn(async move {
|
|
|
|
if let Err(err) = abort_worker(upid).await {
|
2019-04-10 10:42:24 +00:00
|
|
|
eprintln!("abort worker failed - {}", err);
|
|
|
|
}
|
2019-08-27 07:18:39 +00:00
|
|
|
});
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
|
|
|
|
2019-08-27 07:18:39 +00:00
|
|
|
pub fn abort_worker(upid: UPID) -> impl Future<Output = Result<(), Error>> {
|
2019-04-10 10:42:24 +00:00
|
|
|
|
|
|
|
let target_pid = upid.pid;
|
|
|
|
|
|
|
|
let socketname = format!(
|
|
|
|
"\0{}/proxmox-task-control-{}.sock", PROXMOX_BACKUP_VAR_RUN_DIR, target_pid);
|
|
|
|
|
|
|
|
let cmd = json!({
|
|
|
|
"command": "abort-task",
|
|
|
|
"upid": upid.to_string(),
|
|
|
|
});
|
|
|
|
|
2019-08-27 07:18:39 +00:00
|
|
|
super::send_command(socketname, cmd).map_ok(|_| ())
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
|
|
|
|
2019-04-05 10:37:35 +00:00
|
|
|
fn parse_worker_status_line(line: &str) -> Result<(String, UPID, Option<(i64, String)>), Error> {
|
|
|
|
|
|
|
|
let data = line.splitn(3, ' ').collect::<Vec<&str>>();
|
|
|
|
|
|
|
|
let len = data.len();
|
|
|
|
|
|
|
|
match len {
|
|
|
|
1 => Ok((data[0].to_owned(), data[0].parse::<UPID>()?, None)),
|
|
|
|
3 => {
|
|
|
|
let endtime = i64::from_str_radix(data[1], 16)?;
|
|
|
|
Ok((data[0].to_owned(), data[0].parse::<UPID>()?, Some((endtime, data[2].to_owned()))))
|
|
|
|
}
|
|
|
|
_ => bail!("wrong number of components"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-06 15:53:12 +00:00
|
|
|
/// Create task log directory with correct permissions
|
2019-04-09 10:15:06 +00:00
|
|
|
pub fn create_task_log_dirs() -> Result<(), Error> {
|
2019-04-06 15:53:12 +00:00
|
|
|
|
|
|
|
try_block!({
|
2019-08-03 11:05:38 +00:00
|
|
|
let (backup_uid, backup_gid) = crate::tools::getpwnam_ugid("backup")?;
|
2019-08-21 10:21:56 +00:00
|
|
|
let opts = CreateOptions::new()
|
|
|
|
.owner(nix::unistd::Uid::from_raw(backup_uid))
|
|
|
|
.group(nix::unistd::Gid::from_raw(backup_gid));
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2019-08-21 10:21:56 +00:00
|
|
|
create_path(PROXMOX_BACKUP_LOG_DIR, None, Some(opts.clone()))?;
|
|
|
|
create_path(PROXMOX_BACKUP_TASK_DIR, None, Some(opts.clone()))?;
|
|
|
|
create_path(PROXMOX_BACKUP_VAR_RUN_DIR, None, Some(opts))?;
|
2019-04-06 15:53:12 +00:00
|
|
|
Ok(())
|
|
|
|
}).map_err(|err: Error| format_err!("unable to create task log dir - {}", err))?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2019-04-09 13:11:48 +00:00
|
|
|
/// Read exits status from task log file
|
|
|
|
pub fn upid_read_status(upid: &UPID) -> Result<String, Error> {
|
2019-04-05 10:37:35 +00:00
|
|
|
let mut status = String::from("unknown");
|
|
|
|
|
2019-04-07 11:51:46 +00:00
|
|
|
let path = upid.log_path();
|
2019-04-05 10:37:35 +00:00
|
|
|
|
2019-04-09 13:11:48 +00:00
|
|
|
let mut file = File::open(path)?;
|
|
|
|
|
|
|
|
/// speedup - only read tail
|
|
|
|
use std::io::Seek;
|
|
|
|
use std::io::SeekFrom;
|
|
|
|
let _ = file.seek(SeekFrom::End(-8192)); // ignore errors
|
|
|
|
|
2019-04-05 10:37:35 +00:00
|
|
|
let reader = BufReader::new(file);
|
|
|
|
|
|
|
|
for line in reader.lines() {
|
|
|
|
let line = line?;
|
|
|
|
|
|
|
|
let mut iter = line.splitn(2, ": TASK ");
|
|
|
|
if iter.next() == None { continue; }
|
|
|
|
match iter.next() {
|
|
|
|
None => continue,
|
|
|
|
Some(rest) => {
|
|
|
|
if rest == "OK" {
|
|
|
|
status = String::from(rest);
|
|
|
|
} else if rest.starts_with("ERROR: ") {
|
2019-04-15 06:37:13 +00:00
|
|
|
status = String::from(&rest[7..]);
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(status)
|
|
|
|
}
|
|
|
|
|
2019-04-06 08:17:11 +00:00
|
|
|
/// Task details including parsed UPID
|
|
|
|
///
|
|
|
|
/// If there is no `state`, the task is still running.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct TaskListInfo {
|
|
|
|
/// The parsed UPID
|
|
|
|
pub upid: UPID,
|
|
|
|
/// UPID string representation
|
|
|
|
pub upid_str: String,
|
|
|
|
/// Task `(endtime, status)` if already finished
|
|
|
|
///
|
|
|
|
/// The `status` ise iether `unknown`, `OK`, or `ERROR: ...`
|
|
|
|
pub state: Option<(i64, String)>, // endtime, status
|
|
|
|
}
|
|
|
|
|
|
|
|
// atomically read/update the task list, update status of finished tasks
|
|
|
|
// new_upid is added to the list when specified.
|
|
|
|
// Returns a sorted list of known tasks,
|
|
|
|
fn update_active_workers(new_upid: Option<&UPID>) -> Result<Vec<TaskListInfo>, Error> {
|
2019-04-05 10:37:35 +00:00
|
|
|
|
2019-08-03 11:05:38 +00:00
|
|
|
let (backup_uid, backup_gid) = crate::tools::getpwnam_ugid("backup")?;
|
2019-12-18 10:05:30 +00:00
|
|
|
let uid = nix::unistd::Uid::from_raw(backup_uid);
|
|
|
|
let gid = nix::unistd::Gid::from_raw(backup_gid);
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2019-08-03 11:05:38 +00:00
|
|
|
let lock = crate::tools::open_file_locked(PROXMOX_BACKUP_TASK_LOCK_FN, std::time::Duration::new(10, 0))?;
|
2019-12-18 10:05:30 +00:00
|
|
|
nix::unistd::chown(PROXMOX_BACKUP_TASK_LOCK_FN, Some(uid), Some(gid))?;
|
2019-04-05 10:37:35 +00:00
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
let reader = match File::open(PROXMOX_BACKUP_ACTIVE_TASK_FN) {
|
2019-04-05 10:37:35 +00:00
|
|
|
Ok(f) => Some(BufReader::new(f)),
|
|
|
|
Err(err) => {
|
|
|
|
if err.kind() == std::io::ErrorKind::NotFound {
|
|
|
|
None
|
|
|
|
} else {
|
2019-04-08 16:43:26 +00:00
|
|
|
bail!("unable to open active worker {:?} - {}", PROXMOX_BACKUP_ACTIVE_TASK_FN, err);
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut active_list = vec![];
|
|
|
|
let mut finish_list = vec![];
|
|
|
|
|
|
|
|
if let Some(lines) = reader.map(|r| r.lines()) {
|
|
|
|
|
|
|
|
for line in lines {
|
|
|
|
let line = line?;
|
|
|
|
match parse_worker_status_line(&line) {
|
|
|
|
Err(err) => bail!("unable to parse active worker status '{}' - {}", line, err),
|
|
|
|
Ok((upid_str, upid, state)) => {
|
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
let running = worker_is_active(&upid);
|
2019-04-05 10:37:35 +00:00
|
|
|
|
|
|
|
if running {
|
|
|
|
active_list.push(TaskListInfo { upid, upid_str, state: None });
|
|
|
|
} else {
|
|
|
|
match state {
|
|
|
|
None => {
|
|
|
|
println!("Detected stoped UPID {}", upid_str);
|
2019-10-26 09:36:01 +00:00
|
|
|
let status = upid_read_status(&upid)
|
|
|
|
.unwrap_or_else(|_| String::from("unknown"));
|
2019-04-05 10:37:35 +00:00
|
|
|
finish_list.push(TaskListInfo {
|
|
|
|
upid, upid_str, state: Some((Local::now().timestamp(), status))
|
|
|
|
});
|
|
|
|
}
|
|
|
|
Some((endtime, status)) => {
|
|
|
|
finish_list.push(TaskListInfo {
|
|
|
|
upid, upid_str, state: Some((endtime, status))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(upid) = new_upid {
|
|
|
|
active_list.push(TaskListInfo { upid: upid.clone(), upid_str: upid.to_string(), state: None });
|
|
|
|
}
|
|
|
|
|
|
|
|
// assemble list without duplicates
|
|
|
|
// we include all active tasks,
|
|
|
|
// and fill up to 1000 entries with finished tasks
|
|
|
|
|
|
|
|
let max = 1000;
|
|
|
|
|
|
|
|
let mut task_hash = HashMap::new();
|
|
|
|
|
|
|
|
for info in active_list {
|
|
|
|
task_hash.insert(info.upid_str.clone(), info);
|
|
|
|
}
|
|
|
|
|
|
|
|
for info in finish_list {
|
|
|
|
if task_hash.len() > max { break; }
|
|
|
|
if !task_hash.contains_key(&info.upid_str) {
|
|
|
|
task_hash.insert(info.upid_str.clone(), info);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-06 08:17:11 +00:00
|
|
|
let mut task_list: Vec<TaskListInfo> = vec![];
|
|
|
|
for (_, info) in task_hash { task_list.push(info); }
|
|
|
|
|
2019-04-11 07:43:33 +00:00
|
|
|
task_list.sort_unstable_by(|b, a| { // lastest on top
|
2019-04-05 10:37:35 +00:00
|
|
|
match (&a.state, &b.state) {
|
|
|
|
(Some(s1), Some(s2)) => s1.0.cmp(&s2.0),
|
|
|
|
(Some(_), None) => std::cmp::Ordering::Less,
|
|
|
|
(None, Some(_)) => std::cmp::Ordering::Greater,
|
|
|
|
_ => a.upid.starttime.cmp(&b.upid.starttime),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut raw = String::new();
|
|
|
|
for info in &task_list {
|
|
|
|
if let Some((endtime, status)) = &info.state {
|
|
|
|
raw.push_str(&format!("{} {:08X} {}\n", info.upid_str, endtime, status));
|
|
|
|
} else {
|
|
|
|
raw.push_str(&info.upid_str);
|
|
|
|
raw.push('\n');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-18 10:05:30 +00:00
|
|
|
replace_file(
|
|
|
|
PROXMOX_BACKUP_ACTIVE_TASK_FN,
|
|
|
|
raw.as_bytes(),
|
|
|
|
CreateOptions::new()
|
|
|
|
.owner(uid)
|
|
|
|
.group(gid),
|
|
|
|
)?;
|
2019-04-05 10:37:35 +00:00
|
|
|
|
|
|
|
drop(lock);
|
|
|
|
|
2019-04-06 08:17:11 +00:00
|
|
|
Ok(task_list)
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
|
|
|
|
2019-04-06 08:17:11 +00:00
|
|
|
/// Returns a sorted list of known tasks
|
|
|
|
///
|
|
|
|
/// The list is sorted by `(starttime, endtime)` in ascending order
|
|
|
|
pub fn read_task_list() -> Result<Vec<TaskListInfo>, Error> {
|
|
|
|
update_active_workers(None)
|
|
|
|
}
|
2019-04-05 10:37:35 +00:00
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Launch long running worker tasks.
|
|
|
|
///
|
|
|
|
/// A worker task can either be a whole thread, or a simply tokio
|
|
|
|
/// task/future. Each task can `log()` messages, which are stored
|
|
|
|
/// persistently to files. Task should poll the `abort_requested`
|
|
|
|
/// flag, and stop execution when requested.
|
2019-04-04 06:58:39 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct WorkerTask {
|
|
|
|
upid: UPID,
|
|
|
|
data: Mutex<WorkerTaskData>,
|
|
|
|
abort_requested: AtomicBool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for WorkerTask {
|
|
|
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
|
|
self.upid.fmt(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct WorkerTaskData {
|
|
|
|
logger: FileLogger,
|
|
|
|
progress: f64, // 0..1
|
2019-04-15 07:38:05 +00:00
|
|
|
pub abort_listeners: Vec<oneshot::Sender<()>>,
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for WorkerTask {
|
|
|
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
println!("unregister worker");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WorkerTask {
|
|
|
|
|
2019-04-15 05:49:03 +00:00
|
|
|
pub fn new(worker_type: &str, worker_id: Option<String>, username: &str, to_stdout: bool) -> Result<Arc<Self>, Error> {
|
2019-04-04 06:58:39 +00:00
|
|
|
println!("register worker");
|
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
let upid = UPID::new(worker_type, worker_id, username)?;
|
|
|
|
let task_id = upid.task_id;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
let mut path = std::path::PathBuf::from(PROXMOX_BACKUP_TASK_DIR);
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2019-04-04 06:58:39 +00:00
|
|
|
path.push(format!("{:02X}", upid.pstart % 256));
|
|
|
|
|
2019-08-03 11:05:38 +00:00
|
|
|
let (backup_uid, backup_gid) = crate::tools::getpwnam_ugid("backup")?;
|
2019-08-21 10:21:56 +00:00
|
|
|
let uid = nix::unistd::Uid::from_raw(backup_uid);
|
|
|
|
let gid = nix::unistd::Gid::from_raw(backup_gid);
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2019-08-21 10:21:56 +00:00
|
|
|
create_path(&path, None, Some(CreateOptions::new().owner(uid).group(gid)))?;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
|
|
|
path.push(upid.to_string());
|
|
|
|
|
|
|
|
println!("FILE: {:?}", path);
|
|
|
|
|
2019-04-06 15:53:12 +00:00
|
|
|
let logger = FileLogger::new(&path, to_stdout)?;
|
2019-08-21 10:21:56 +00:00
|
|
|
nix::unistd::chown(&path, Some(uid), Some(gid))?;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-04-05 10:37:35 +00:00
|
|
|
update_active_workers(Some(&upid))?;
|
|
|
|
|
2019-04-04 06:58:39 +00:00
|
|
|
let worker = Arc::new(Self {
|
2019-09-11 10:06:59 +00:00
|
|
|
upid,
|
2019-04-04 06:58:39 +00:00
|
|
|
abort_requested: AtomicBool::new(false),
|
|
|
|
data: Mutex::new(WorkerTaskData {
|
|
|
|
logger,
|
|
|
|
progress: 0.0,
|
2019-04-15 07:38:05 +00:00
|
|
|
abort_listeners: vec![],
|
2019-04-04 06:58:39 +00:00
|
|
|
}),
|
|
|
|
});
|
|
|
|
|
2019-04-08 10:21:29 +00:00
|
|
|
let mut hash = WORKER_TASK_LIST.lock().unwrap();
|
|
|
|
|
|
|
|
hash.insert(task_id, worker.clone());
|
|
|
|
super::set_worker_count(hash.len());
|
2019-04-04 06:58:39 +00:00
|
|
|
|
|
|
|
Ok(worker)
|
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Spawn a new tokio task/future.
|
2019-04-06 09:23:53 +00:00
|
|
|
pub fn spawn<F, T>(
|
|
|
|
worker_type: &str,
|
|
|
|
worker_id: Option<String>,
|
|
|
|
username: &str,
|
|
|
|
to_stdout: bool,
|
|
|
|
f: F,
|
|
|
|
) -> Result<String, Error>
|
2019-04-04 06:58:39 +00:00
|
|
|
where F: Send + 'static + FnOnce(Arc<WorkerTask>) -> T,
|
2019-08-27 07:18:39 +00:00
|
|
|
T: Send + 'static + Future<Output = Result<(), Error>>,
|
2019-04-04 06:58:39 +00:00
|
|
|
{
|
|
|
|
let worker = WorkerTask::new(worker_type, worker_id, username, to_stdout)?;
|
2019-04-06 09:23:53 +00:00
|
|
|
let upid_str = worker.upid.to_string();
|
2019-08-27 07:18:39 +00:00
|
|
|
let f = f(worker.clone());
|
|
|
|
tokio::spawn(async move {
|
|
|
|
let result = f.await;
|
2019-06-25 06:12:25 +00:00
|
|
|
worker.log_result(&result);
|
2019-08-27 07:18:39 +00:00
|
|
|
});
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-04-06 09:23:53 +00:00
|
|
|
Ok(upid_str)
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Create a new worker thread.
|
2019-04-06 09:23:53 +00:00
|
|
|
pub fn new_thread<F>(
|
|
|
|
worker_type: &str,
|
|
|
|
worker_id: Option<String>,
|
|
|
|
username: &str,
|
|
|
|
to_stdout: bool,
|
|
|
|
f: F,
|
|
|
|
) -> Result<String, Error>
|
2019-04-11 05:55:02 +00:00
|
|
|
where F: Send + UnwindSafe + 'static + FnOnce(Arc<WorkerTask>) -> Result<(), Error>
|
2019-04-04 06:58:39 +00:00
|
|
|
{
|
|
|
|
println!("register worker thread");
|
|
|
|
|
|
|
|
let (p, c) = oneshot::channel::<()>();
|
|
|
|
|
|
|
|
let worker = WorkerTask::new(worker_type, worker_id, username, to_stdout)?;
|
2019-04-06 09:23:53 +00:00
|
|
|
let upid_str = worker.upid.to_string();
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-12-19 06:07:39 +00:00
|
|
|
let _child = std::thread::Builder::new().name(upid_str.clone()).spawn(move || {
|
2019-04-11 05:55:02 +00:00
|
|
|
let worker1 = worker.clone();
|
|
|
|
let result = match std::panic::catch_unwind(move || f(worker1)) {
|
|
|
|
Ok(r) => r,
|
|
|
|
Err(panic) => {
|
|
|
|
match panic.downcast::<&str>() {
|
|
|
|
Ok(panic_msg) => {
|
|
|
|
Err(format_err!("worker panicked: {}", panic_msg))
|
|
|
|
}
|
|
|
|
Err(_) => {
|
|
|
|
Err(format_err!("worker panicked: unknown type."))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-06-25 06:12:25 +00:00
|
|
|
worker.log_result(&result);
|
2019-04-04 06:58:39 +00:00
|
|
|
p.send(()).unwrap();
|
|
|
|
});
|
|
|
|
|
2019-08-27 07:18:39 +00:00
|
|
|
tokio::spawn(c.map(|_| ()));
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2019-04-06 09:23:53 +00:00
|
|
|
Ok(upid_str)
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2019-04-15 05:49:03 +00:00
|
|
|
/// Log task result, remove task from running list
|
2019-06-25 06:12:25 +00:00
|
|
|
pub fn log_result(&self, result: &Result<(), Error>) {
|
2019-04-15 05:49:03 +00:00
|
|
|
|
2019-04-05 10:37:35 +00:00
|
|
|
if let Err(err) = result {
|
|
|
|
self.log(&format!("TASK ERROR: {}", err));
|
|
|
|
} else {
|
|
|
|
self.log("TASK OK");
|
|
|
|
}
|
2019-04-15 05:49:03 +00:00
|
|
|
|
|
|
|
WORKER_TASK_LIST.lock().unwrap().remove(&self.upid.task_id);
|
|
|
|
let _ = update_active_workers(None);
|
|
|
|
super::set_worker_count(WORKER_TASK_LIST.lock().unwrap().len());
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Log a message.
|
2019-04-04 06:58:39 +00:00
|
|
|
pub fn log<S: AsRef<str>>(&self, msg: S) {
|
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
data.logger.log(msg);
|
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Set progress indicator
|
2019-04-04 06:58:39 +00:00
|
|
|
pub fn progress(&self, progress: f64) {
|
|
|
|
if progress >= 0.0 && progress <= 1.0 {
|
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
data.progress = progress;
|
|
|
|
} else {
|
|
|
|
// fixme: log!("task '{}': ignoring strange value for progress '{}'", self.upid, progress);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Request abort
|
2019-04-09 10:15:06 +00:00
|
|
|
pub fn request_abort(&self) {
|
2019-04-10 11:54:28 +00:00
|
|
|
eprintln!("set abort flag for worker {}", self.upid);
|
2019-04-04 06:58:39 +00:00
|
|
|
self.abort_requested.store(true, Ordering::SeqCst);
|
2019-04-15 07:38:05 +00:00
|
|
|
// noitify listeners
|
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
loop {
|
|
|
|
match data.abort_listeners.pop() {
|
|
|
|
None => { break; },
|
|
|
|
Some(ch) => {
|
|
|
|
let _ = ch.send(()); // ignore erros here
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Test if abort was requested.
|
2019-04-04 06:58:39 +00:00
|
|
|
pub fn abort_requested(&self) -> bool {
|
|
|
|
self.abort_requested.load(Ordering::SeqCst)
|
|
|
|
}
|
|
|
|
|
2019-04-06 07:17:25 +00:00
|
|
|
/// Fail if abort was requested.
|
2019-04-04 06:58:39 +00:00
|
|
|
pub fn fail_on_abort(&self) -> Result<(), Error> {
|
|
|
|
if self.abort_requested() {
|
|
|
|
bail!("task '{}': abort requested - aborting task", self.upid);
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2019-04-15 07:38:05 +00:00
|
|
|
|
|
|
|
/// Get a future which resolves on task abort
|
|
|
|
pub fn abort_future(&self) -> oneshot::Receiver<()> {
|
|
|
|
let (tx, rx) = oneshot::channel::<()>();
|
|
|
|
|
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
if self.abort_requested() {
|
|
|
|
let _ = tx.send(());
|
|
|
|
} else {
|
|
|
|
data.abort_listeners.push(tx);
|
|
|
|
}
|
|
|
|
rx
|
|
|
|
}
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|