2020-09-28 13:32:08 +00:00
|
|
|
use std::collections::{HashMap, VecDeque};
|
2019-04-05 10:37:35 +00:00
|
|
|
use std::fs::File;
|
2021-09-22 06:44:48 +00:00
|
|
|
use std::path::PathBuf;
|
2020-09-28 13:32:07 +00:00
|
|
|
use std::io::{Read, Write, BufRead, BufReader};
|
2019-04-11 05:55:02 +00:00
|
|
|
use std::panic::UnwindSafe;
|
2020-01-16 07:51:52 +00:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::sync::{Arc, Mutex};
|
2021-10-07 12:03:36 +00:00
|
|
|
use std::time::{SystemTime, Duration};
|
2019-04-11 05:55:02 +00:00
|
|
|
|
2020-04-17 12:11:25 +00:00
|
|
|
use anyhow::{bail, format_err, Error};
|
2020-01-16 07:51:52 +00:00
|
|
|
use futures::*;
|
|
|
|
use lazy_static::lazy_static;
|
2019-04-10 10:42:24 +00:00
|
|
|
use serde_json::{json, Value};
|
2020-08-13 08:29:13 +00:00
|
|
|
use serde::{Serialize, Deserialize};
|
2020-01-16 07:51:52 +00:00
|
|
|
use tokio::sync::oneshot;
|
2021-09-22 06:44:48 +00:00
|
|
|
use nix::fcntl::OFlag;
|
|
|
|
use once_cell::sync::OnceCell;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2020-01-16 07:58:54 +00:00
|
|
|
use proxmox::sys::linux::procfs;
|
2021-09-22 06:44:48 +00:00
|
|
|
use proxmox::tools::fs::{create_path, replace_file, atomic_open_or_create_file, CreateOptions};
|
2021-10-08 09:19:37 +00:00
|
|
|
use proxmox_lang::try_block;
|
|
|
|
use proxmox_schema::upid::UPID;
|
2019-08-03 11:05:38 +00:00
|
|
|
|
2021-11-19 09:51:41 +00:00
|
|
|
use proxmox_sys::worker_task_context::{WorkerTaskContext};
|
|
|
|
use proxmox_sys::logrotate::{LogRotate, LogRotateFiles};
|
2021-09-23 08:09:19 +00:00
|
|
|
|
2021-09-30 10:31:38 +00:00
|
|
|
use crate::{CommandSocket, FileLogger, FileLogOptions};
|
2021-09-01 10:21:51 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
struct TaskListLockGuard(File);
|
2021-07-06 09:56:35 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
struct WorkerTaskSetup {
|
|
|
|
file_opts: CreateOptions,
|
|
|
|
taskdir: PathBuf,
|
|
|
|
task_lock_fn: PathBuf,
|
|
|
|
active_tasks_fn: PathBuf,
|
|
|
|
task_index_fn: PathBuf,
|
|
|
|
task_archive_fn: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
static WORKER_TASK_SETUP: OnceCell<WorkerTaskSetup> = OnceCell::new();
|
|
|
|
|
|
|
|
fn worker_task_setup() -> Result<&'static WorkerTaskSetup, Error> {
|
|
|
|
WORKER_TASK_SETUP.get()
|
|
|
|
.ok_or_else(|| format_err!("WorkerTask library is not initialized"))
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WorkerTaskSetup {
|
|
|
|
|
|
|
|
fn new(basedir: PathBuf, file_opts: CreateOptions) -> Self {
|
|
|
|
|
|
|
|
let mut taskdir = basedir.clone();
|
|
|
|
taskdir.push("tasks");
|
|
|
|
|
|
|
|
let mut task_lock_fn = taskdir.clone();
|
|
|
|
task_lock_fn.push(".active.lock");
|
|
|
|
|
|
|
|
let mut active_tasks_fn = taskdir.clone();
|
|
|
|
active_tasks_fn.push("active");
|
|
|
|
|
|
|
|
let mut task_index_fn = taskdir.clone();
|
|
|
|
task_index_fn.push("index");
|
|
|
|
|
|
|
|
let mut task_archive_fn = taskdir.clone();
|
|
|
|
task_archive_fn.push("archive");
|
|
|
|
|
|
|
|
Self {
|
|
|
|
file_opts,
|
|
|
|
taskdir,
|
|
|
|
task_lock_fn,
|
|
|
|
active_tasks_fn,
|
|
|
|
task_index_fn,
|
|
|
|
task_archive_fn,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn lock_task_list_files(&self, exclusive: bool) -> Result<TaskListLockGuard, Error> {
|
|
|
|
let options = self.file_opts.clone()
|
|
|
|
.perm(nix::sys::stat::Mode::from_bits_truncate(0o660));
|
|
|
|
|
|
|
|
let timeout = std::time::Duration::new(10, 0);
|
|
|
|
|
|
|
|
let file = proxmox::tools::fs::open_file_locked(
|
|
|
|
&self.task_lock_fn,
|
|
|
|
timeout,
|
|
|
|
exclusive,
|
|
|
|
options,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
Ok(TaskListLockGuard(file))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn log_path(&self, upid: &UPID) -> std::path::PathBuf {
|
|
|
|
let mut path = self.taskdir.clone();
|
|
|
|
path.push(format!("{:02X}", upid.pstart % 256));
|
|
|
|
path.push(upid.to_string());
|
|
|
|
path
|
|
|
|
}
|
|
|
|
|
|
|
|
// atomically read/update the task list, update status of finished tasks
|
|
|
|
// new_upid is added to the list when specified.
|
|
|
|
fn update_active_workers(&self, new_upid: Option<&UPID>) -> Result<(), Error> {
|
|
|
|
|
|
|
|
let lock = self.lock_task_list_files(true)?;
|
|
|
|
|
|
|
|
// TODO remove with 1.x
|
|
|
|
let mut finish_list: Vec<TaskListInfo> = read_task_file_from_path(&self.task_index_fn)?;
|
|
|
|
let had_index_file = !finish_list.is_empty();
|
|
|
|
|
|
|
|
// We use filter_map because one negative case wants to *move* the data into `finish_list`,
|
|
|
|
// clippy doesn't quite catch this!
|
|
|
|
#[allow(clippy::unnecessary_filter_map)]
|
|
|
|
let mut active_list: Vec<TaskListInfo> = read_task_file_from_path(&self.active_tasks_fn)?
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(|info| {
|
|
|
|
if info.state.is_some() {
|
|
|
|
// this can happen when the active file still includes finished tasks
|
|
|
|
finish_list.push(info);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
if !worker_is_active_local(&info.upid) {
|
|
|
|
// println!("Detected stopped task '{}'", &info.upid_str);
|
2021-10-08 09:19:37 +00:00
|
|
|
let now = proxmox_time::epoch_i64();
|
2021-09-22 06:44:48 +00:00
|
|
|
let status = upid_read_status(&info.upid).unwrap_or(TaskState::Unknown { endtime: now });
|
|
|
|
finish_list.push(TaskListInfo {
|
|
|
|
upid: info.upid,
|
|
|
|
upid_str: info.upid_str,
|
|
|
|
state: Some(status)
|
|
|
|
});
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(info)
|
|
|
|
}).collect();
|
|
|
|
|
|
|
|
if let Some(upid) = new_upid {
|
|
|
|
active_list.push(TaskListInfo { upid: upid.clone(), upid_str: upid.to_string(), state: None });
|
|
|
|
}
|
|
|
|
|
|
|
|
let active_raw = render_task_list(&active_list);
|
|
|
|
|
|
|
|
let options = self.file_opts.clone()
|
|
|
|
.perm(nix::sys::stat::Mode::from_bits_truncate(0o660));
|
|
|
|
|
|
|
|
replace_file(
|
|
|
|
&self.active_tasks_fn,
|
|
|
|
active_raw.as_bytes(),
|
|
|
|
options,
|
2021-10-20 12:56:15 +00:00
|
|
|
false,
|
2021-09-22 06:44:48 +00:00
|
|
|
)?;
|
|
|
|
|
|
|
|
finish_list.sort_unstable_by(|a, b| {
|
|
|
|
match (&a.state, &b.state) {
|
|
|
|
(Some(s1), Some(s2)) => s1.cmp(&s2),
|
|
|
|
(Some(_), None) => std::cmp::Ordering::Less,
|
|
|
|
(None, Some(_)) => std::cmp::Ordering::Greater,
|
|
|
|
_ => a.upid.starttime.cmp(&b.upid.starttime),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if !finish_list.is_empty() {
|
|
|
|
let options = self.file_opts.clone()
|
|
|
|
.perm(nix::sys::stat::Mode::from_bits_truncate(0o660));
|
|
|
|
|
|
|
|
let mut writer = atomic_open_or_create_file(
|
|
|
|
&self.task_archive_fn,
|
|
|
|
OFlag::O_APPEND | OFlag::O_RDWR,
|
|
|
|
&[],
|
|
|
|
options,
|
2021-10-20 12:56:15 +00:00
|
|
|
false,
|
2021-09-22 06:44:48 +00:00
|
|
|
)?;
|
|
|
|
for info in &finish_list {
|
|
|
|
writer.write_all(render_task_line(&info).as_bytes())?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO Remove with 1.x
|
|
|
|
// for compatibility, if we had an INDEX file, we do not need it anymore
|
|
|
|
if had_index_file {
|
|
|
|
let _ = nix::unistd::unlink(&self.task_index_fn);
|
|
|
|
}
|
|
|
|
|
|
|
|
drop(lock);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create task log directory with correct permissions
|
|
|
|
fn create_task_log_dirs(&self) -> Result<(), Error> {
|
|
|
|
|
|
|
|
try_block!({
|
|
|
|
let dir_opts = self.file_opts.clone()
|
|
|
|
.perm(nix::sys::stat::Mode::from_bits_truncate(0o755));
|
|
|
|
|
|
|
|
create_path(&self.taskdir, Some(dir_opts.clone()), Some(dir_opts.clone()))?;
|
|
|
|
// fixme:??? create_path(pbs_buildcfg::PROXMOX_BACKUP_RUN_DIR, None, Some(opts))?;
|
|
|
|
Ok(())
|
|
|
|
}).map_err(|err: Error| format_err!("unable to create task log dir - {}", err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Initialize the WorkerTask library
|
|
|
|
pub fn init_worker_tasks(basedir: PathBuf, file_opts: CreateOptions) -> Result<(), Error> {
|
|
|
|
let setup = WorkerTaskSetup::new(basedir, file_opts);
|
|
|
|
setup.create_task_log_dirs()?;
|
|
|
|
WORKER_TASK_SETUP.set(setup)
|
|
|
|
.map_err(|_| format_err!("init_worker_tasks failed - already initialized"))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// checks if the Task Archive is bigger that 'size_threshold' bytes, and
|
|
|
|
/// rotates it if it is
|
2021-11-19 09:51:41 +00:00
|
|
|
pub fn rotate_task_log_archive(
|
|
|
|
size_threshold: u64,
|
|
|
|
compress: bool,
|
|
|
|
max_files: Option<usize>,
|
|
|
|
options: Option<CreateOptions>,
|
|
|
|
) -> Result<bool, Error> {
|
2021-09-22 06:44:48 +00:00
|
|
|
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
|
|
|
|
let _lock = setup.lock_task_list_files(true)?;
|
|
|
|
|
2021-11-19 09:51:41 +00:00
|
|
|
let mut logrotate = LogRotate::new(
|
|
|
|
&setup.task_archive_fn,
|
|
|
|
compress,
|
|
|
|
max_files,
|
|
|
|
options,
|
|
|
|
)?;
|
2021-09-22 06:44:48 +00:00
|
|
|
|
2021-11-19 09:51:41 +00:00
|
|
|
logrotate.rotate(size_threshold)
|
2021-09-22 06:44:48 +00:00
|
|
|
}
|
|
|
|
|
2021-10-07 12:03:36 +00:00
|
|
|
/// removes all task logs that are older than the oldest task entry in the
|
|
|
|
/// task archive
|
|
|
|
pub fn cleanup_old_tasks(compressed: bool) -> Result<(), Error> {
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
|
|
|
|
let _lock = setup.lock_task_list_files(true)?;
|
|
|
|
|
2021-11-19 09:51:41 +00:00
|
|
|
let logrotate = LogRotate::new(
|
|
|
|
&setup.task_archive_fn,
|
|
|
|
compressed,
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
)?;
|
2021-10-07 12:03:36 +00:00
|
|
|
|
|
|
|
let mut timestamp = None;
|
|
|
|
if let Some(last_file) = logrotate.files().last() {
|
|
|
|
let reader = BufReader::new(last_file);
|
|
|
|
for line in reader.lines() {
|
|
|
|
let line = line?;
|
|
|
|
if let Ok((_, _, Some(state))) = parse_worker_status_line(&line) {
|
|
|
|
timestamp = Some(state.endtime());
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_modified(entry: std::fs::DirEntry) -> Result<SystemTime, std::io::Error> {
|
|
|
|
entry.metadata()?.modified()
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(timestamp) = timestamp {
|
|
|
|
let cutoff_time = if timestamp > 0 {
|
|
|
|
SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(timestamp as u64))
|
|
|
|
} else {
|
|
|
|
SystemTime::UNIX_EPOCH.checked_sub(Duration::from_secs(-timestamp as u64))
|
|
|
|
}.ok_or_else(|| format_err!("could not calculate cutoff time"))?;
|
|
|
|
|
|
|
|
for i in 0..256 {
|
|
|
|
let mut path = setup.taskdir.clone();
|
|
|
|
path.push(format!("{:02X}", i));
|
|
|
|
for file in std::fs::read_dir(path)? {
|
|
|
|
let file = file?;
|
|
|
|
let path = file.path();
|
|
|
|
|
|
|
|
let modified = get_modified(file)
|
|
|
|
.map_err(|err| format_err!("error getting mtime for {:?}: {}", path, err))?;
|
|
|
|
|
|
|
|
if modified < cutoff_time {
|
|
|
|
match std::fs::remove_file(path) {
|
|
|
|
Ok(()) => {},
|
|
|
|
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {},
|
|
|
|
Err(err) => bail!("could not remove file: {}", err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
|
|
|
|
/// Path to the worker log file
|
|
|
|
pub fn upid_log_path(upid: &UPID) -> Result<std::path::PathBuf, Error> {
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
Ok(setup.log_path(upid))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Read endtime (time of last log line) and exitstatus from task log file
|
|
|
|
/// If there is not a single line with at valid datetime, we assume the
|
|
|
|
/// starttime to be the endtime
|
|
|
|
pub fn upid_read_status(upid: &UPID) -> Result<TaskState, Error> {
|
|
|
|
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
|
|
|
|
let mut status = TaskState::Unknown { endtime: upid.starttime };
|
|
|
|
|
|
|
|
let path = setup.log_path(upid);
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
let mut data = Vec::with_capacity(8192);
|
|
|
|
file.read_to_end(&mut data)?;
|
|
|
|
|
|
|
|
// strip newlines at the end of the task logs
|
|
|
|
while data.last() == Some(&b'\n') {
|
|
|
|
data.pop();
|
|
|
|
}
|
|
|
|
|
|
|
|
let last_line = match data.iter().rposition(|c| *c == b'\n') {
|
|
|
|
Some(start) if data.len() > (start+1) => &data[start+1..],
|
|
|
|
Some(_) => &data, // should not happen, since we removed all trailing newlines
|
|
|
|
None => &data,
|
|
|
|
};
|
|
|
|
|
|
|
|
let last_line = std::str::from_utf8(last_line)
|
|
|
|
.map_err(|err| format_err!("upid_read_status: utf8 parse failed: {}", err))?;
|
|
|
|
|
|
|
|
let mut iter = last_line.splitn(2, ": ");
|
|
|
|
if let Some(time_str) = iter.next() {
|
2021-10-08 09:19:37 +00:00
|
|
|
if let Ok(endtime) = proxmox_time::parse_rfc3339(time_str) {
|
2021-09-22 06:44:48 +00:00
|
|
|
// set the endtime even if we cannot parse the state
|
|
|
|
status = TaskState::Unknown { endtime };
|
|
|
|
if let Some(rest) = iter.next().and_then(|rest| rest.strip_prefix("TASK ")) {
|
|
|
|
if let Ok(state) = TaskState::from_endtime_and_message(endtime, rest) {
|
|
|
|
status = state;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(status)
|
2020-11-02 07:50:56 +00:00
|
|
|
}
|
2020-09-28 13:32:06 +00:00
|
|
|
|
2019-04-04 06:58:39 +00:00
|
|
|
lazy_static! {
|
|
|
|
static ref WORKER_TASK_LIST: Mutex<HashMap<usize, Arc<WorkerTask>>> = Mutex::new(HashMap::new());
|
2020-11-02 18:13:36 +00:00
|
|
|
}
|
2019-04-09 10:15:06 +00:00
|
|
|
|
2020-11-02 18:13:36 +00:00
|
|
|
/// checks if the task UPID refers to a worker from this process
|
|
|
|
fn is_local_worker(upid: &UPID) -> bool {
|
2021-09-23 08:09:19 +00:00
|
|
|
upid.pid == crate::pid() && upid.pstart == crate::pstart()
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2019-04-08 16:43:26 +00:00
|
|
|
/// Test if the task is still running
|
2020-05-07 06:30:38 +00:00
|
|
|
pub async fn worker_is_active(upid: &UPID) -> Result<bool, Error> {
|
2020-11-02 18:13:36 +00:00
|
|
|
if is_local_worker(upid) {
|
2020-05-07 06:30:38 +00:00
|
|
|
return Ok(WORKER_TASK_LIST.lock().unwrap().contains_key(&upid.task_id));
|
|
|
|
}
|
|
|
|
|
2021-01-19 09:27:59 +00:00
|
|
|
if procfs::check_process_running_pstart(upid.pid, upid.pstart).is_none() {
|
2020-05-07 06:30:38 +00:00
|
|
|
return Ok(false);
|
|
|
|
}
|
|
|
|
|
2021-09-23 08:09:19 +00:00
|
|
|
let sock = crate::ctrl_sock_from_pid(upid.pid);
|
2020-05-07 06:30:38 +00:00
|
|
|
let cmd = json!({
|
2020-11-02 18:13:36 +00:00
|
|
|
"command": "worker-task-status",
|
2020-11-04 15:44:07 +00:00
|
|
|
"args": {
|
|
|
|
"upid": upid.to_string(),
|
|
|
|
},
|
2020-05-07 06:30:38 +00:00
|
|
|
});
|
2021-09-23 08:09:19 +00:00
|
|
|
let status = crate::send_command(sock, &cmd).await?;
|
2019-04-07 11:51:46 +00:00
|
|
|
|
2020-05-07 06:30:38 +00:00
|
|
|
if let Some(active) = status.as_bool() {
|
|
|
|
Ok(active)
|
|
|
|
} else {
|
|
|
|
bail!("got unexpected result {:?} (expected bool)", status);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Test if the task is still running (fast but inaccurate implementation)
|
|
|
|
///
|
2020-11-02 18:13:36 +00:00
|
|
|
/// If the task is spawned from a different process, we simply return if
|
2020-05-07 06:30:38 +00:00
|
|
|
/// that process is still running. This information is good enough to detect
|
|
|
|
/// stale tasks...
|
2020-05-29 06:05:10 +00:00
|
|
|
pub fn worker_is_active_local(upid: &UPID) -> bool {
|
2020-11-02 18:13:36 +00:00
|
|
|
if is_local_worker(upid) {
|
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
|
|
|
procfs::check_process_running_pstart(upid.pid, upid.pstart).is_some()
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-30 10:31:38 +00:00
|
|
|
/// Register task control command on a [CommandSocket].
|
2021-09-30 08:33:57 +00:00
|
|
|
///
|
|
|
|
/// This create two commands:
|
|
|
|
///
|
|
|
|
/// * ``worker-task-abort <UPID>``: calls [abort_local_worker]
|
|
|
|
///
|
|
|
|
/// * ``worker-task-status <UPID>``: return true of false, depending on
|
|
|
|
/// whether the worker is running or stopped.
|
2020-11-02 18:13:36 +00:00
|
|
|
pub fn register_task_control_commands(
|
2021-09-30 10:31:38 +00:00
|
|
|
commando_sock: &mut CommandSocket,
|
2020-11-02 18:13:36 +00:00
|
|
|
) -> Result<(), Error> {
|
|
|
|
fn get_upid(args: Option<&Value>) -> Result<UPID, Error> {
|
|
|
|
let args = if let Some(args) = args { args } else { bail!("missing args") };
|
|
|
|
let upid = match args.get("upid") {
|
|
|
|
Some(Value::String(upid)) => upid.parse::<UPID>()?,
|
|
|
|
None => bail!("no upid in args"),
|
|
|
|
_ => bail!("unable to parse upid"),
|
|
|
|
};
|
|
|
|
if !is_local_worker(&upid) {
|
2019-04-09 10:15:06 +00:00
|
|
|
bail!("upid does not belong to this process");
|
|
|
|
}
|
2020-11-02 18:13:36 +00:00
|
|
|
Ok(upid)
|
|
|
|
}
|
2019-04-09 10:15:06 +00:00
|
|
|
|
2020-11-02 18:13:36 +00:00
|
|
|
commando_sock.register_command("worker-task-abort".into(), move |args| {
|
|
|
|
let upid = get_upid(args)?;
|
|
|
|
|
2021-09-21 10:11:12 +00:00
|
|
|
abort_local_worker(upid);
|
|
|
|
|
2020-11-02 18:13:36 +00:00
|
|
|
Ok(Value::Null)
|
2019-04-09 10:15:06 +00:00
|
|
|
})?;
|
2020-11-02 18:13:36 +00:00
|
|
|
commando_sock.register_command("worker-task-status".into(), move |args| {
|
|
|
|
let upid = get_upid(args)?;
|
2019-04-09 10:15:06 +00:00
|
|
|
|
2020-11-02 18:13:36 +00:00
|
|
|
let active = WORKER_TASK_LIST.lock().unwrap().contains_key(&upid.task_id);
|
|
|
|
|
|
|
|
Ok(active.into())
|
|
|
|
})?;
|
2019-04-09 10:15:06 +00:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Try to abort a worker task, but do no wait
|
|
|
|
///
|
|
|
|
/// Errors (if any) are simply logged.
|
|
|
|
pub fn abort_worker_nowait(upid: UPID) {
|
2019-08-27 07:18:39 +00:00
|
|
|
tokio::spawn(async move {
|
|
|
|
if let Err(err) = abort_worker(upid).await {
|
2021-09-30 08:33:57 +00:00
|
|
|
log::error!("abort worker task failed - {}", err);
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
2019-08-27 07:18:39 +00:00
|
|
|
});
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Abort a worker task
|
|
|
|
///
|
|
|
|
/// By sending ``worker-task-abort`` to the control socket.
|
2020-05-07 06:30:38 +00:00
|
|
|
pub async fn abort_worker(upid: UPID) -> Result<(), Error> {
|
2019-04-10 10:42:24 +00:00
|
|
|
|
2021-09-23 08:09:19 +00:00
|
|
|
let sock = crate::ctrl_sock_from_pid(upid.pid);
|
2019-04-10 10:42:24 +00:00
|
|
|
let cmd = json!({
|
2020-11-02 18:13:36 +00:00
|
|
|
"command": "worker-task-abort",
|
2020-11-04 15:44:07 +00:00
|
|
|
"args": {
|
|
|
|
"upid": upid.to_string(),
|
|
|
|
},
|
2019-04-10 10:42:24 +00:00
|
|
|
});
|
2021-09-23 08:09:19 +00:00
|
|
|
crate::send_command(sock, &cmd).map_ok(|_| ()).await
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
|
|
|
|
2020-08-13 12:30:17 +00:00
|
|
|
fn parse_worker_status_line(line: &str) -> Result<(String, UPID, Option<TaskState>), Error> {
|
2019-04-05 10:37:35 +00:00
|
|
|
|
|
|
|
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)?;
|
2020-08-13 12:30:17 +00:00
|
|
|
let state = TaskState::from_endtime_and_message(endtime, data[2])?;
|
|
|
|
Ok((data[0].to_owned(), data[0].parse::<UPID>()?, Some(state)))
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
|
|
|
_ => bail!("wrong number of components"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-13 08:29:13 +00:00
|
|
|
/// Task State
|
2020-08-13 12:30:17 +00:00
|
|
|
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
2020-08-13 08:29:13 +00:00
|
|
|
pub enum TaskState {
|
|
|
|
/// The Task ended with an undefined state
|
2020-08-13 12:30:17 +00:00
|
|
|
Unknown { endtime: i64 },
|
2020-08-13 08:29:13 +00:00
|
|
|
/// The Task ended and there were no errors or warnings
|
2020-08-13 12:30:17 +00:00
|
|
|
OK { endtime: i64 },
|
2020-08-13 08:29:13 +00:00
|
|
|
/// The Task had 'count' amount of warnings and no errors
|
2020-08-13 12:30:17 +00:00
|
|
|
Warning { count: u64, endtime: i64 },
|
2020-08-13 08:29:13 +00:00
|
|
|
/// The Task ended with the error described in 'message'
|
2020-08-13 12:30:17 +00:00
|
|
|
Error { message: String, endtime: i64 },
|
2020-08-13 08:29:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TaskState {
|
2020-08-13 12:30:17 +00:00
|
|
|
pub fn endtime(&self) -> i64 {
|
|
|
|
match *self {
|
|
|
|
TaskState::Unknown { endtime } => endtime,
|
|
|
|
TaskState::OK { endtime } => endtime,
|
|
|
|
TaskState::Warning { endtime, .. } => endtime,
|
|
|
|
TaskState::Error { endtime, .. } => endtime,
|
2020-08-13 08:29:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-13 12:30:17 +00:00
|
|
|
fn result_text(&self) -> String {
|
2020-08-13 08:29:13 +00:00
|
|
|
match self {
|
2020-08-13 12:30:17 +00:00
|
|
|
TaskState::Error { message, .. } => format!("TASK ERROR: {}", message),
|
|
|
|
other => format!("TASK {}", other),
|
2020-08-13 08:29:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-13 12:30:17 +00:00
|
|
|
fn from_endtime_and_message(endtime: i64, s: &str) -> Result<Self, Error> {
|
2020-08-13 08:29:13 +00:00
|
|
|
if s == "unknown" {
|
2020-08-13 12:30:17 +00:00
|
|
|
Ok(TaskState::Unknown { endtime })
|
2020-08-13 08:29:13 +00:00
|
|
|
} else if s == "OK" {
|
2020-08-13 12:30:17 +00:00
|
|
|
Ok(TaskState::OK { endtime })
|
2021-01-18 12:50:28 +00:00
|
|
|
} else if let Some(warnings) = s.strip_prefix("WARNINGS: ") {
|
|
|
|
let count: u64 = warnings.parse()?;
|
2020-08-13 12:30:17 +00:00
|
|
|
Ok(TaskState::Warning{ count, endtime })
|
2021-01-19 09:27:59 +00:00
|
|
|
} else if !s.is_empty() {
|
2021-01-18 12:50:28 +00:00
|
|
|
let message = if let Some(err) = s.strip_prefix("ERROR: ") { err } else { s }.to_string();
|
2020-08-13 12:30:17 +00:00
|
|
|
Ok(TaskState::Error{ message, endtime })
|
2020-08-13 08:29:13 +00:00
|
|
|
} else {
|
|
|
|
bail!("unable to parse Task Status '{}'", s);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-13 12:30:17 +00:00
|
|
|
impl std::cmp::PartialOrd for TaskState {
|
|
|
|
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
|
|
|
Some(self.endtime().cmp(&other.endtime()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::cmp::Ord for TaskState {
|
|
|
|
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
|
|
|
self.endtime().cmp(&other.endtime())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for TaskState {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
TaskState::Unknown { .. } => write!(f, "unknown"),
|
|
|
|
TaskState::OK { .. }=> write!(f, "OK"),
|
|
|
|
TaskState::Warning { count, .. } => write!(f, "WARNINGS: {}", count),
|
|
|
|
TaskState::Error { message, .. } => write!(f, "{}", message),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
2020-08-13 12:30:17 +00:00
|
|
|
pub state: Option<TaskState>, // endtime, status
|
2019-04-06 08:17:11 +00:00
|
|
|
}
|
|
|
|
|
2020-09-25 14:13:19 +00:00
|
|
|
fn render_task_line(info: &TaskListInfo) -> String {
|
|
|
|
let mut raw = String::new();
|
|
|
|
if let Some(status) = &info.state {
|
|
|
|
raw.push_str(&format!("{} {:08X} {}\n", info.upid_str, status.endtime(), status));
|
|
|
|
} else {
|
|
|
|
raw.push_str(&info.upid_str);
|
|
|
|
raw.push('\n');
|
|
|
|
}
|
|
|
|
|
|
|
|
raw
|
|
|
|
}
|
|
|
|
|
|
|
|
fn render_task_list(list: &[TaskListInfo]) -> String {
|
|
|
|
let mut raw = String::new();
|
|
|
|
for info in list {
|
|
|
|
raw.push_str(&render_task_line(&info));
|
|
|
|
}
|
|
|
|
raw
|
|
|
|
}
|
|
|
|
|
2020-09-28 13:32:06 +00:00
|
|
|
// note this is not locked, caller has to make sure it is
|
|
|
|
// this will skip (and log) lines that are not valid status lines
|
|
|
|
fn read_task_file<R: Read>(reader: R) -> Result<Vec<TaskListInfo>, Error>
|
|
|
|
{
|
|
|
|
let reader = BufReader::new(reader);
|
|
|
|
let mut list = Vec::new();
|
|
|
|
for line in reader.lines() {
|
|
|
|
let line = line?;
|
|
|
|
match parse_worker_status_line(&line) {
|
|
|
|
Ok((upid_str, upid, state)) => list.push(TaskListInfo {
|
|
|
|
upid_str,
|
|
|
|
upid,
|
|
|
|
state
|
|
|
|
}),
|
|
|
|
Err(err) => {
|
2021-09-30 08:33:57 +00:00
|
|
|
log::warn!("unable to parse worker status '{}' - {}", line, err);
|
2020-09-28 13:32:06 +00:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(list)
|
|
|
|
}
|
|
|
|
|
|
|
|
// note this is not locked, caller has to make sure it is
|
|
|
|
fn read_task_file_from_path<P>(path: P) -> Result<Vec<TaskListInfo>, Error>
|
|
|
|
where
|
|
|
|
P: AsRef<std::path::Path> + std::fmt::Debug,
|
|
|
|
{
|
|
|
|
let file = match File::open(&path) {
|
|
|
|
Ok(f) => f,
|
|
|
|
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
|
|
|
Err(err) => bail!("unable to open task list {:?} - {}", path, err),
|
|
|
|
};
|
|
|
|
|
|
|
|
read_task_file(file)
|
|
|
|
}
|
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Iterate over existing/active worker tasks
|
2020-09-28 13:32:08 +00:00
|
|
|
pub struct TaskListInfoIterator {
|
|
|
|
list: VecDeque<TaskListInfo>,
|
2020-10-29 09:50:13 +00:00
|
|
|
end: bool,
|
2020-09-28 13:32:08 +00:00
|
|
|
archive: Option<LogRotateFiles>,
|
2021-09-22 06:44:48 +00:00
|
|
|
lock: Option<TaskListLockGuard>,
|
2020-09-28 13:32:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TaskListInfoIterator {
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Creates a new iterator instance.
|
2020-09-28 13:32:08 +00:00
|
|
|
pub fn new(active_only: bool) -> Result<Self, Error> {
|
2021-09-22 06:44:48 +00:00
|
|
|
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
|
2020-09-28 13:32:08 +00:00
|
|
|
let (read_lock, active_list) = {
|
2021-09-22 06:44:48 +00:00
|
|
|
let lock = setup.lock_task_list_files(false)?;
|
|
|
|
let active_list = read_task_file_from_path(&setup.active_tasks_fn)?;
|
2020-09-28 13:32:08 +00:00
|
|
|
|
|
|
|
let needs_update = active_list
|
|
|
|
.iter()
|
2020-09-30 08:45:06 +00:00
|
|
|
.any(|info| info.state.is_some() || !worker_is_active_local(&info.upid));
|
2020-09-28 13:32:08 +00:00
|
|
|
|
2020-10-29 09:50:13 +00:00
|
|
|
// TODO remove with 1.x
|
2021-09-22 06:44:48 +00:00
|
|
|
let index_exists = setup.task_index_fn.is_file();
|
2020-10-29 09:50:13 +00:00
|
|
|
|
|
|
|
if needs_update || index_exists {
|
2020-09-28 13:32:08 +00:00
|
|
|
drop(lock);
|
2021-09-22 06:44:48 +00:00
|
|
|
setup.update_active_workers(None)?;
|
|
|
|
let lock = setup.lock_task_list_files(false)?;
|
|
|
|
let active_list = read_task_file_from_path(&setup.active_tasks_fn)?;
|
2020-09-28 13:32:08 +00:00
|
|
|
(lock, active_list)
|
|
|
|
} else {
|
|
|
|
(lock, active_list)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let archive = if active_only {
|
|
|
|
None
|
|
|
|
} else {
|
2021-11-19 09:51:41 +00:00
|
|
|
let logrotate = LogRotate::new(&setup.task_archive_fn, true, None, None)?;
|
2020-09-28 13:32:08 +00:00
|
|
|
Some(logrotate.files())
|
|
|
|
};
|
|
|
|
|
|
|
|
let lock = if active_only { None } else { Some(read_lock) };
|
|
|
|
|
|
|
|
Ok(Self {
|
|
|
|
list: active_list.into(),
|
2020-10-29 09:50:13 +00:00
|
|
|
end: active_only,
|
2020-09-28 13:32:08 +00:00
|
|
|
archive,
|
|
|
|
lock,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Iterator for TaskListInfoIterator {
|
|
|
|
type Item = Result<TaskListInfo, Error>;
|
|
|
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
loop {
|
|
|
|
if let Some(element) = self.list.pop_back() {
|
|
|
|
return Some(Ok(element));
|
2020-10-29 09:50:13 +00:00
|
|
|
} else if self.end {
|
|
|
|
return None;
|
2020-09-28 13:32:08 +00:00
|
|
|
} else {
|
2020-10-29 09:50:13 +00:00
|
|
|
if let Some(mut archive) = self.archive.take() {
|
|
|
|
if let Some(file) = archive.next() {
|
|
|
|
let list = match read_task_file(file) {
|
|
|
|
Ok(list) => list,
|
2020-09-28 13:32:08 +00:00
|
|
|
Err(err) => return Some(Err(err)),
|
|
|
|
};
|
2020-10-29 09:50:13 +00:00
|
|
|
self.list.append(&mut list.into());
|
|
|
|
self.archive = Some(archive);
|
|
|
|
continue;
|
2020-09-28 13:32:08 +00:00
|
|
|
}
|
|
|
|
}
|
2020-10-29 09:50:13 +00:00
|
|
|
|
|
|
|
self.end = true;
|
|
|
|
self.lock.take();
|
2020-09-28 13:32:08 +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
|
|
|
pub struct WorkerTask {
|
2021-09-22 06:44:48 +00:00
|
|
|
setup: &'static WorkerTaskSetup,
|
2019-04-04 06:58:39 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct WorkerTaskData {
|
|
|
|
logger: FileLogger,
|
|
|
|
progress: f64, // 0..1
|
2020-06-24 07:04:35 +00:00
|
|
|
warn_count: u64,
|
2019-04-15 07:38:05 +00:00
|
|
|
pub abort_listeners: Vec<oneshot::Sender<()>>,
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WorkerTask {
|
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
pub fn new(
|
|
|
|
worker_type: &str,
|
|
|
|
worker_id: Option<String>,
|
|
|
|
auth_id: String,
|
|
|
|
to_stdout: bool,
|
|
|
|
) -> Result<Arc<Self>, Error> {
|
|
|
|
|
|
|
|
let setup = worker_task_setup()?;
|
|
|
|
|
2020-10-23 11:33:21 +00:00
|
|
|
let upid = UPID::new(worker_type, worker_id, auth_id)?;
|
2019-04-08 16:43:26 +00:00
|
|
|
let task_id = upid.task_id;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
let mut path = setup.taskdir.clone();
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2020-10-29 11:35:33 +00:00
|
|
|
path.push(format!("{:02X}", upid.pstart & 255));
|
2019-04-04 06:58:39 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
let dir_opts = setup.file_opts.clone()
|
|
|
|
.perm(nix::sys::stat::Mode::from_bits_truncate(0o755));
|
2019-04-06 15:53:12 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
create_path(&path, None, Some(dir_opts))?;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
|
|
|
path.push(upid.to_string());
|
|
|
|
|
2020-10-15 15:49:18 +00:00
|
|
|
let logger_options = FileLogOptions {
|
2020-11-30 12:56:21 +00:00
|
|
|
to_stdout,
|
2020-10-15 15:49:18 +00:00
|
|
|
exclusive: true,
|
2020-10-19 11:22:37 +00:00
|
|
|
prefix_time: true,
|
2020-10-15 15:49:18 +00:00
|
|
|
read: true,
|
2021-09-22 06:44:48 +00:00
|
|
|
file_opts: setup.file_opts.clone(),
|
2020-10-15 15:49:18 +00:00
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
let logger = FileLogger::new(&path, logger_options)?;
|
2019-04-04 06:58:39 +00:00
|
|
|
|
|
|
|
let worker = Arc::new(Self {
|
2021-09-22 06:44:48 +00:00
|
|
|
setup,
|
2020-05-27 14:42:22 +00:00
|
|
|
upid: upid.clone(),
|
2019-04-04 06:58:39 +00:00
|
|
|
abort_requested: AtomicBool::new(false),
|
|
|
|
data: Mutex::new(WorkerTaskData {
|
|
|
|
logger,
|
|
|
|
progress: 0.0,
|
2020-06-24 07:04:35 +00:00
|
|
|
warn_count: 0,
|
2019-04-15 07:38:05 +00:00
|
|
|
abort_listeners: vec![],
|
2019-04-04 06:58:39 +00:00
|
|
|
}),
|
|
|
|
});
|
|
|
|
|
2020-05-27 14:42:22 +00:00
|
|
|
// scope to drop the lock again after inserting
|
|
|
|
{
|
|
|
|
let mut hash = WORKER_TASK_LIST.lock().unwrap();
|
|
|
|
hash.insert(task_id, worker.clone());
|
2021-09-23 08:09:19 +00:00
|
|
|
crate::set_worker_count(hash.len());
|
2020-05-27 14:42:22 +00:00
|
|
|
}
|
2019-04-08 10:21:29 +00:00
|
|
|
|
2021-09-22 06:44:48 +00:00
|
|
|
setup.update_active_workers(Some(&upid))?;
|
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>,
|
2021-09-21 10:14:19 +00:00
|
|
|
auth_id: String,
|
2019-04-06 09:23:53 +00:00
|
|
|
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
|
|
|
{
|
2020-10-23 11:33:21 +00:00
|
|
|
let worker = WorkerTask::new(worker_type, worker_id, auth_id, 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>,
|
2021-09-21 10:14:19 +00:00
|
|
|
auth_id: String,
|
2019-04-06 09:23:53 +00:00
|
|
|
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
|
|
|
{
|
2020-10-23 11:33:21 +00:00
|
|
|
let worker = WorkerTask::new(worker_type, worker_id, auth_id, 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
|
|
|
});
|
|
|
|
|
2019-04-06 09:23:53 +00:00
|
|
|
Ok(upid_str)
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
2020-08-13 08:29:13 +00:00
|
|
|
/// create state from self and a result
|
|
|
|
pub fn create_state(&self, result: &Result<(), Error>) -> TaskState {
|
2020-06-24 07:04:35 +00:00
|
|
|
let warn_count = self.data.lock().unwrap().warn_count;
|
2020-07-31 12:43:23 +00:00
|
|
|
|
2021-10-08 09:19:37 +00:00
|
|
|
let endtime = proxmox_time::epoch_i64();
|
2020-08-13 12:30:17 +00:00
|
|
|
|
2019-04-05 10:37:35 +00:00
|
|
|
if let Err(err) = result {
|
2020-08-13 12:30:17 +00:00
|
|
|
TaskState::Error { message: err.to_string(), endtime }
|
2020-06-24 07:04:35 +00:00
|
|
|
} else if warn_count > 0 {
|
2020-08-13 12:30:17 +00:00
|
|
|
TaskState::Warning { count: warn_count, endtime }
|
2019-04-05 10:37:35 +00:00
|
|
|
} else {
|
2020-08-13 12:30:17 +00:00
|
|
|
TaskState::OK { endtime }
|
2019-04-05 10:37:35 +00:00
|
|
|
}
|
2020-07-31 12:43:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Log task result, remove task from running list
|
|
|
|
pub fn log_result(&self, result: &Result<(), Error>) {
|
2020-08-13 08:29:13 +00:00
|
|
|
let state = self.create_state(result);
|
2021-09-24 07:30:00 +00:00
|
|
|
self.log_message(state.result_text());
|
2019-04-15 05:49:03 +00:00
|
|
|
|
|
|
|
WORKER_TASK_LIST.lock().unwrap().remove(&self.upid.task_id);
|
2021-09-22 06:44:48 +00:00
|
|
|
let _ = self.setup.update_active_workers(None);
|
2021-09-23 08:09:19 +00:00
|
|
|
crate::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.
|
2021-09-24 07:30:00 +00:00
|
|
|
pub fn log_message<S: AsRef<str>>(&self, msg: S) {
|
2019-04-04 06:58:39 +00:00
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
data.logger.log(msg);
|
|
|
|
}
|
|
|
|
|
2020-06-24 07:04:35 +00:00
|
|
|
/// Log a message as warning.
|
2021-09-24 07:30:00 +00:00
|
|
|
pub fn log_warning<S: AsRef<str>>(&self, msg: S) {
|
2020-06-24 07:04:35 +00:00
|
|
|
let mut data = self.data.lock().unwrap();
|
|
|
|
data.logger.log(format!("WARN: {}", msg.as_ref()));
|
|
|
|
data.warn_count += 1;
|
|
|
|
}
|
|
|
|
|
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) {
|
2021-01-29 08:22:37 +00:00
|
|
|
let prev_abort = self.abort_requested.swap(true, Ordering::SeqCst);
|
|
|
|
if !prev_abort { // log abort one time
|
2021-09-24 07:30:00 +00:00
|
|
|
self.log_message(format!("received abort request ..."));
|
2021-01-29 08:22:37 +00:00
|
|
|
}
|
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) => {
|
2021-03-10 15:37:09 +00:00
|
|
|
let _ = ch.send(()); // ignore errors here
|
2019-04-15 07:38:05 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
2020-07-31 12:43:24 +00:00
|
|
|
|
|
|
|
pub fn upid(&self) -> &UPID {
|
|
|
|
&self.upid
|
|
|
|
}
|
2019-04-04 06:58:39 +00:00
|
|
|
}
|
2020-10-12 09:28:03 +00:00
|
|
|
|
2021-09-24 05:40:49 +00:00
|
|
|
impl WorkerTaskContext for WorkerTask {
|
2021-09-24 09:39:30 +00:00
|
|
|
|
|
|
|
fn abort_requested(&self) -> bool {
|
|
|
|
self.abort_requested.load(Ordering::SeqCst)
|
2020-10-12 09:28:03 +00:00
|
|
|
}
|
|
|
|
|
2021-09-24 09:56:53 +00:00
|
|
|
fn shutdown_requested(&self) -> bool {
|
|
|
|
crate::shutdown_requested()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn fail_on_shutdown(&self) -> Result<(), Error> {
|
|
|
|
crate::fail_on_shutdown()
|
|
|
|
}
|
|
|
|
|
2020-10-12 09:28:03 +00:00
|
|
|
fn log(&self, level: log::Level, message: &std::fmt::Arguments) {
|
|
|
|
match level {
|
2021-09-24 07:30:00 +00:00
|
|
|
log::Level::Error => self.log_warning(&message.to_string()),
|
|
|
|
log::Level::Warn => self.log_warning(&message.to_string()),
|
|
|
|
log::Level::Info => self.log_message(&message.to_string()),
|
|
|
|
log::Level::Debug => self.log_message(&format!("DEBUG: {}", message)),
|
|
|
|
log::Level::Trace => self.log_message(&format!("TRACE: {}", message)),
|
2020-10-12 09:28:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-07-19 08:44:40 +00:00
|
|
|
|
|
|
|
/// Wait for a locally spanned worker task
|
|
|
|
///
|
|
|
|
/// Note: local workers should print logs to stdout, so there is no
|
|
|
|
/// need to fetch/display logs. We just wait for the worker to finish.
|
|
|
|
pub async fn wait_for_local_worker(upid_str: &str) -> Result<(), Error> {
|
|
|
|
|
|
|
|
let upid: UPID = upid_str.parse()?;
|
|
|
|
|
|
|
|
let sleep_duration = core::time::Duration::new(0, 100_000_000);
|
|
|
|
|
|
|
|
loop {
|
|
|
|
if worker_is_active_local(&upid) {
|
|
|
|
tokio::time::sleep(sleep_duration).await;
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2021-09-21 10:11:12 +00:00
|
|
|
|
|
|
|
/// Request abort of a local worker (if existing and running)
|
|
|
|
pub fn abort_local_worker(upid: UPID) {
|
|
|
|
if let Some(ref worker) = WORKER_TASK_LIST.lock().unwrap().get(&upid.task_id) {
|
|
|
|
worker.request_abort();
|
|
|
|
}
|
|
|
|
}
|