| 1 |
use std::io::Read; |
| 2 |
use std::path::{Path, PathBuf}; |
| 3 |
|
| 4 |
use super::{FileWrapper, Io, Schedstat, Stat, Status, Syscall}; |
| 5 |
use crate::{ProcError, ProcResult}; |
| 6 |
use procfs_core::FromRead; |
| 7 |
use rustix::fd::{BorrowedFd, OwnedFd}; |
| 8 |
|
| 9 |
/// A task (aka Thread) inside of a [`Process`](crate::process::Process) |
| 10 |
/// |
| 11 |
/// Created by [`Process::tasks`](crate::process::Process::tasks), tasks in |
| 12 |
/// general are similar to Processes and should have mostly the same fields. |
| 13 |
#[derive(Debug)] |
| 14 |
pub struct Task { |
| 15 |
fd: OwnedFd, |
| 16 |
/// The ID of the process that this task belongs to |
| 17 |
pub pid: i32, |
| 18 |
/// The task ID |
| 19 |
pub tid: i32, |
| 20 |
/// Task root: `/proc/<pid>/task/<tid>` |
| 21 |
pub(crate) root: PathBuf, |
| 22 |
} |
| 23 |
|
| 24 |
impl Task { |
| 25 |
/// Create a new `Task` inside of the process |
| 26 |
/// |
| 27 |
/// This API is designed to be ergonomic from inside of [`TasksIter`](super::TasksIter) |
| 28 |
pub(crate) fn from_process_at<P: AsRef<Path>, Q: AsRef<Path>>( |
| 29 |
base: P, |
| 30 |
dirfd: BorrowedFd, |
| 31 |
path: Q, |
| 32 |
pid: i32, |
| 33 |
tid: i32, |
| 34 |
) -> ProcResult<Task> { |
| 35 |
use rustix::fs::{Mode, OFlags}; |
| 36 |
|
| 37 |
let p = path.as_ref(); |
| 38 |
let root = base.as_ref().join(p); |
| 39 |
let fd = wrap_io_error!( |
| 40 |
root, |
| 41 |
rustix::fs::openat( |
| 42 |
dirfd, |
| 43 |
p, |
| 44 |
OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 45 |
Mode::empty() |
| 46 |
) |
| 47 |
)?; |
| 48 |
|
| 49 |
Ok(Task { fd, pid, tid, root }) |
| 50 |
} |
| 51 |
|
| 52 |
/// Thread info from `/proc/<pid>/task/<tid>/stat` |
| 53 |
/// |
| 54 |
/// Many of the returned fields will be the same as the parent process, but some fields like `utime` and `stime` will be per-task |
| 55 |
pub fn stat(&self) -> ProcResult<Stat> { |
| 56 |
self.read("stat") |
| 57 |
} |
| 58 |
|
| 59 |
/// Thread info from `/proc/<pid>/task/<tid>/status` |
| 60 |
/// |
| 61 |
/// Many of the returned fields will be the same as the parent process |
| 62 |
pub fn status(&self) -> ProcResult<Status> { |
| 63 |
self.read("status") |
| 64 |
} |
| 65 |
|
| 66 |
/// Thread IO info from `/proc/<pid>/task/<tid>/io` |
| 67 |
/// |
| 68 |
/// This data will be unique per task. |
| 69 |
pub fn io(&self) -> ProcResult<Io> { |
| 70 |
self.read("io") |
| 71 |
} |
| 72 |
|
| 73 |
/// Thread scheduler info from `/proc/<pid>/task/<tid>/schedstat` |
| 74 |
/// |
| 75 |
/// This data will be unique per task. |
| 76 |
pub fn schedstat(&self) -> ProcResult<Schedstat> { |
| 77 |
self.read("schedstat") |
| 78 |
} |
| 79 |
|
| 80 |
/// Returns the status info from `/proc/<pid>/task/<tid>/syscall`. |
| 81 |
pub fn syscall(&self) -> ProcResult<Syscall> { |
| 82 |
self.read("syscall") |
| 83 |
} |
| 84 |
|
| 85 |
/// Thread children from `/proc/<pid>/task/<tid>/children` |
| 86 |
/// |
| 87 |
/// WARNING: |
| 88 |
/// This interface is not reliable unless all the child processes are stoppped or frozen. |
| 89 |
/// If a child task exits while the file is being read, non-exiting children may be omitted. |
| 90 |
/// See the procfs(5) man page for more information. |
| 91 |
/// |
| 92 |
/// This data will be unique per task. |
| 93 |
pub fn children(&self) -> ProcResult<Vec<u32>> { |
| 94 |
let mut buf = String::new(); |
| 95 |
let mut file = FileWrapper::open_at(&self.root, &self.fd, "children")?; |
| 96 |
file.read_to_string(&mut buf)?; |
| 97 |
buf.split_whitespace() |
| 98 |
.map(|child| { |
| 99 |
child |
| 100 |
.parse() |
| 101 |
.map_err(|_| ProcError::Other("Failed to parse task's child PIDs".to_string())) |
| 102 |
}) |
| 103 |
.collect() |
| 104 |
} |
| 105 |
|
| 106 |
/// Deliberately generate an IO error |
| 107 |
#[cfg(test)] |
| 108 |
pub(crate) fn generate_error(&self) -> ProcResult<()> { |
| 109 |
let _ = FileWrapper::open_at(&self.root, &self.fd, "does_not_exist")?; |
| 110 |
Ok(()) |
| 111 |
} |
| 112 |
|
| 113 |
/// Parse a file relative to the task proc structure. |
| 114 |
pub fn read<P, T>(&self, path: P) -> ProcResult<T> |
| 115 |
where |
| 116 |
P: AsRef<Path>, |
| 117 |
T: FromRead, |
| 118 |
{ |
| 119 |
FromRead::from_read(FileWrapper::open_at(&self.root, &self.fd, path)?) |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
#[cfg(test)] |
| 124 |
mod tests { |
| 125 |
use crate::process::{Io, Syscall}; |
| 126 |
use crate::ProcError; |
| 127 |
use rustix; |
| 128 |
use std::process; |
| 129 |
use std::sync::{Arc, Barrier}; |
| 130 |
|
| 131 |
#[test] |
| 132 |
#[cfg(not(tarpaulin))] // this test is unstable under tarpaulin, and i'm yet sure why |
| 133 |
// When this test runs in CI, run it single-threaded |
| 134 |
fn test_task_runsinglethread() { |
| 135 |
use std::io::Read; |
| 136 |
|
| 137 |
let me = crate::process::Process::myself().unwrap(); |
| 138 |
|
| 139 |
let (work_barrier, w_a, w_b) = { |
| 140 |
let b = Arc::new(Barrier::new(3)); |
| 141 |
(b.clone(), b.clone(), b) |
| 142 |
}; |
| 143 |
let (done_barrier, d_a, d_b) = { |
| 144 |
let b = Arc::new(Barrier::new(3)); |
| 145 |
(b.clone(), b.clone(), b) |
| 146 |
}; |
| 147 |
|
| 148 |
let bytes_to_read = 2_000_000; |
| 149 |
|
| 150 |
// create a new task to do some work |
| 151 |
let join_a = std::thread::Builder::new() |
| 152 |
.name("one".to_owned()) |
| 153 |
.spawn(move || { |
| 154 |
let mut vec = Vec::new(); |
| 155 |
let zero = std::fs::File::open("/dev/zero").unwrap(); |
| 156 |
|
| 157 |
zero.take(bytes_to_read).read_to_end(&mut vec).unwrap(); |
| 158 |
assert_eq!(vec.len(), bytes_to_read as usize); |
| 159 |
|
| 160 |
// spin for about 52 ticks (utime accounting isn't perfectly accurate) |
| 161 |
let dur = std::time::Duration::from_millis(52 * (1000 / crate::ticks_per_second()) as u64); |
| 162 |
let start = std::time::Instant::now(); |
| 163 |
while start.elapsed() <= dur { |
| 164 |
// spin |
| 165 |
} |
| 166 |
|
| 167 |
w_a.wait(); |
| 168 |
d_a.wait() |
| 169 |
}) |
| 170 |
.unwrap(); |
| 171 |
|
| 172 |
// create a new task that does nothing |
| 173 |
let join_b = std::thread::Builder::new() |
| 174 |
.name("two".to_owned()) |
| 175 |
.spawn(move || { |
| 176 |
w_b.wait(); |
| 177 |
d_b.wait(); |
| 178 |
}) |
| 179 |
.unwrap(); |
| 180 |
|
| 181 |
work_barrier.wait(); |
| 182 |
|
| 183 |
let mut found_one = false; |
| 184 |
let mut found_two = false; |
| 185 |
let mut summed_io = Io { |
| 186 |
rchar: 0, |
| 187 |
wchar: 0, |
| 188 |
syscr: 0, |
| 189 |
syscw: 0, |
| 190 |
read_bytes: 0, |
| 191 |
write_bytes: 0, |
| 192 |
cancelled_write_bytes: 0, |
| 193 |
}; |
| 194 |
for task in me.tasks().unwrap() { |
| 195 |
let task = task.unwrap(); |
| 196 |
let stat = task.stat().unwrap(); |
| 197 |
let status = task.status().unwrap(); |
| 198 |
let io = task.io().unwrap(); |
| 199 |
let syscall = task.syscall().unwrap(); |
| 200 |
|
| 201 |
summed_io.rchar += io.rchar; |
| 202 |
summed_io.wchar += io.wchar; |
| 203 |
summed_io.syscr += io.syscr; |
| 204 |
summed_io.syscw += io.syscw; |
| 205 |
summed_io.read_bytes += io.read_bytes; |
| 206 |
summed_io.write_bytes += io.write_bytes; |
| 207 |
summed_io.cancelled_write_bytes += io.cancelled_write_bytes; |
| 208 |
|
| 209 |
if stat.comm == "one" && status.name == "one" { |
| 210 |
found_one = true; |
| 211 |
assert!(io.rchar >= bytes_to_read); |
| 212 |
assert!(stat.utime >= 50, "utime({}) too small", stat.utime); |
| 213 |
assert!(matches!(syscall, Syscall::Blocked { .. }), "{:?}", syscall); |
| 214 |
} |
| 215 |
if stat.comm == "two" && status.name == "two" { |
| 216 |
found_two = true; |
| 217 |
// The process might read miscellaneous things from procfs or |
| 218 |
// things like /sys/devices/system/cpu/online; allow some small |
| 219 |
// reads. |
| 220 |
assert!(io.rchar < bytes_to_read); |
| 221 |
assert_eq!(io.wchar, 0); |
| 222 |
assert_eq!(stat.utime, 0); |
| 223 |
assert!(matches!(syscall, Syscall::Blocked { .. }), "{:?}", syscall); |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
let proc_io = me.io().unwrap(); |
| 228 |
// these should be mostly the same (though creating the IO struct in the above line will cause some IO to occur) |
| 229 |
println!("{:?}", summed_io); |
| 230 |
println!("{:?}", proc_io); |
| 231 |
|
| 232 |
// signal the threads to exit |
| 233 |
done_barrier.wait(); |
| 234 |
join_a.join().unwrap(); |
| 235 |
join_b.join().unwrap(); |
| 236 |
|
| 237 |
assert!(found_one); |
| 238 |
assert!(found_two); |
| 239 |
} |
| 240 |
|
| 241 |
#[test] |
| 242 |
fn test_task_children() { |
| 243 |
// Use tail -f /dev/null to create two infinite processes |
| 244 |
let mut command = process::Command::new("tail"); |
| 245 |
command.arg("-f").arg("/dev/null"); |
| 246 |
let (mut child1, mut child2) = (command.spawn().unwrap(), command.spawn().unwrap()); |
| 247 |
|
| 248 |
let tid = rustix::thread::gettid(); |
| 249 |
|
| 250 |
let children = crate::process::Process::myself() |
| 251 |
.unwrap() |
| 252 |
.task_from_tid(tid.as_raw_nonzero().get() as i32) |
| 253 |
.unwrap() |
| 254 |
.children() |
| 255 |
.unwrap(); |
| 256 |
|
| 257 |
assert!(children.contains(&child1.id())); |
| 258 |
assert!(children.contains(&child2.id())); |
| 259 |
|
| 260 |
child1.kill().unwrap(); |
| 261 |
child2.kill().unwrap(); |
| 262 |
} |
| 263 |
|
| 264 |
#[test] |
| 265 |
fn test_error_msg() { |
| 266 |
let myself = crate::process::Process::myself().unwrap(); |
| 267 |
// let mytask = myself.task_main_thread().unwrap(); |
| 268 |
for task in myself.tasks().unwrap() { |
| 269 |
let task = task.unwrap(); |
| 270 |
let err = task.generate_error().unwrap_err(); |
| 271 |
// make sure the contained path in the error is correct |
| 272 |
if let ProcError::NotFound(Some(p)) = err { |
| 273 |
assert!( |
| 274 |
p.display() |
| 275 |
.to_string() |
| 276 |
.ends_with(&format!("/task/{}/does_not_exist", task.tid)), |
| 277 |
"NotFound path({:?}) doesn't look right", |
| 278 |
p |
| 279 |
); |
| 280 |
} else { |
| 281 |
panic!("Unexpected error from task.generate_error()"); |
| 282 |
} |
| 283 |
} |
| 284 |
} |
| 285 |
} |