]> git.proxmox.com Git - proxmox-backup.git/blob - pbs-api-types/src/upid.rs
worker task: allow to configure path and owner/group
[proxmox-backup.git] / pbs-api-types / src / upid.rs
1 use std::sync::atomic::{AtomicUsize, Ordering};
2
3 use anyhow::{bail, Error};
4 use serde::{Deserialize, Serialize};
5
6 use proxmox::api::api;
7 use proxmox::api::schema::{ApiStringFormat, ApiType, Schema, StringSchema, ArraySchema, ReturnType};
8 use proxmox::const_regex;
9 use proxmox::sys::linux::procfs;
10
11 /// Unique Process/Task Identifier
12 ///
13 /// We use this to uniquely identify worker task. UPIDs have a short
14 /// string repesentaion, which gives additional information about the
15 /// type of the task. for example:
16 /// ```text
17 /// UPID:{node}:{pid}:{pstart}:{task_id}:{starttime}:{worker_type}:{worker_id}:{userid}:
18 /// UPID:elsa:00004F37:0039E469:00000000:5CA78B83:garbage_collection::root@pam:
19 /// ```
20 /// Please note that we use tokio, so a single thread can run multiple
21 /// tasks.
22 // #[api] - manually implemented API type
23 #[derive(Debug, Clone)]
24 pub struct UPID {
25 /// The Unix PID
26 pub pid: libc::pid_t,
27 /// The Unix process start time from `/proc/pid/stat`
28 pub pstart: u64,
29 /// The task start time (Epoch)
30 pub starttime: i64,
31 /// The task ID (inside the process/thread)
32 pub task_id: usize,
33 /// Worker type (arbitrary ASCII string)
34 pub worker_type: String,
35 /// Worker ID (arbitrary ASCII string)
36 pub worker_id: Option<String>,
37 /// The authenticated entity who started the task
38 pub auth_id: String,
39 /// The node name.
40 pub node: String,
41 }
42
43 proxmox::forward_serialize_to_display!(UPID);
44 proxmox::forward_deserialize_to_from_str!(UPID);
45
46 const_regex! {
47 pub PROXMOX_UPID_REGEX = concat!(
48 r"^UPID:(?P<node>[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?):(?P<pid>[0-9A-Fa-f]{8}):",
49 r"(?P<pstart>[0-9A-Fa-f]{8,9}):(?P<task_id>[0-9A-Fa-f]{8,16}):(?P<starttime>[0-9A-Fa-f]{8}):",
50 r"(?P<wtype>[^:\s]+):(?P<wid>[^:\s]*):(?P<authid>[^:\s]+):$"
51 );
52 }
53
54 pub const PROXMOX_UPID_FORMAT: ApiStringFormat =
55 ApiStringFormat::Pattern(&PROXMOX_UPID_REGEX);
56
57 pub const UPID_SCHEMA: Schema = StringSchema::new("Unique Process/Task Identifier")
58 .min_length("UPID:N:12345678:12345678:12345678:::".len())
59 .max_length(128) // arbitrary
60 .format(&PROXMOX_UPID_FORMAT)
61 .schema();
62
63 impl ApiType for UPID {
64 const API_SCHEMA: Schema = UPID_SCHEMA;
65 }
66
67 impl UPID {
68 /// Create a new UPID
69 pub fn new(
70 worker_type: &str,
71 worker_id: Option<String>,
72 auth_id: String,
73 ) -> Result<Self, Error> {
74
75 let pid = unsafe { libc::getpid() };
76
77 let bad: &[_] = &['/', ':', ' '];
78
79 if worker_type.contains(bad) {
80 bail!("illegal characters in worker type '{}'", worker_type);
81 }
82
83 if auth_id.contains(bad) {
84 bail!("illegal characters in auth_id '{}'", auth_id);
85 }
86
87 static WORKER_TASK_NEXT_ID: AtomicUsize = AtomicUsize::new(0);
88
89 let task_id = WORKER_TASK_NEXT_ID.fetch_add(1, Ordering::SeqCst);
90
91 Ok(UPID {
92 pid,
93 pstart: procfs::PidStat::read_from_pid(nix::unistd::Pid::from_raw(pid))?.starttime,
94 starttime: proxmox::tools::time::epoch_i64(),
95 task_id,
96 worker_type: worker_type.to_owned(),
97 worker_id,
98 auth_id,
99 node: proxmox::tools::nodename().to_owned(),
100 })
101 }
102 }
103
104
105 impl std::str::FromStr for UPID {
106 type Err = Error;
107
108 fn from_str(s: &str) -> Result<Self, Self::Err> {
109 if let Some(cap) = PROXMOX_UPID_REGEX.captures(s) {
110
111 let worker_id = if cap["wid"].is_empty() {
112 None
113 } else {
114 let wid = proxmox_systemd::unescape_unit(&cap["wid"])?;
115 Some(wid)
116 };
117
118 Ok(UPID {
119 pid: i32::from_str_radix(&cap["pid"], 16).unwrap(),
120 pstart: u64::from_str_radix(&cap["pstart"], 16).unwrap(),
121 starttime: i64::from_str_radix(&cap["starttime"], 16).unwrap(),
122 task_id: usize::from_str_radix(&cap["task_id"], 16).unwrap(),
123 worker_type: cap["wtype"].to_string(),
124 worker_id,
125 auth_id: cap["authid"].parse()?,
126 node: cap["node"].to_string(),
127 })
128 } else {
129 bail!("unable to parse UPID '{}'", s);
130 }
131
132 }
133 }
134
135 impl std::fmt::Display for UPID {
136
137 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
138
139 let wid = if let Some(ref id) = self.worker_id {
140 proxmox_systemd::escape_unit(id, false)
141 } else {
142 String::new()
143 };
144
145 // Note: pstart can be > 32bit if uptime > 497 days, so this can result in
146 // more that 8 characters for pstart
147
148 write!(f, "UPID:{}:{:08X}:{:08X}:{:08X}:{:08X}:{}:{}:{}:",
149 self.node, self.pid, self.pstart, self.task_id, self.starttime, self.worker_type, wid, self.auth_id)
150 }
151 }
152
153 #[api()]
154 #[derive(Eq, PartialEq, Debug, Serialize, Deserialize)]
155 #[serde(rename_all = "lowercase")]
156 pub enum TaskStateType {
157 /// Ok
158 OK,
159 /// Warning
160 Warning,
161 /// Error
162 Error,
163 /// Unknown
164 Unknown,
165 }
166
167 #[api(
168 properties: {
169 upid: { schema: UPID::API_SCHEMA },
170 },
171 )]
172 #[derive(Serialize, Deserialize)]
173 /// Task properties.
174 pub struct TaskListItem {
175 pub upid: String,
176 /// The node name where the task is running on.
177 pub node: String,
178 /// The Unix PID
179 pub pid: i64,
180 /// The task start time (Epoch)
181 pub pstart: u64,
182 /// The task start time (Epoch)
183 pub starttime: i64,
184 /// Worker type (arbitrary ASCII string)
185 pub worker_type: String,
186 /// Worker ID (arbitrary ASCII string)
187 pub worker_id: Option<String>,
188 /// The authenticated entity who started the task
189 pub user: String,
190 /// The task end time (Epoch)
191 #[serde(skip_serializing_if="Option::is_none")]
192 pub endtime: Option<i64>,
193 /// Task end status
194 #[serde(skip_serializing_if="Option::is_none")]
195 pub status: Option<String>,
196 }
197
198 pub const NODE_TASKS_LIST_TASKS_RETURN_TYPE: ReturnType = ReturnType {
199 optional: false,
200 schema: &ArraySchema::new(
201 "A list of tasks.",
202 &TaskListItem::API_SCHEMA,
203 ).schema(),
204 };