| 1 | use std::{collections::VecDeque, fmt::Debug}; |
| 2 | |
| 3 | use humantime::parse_duration; |
| 4 | |
| 5 | use crate::{ |
| 6 | collection::processes::ProcessHarvest, |
| 7 | utils::data_units::*, |
| 8 | widgets::query::{ |
| 9 | And, NumericalQuery, Or, PrefixType, ProcessAttribute, QueryComparison, QueryOptions, |
| 10 | QueryProcessor, QueryResult, TimeQuery, |
| 11 | attribute::{new_numerical_attribute, new_string_attribute, new_time_attribute}, |
| 12 | error::QueryError, |
| 13 | }, |
| 14 | }; |
| 15 | |
| 16 | #[inline] |
| 17 | fn process_prefix_units(query: &mut VecDeque<String>, value: &mut f64) { |
| 18 | // If no unit, assume base. |
| 19 | // |
| 20 | // Furthermore, base must be PEEKED at initially, and will |
| 21 | // require (likely) prefix_type specific checks |
| 22 | // Lastly, if it *is* a unit, remember to POP! |
| 23 | if let Some(potential_unit) = query.front() { |
| 24 | if potential_unit.eq_ignore_ascii_case("tb") { |
| 25 | *value *= TERA_LIMIT_F64; |
| 26 | query.pop_front(); |
| 27 | } else if potential_unit.eq_ignore_ascii_case("tib") { |
| 28 | *value *= TEBI_LIMIT_F64; |
| 29 | query.pop_front(); |
| 30 | } else if potential_unit.eq_ignore_ascii_case("gb") { |
| 31 | *value *= GIGA_LIMIT_F64; |
| 32 | query.pop_front(); |
| 33 | } else if potential_unit.eq_ignore_ascii_case("gib") { |
| 34 | *value *= GIBI_LIMIT_F64; |
| 35 | query.pop_front(); |
| 36 | } else if potential_unit.eq_ignore_ascii_case("mb") { |
| 37 | *value *= MEGA_LIMIT_F64; |
| 38 | query.pop_front(); |
| 39 | } else if potential_unit.eq_ignore_ascii_case("mib") { |
| 40 | *value *= MEBI_LIMIT_F64; |
| 41 | query.pop_front(); |
| 42 | } else if potential_unit.eq_ignore_ascii_case("kb") { |
| 43 | *value *= KILO_LIMIT_F64; |
| 44 | query.pop_front(); |
| 45 | } else if potential_unit.eq_ignore_ascii_case("kib") { |
| 46 | *value *= KIBI_LIMIT_F64; |
| 47 | query.pop_front(); |
| 48 | } else if potential_unit.eq_ignore_ascii_case("b") { |
| 49 | query.pop_front(); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Either contains a further `Or` recursively, or an attribute that can be |
| 55 | /// queried, possibly as part of a larger query. |
| 56 | /// |
| 57 | /// In theory, this can be made generic to work on all table types, though for |
| 58 | /// now, it's hardcoded for processes. |
| 59 | #[derive(Debug)] |
| 60 | pub(super) enum Prefix { |
| 61 | /// True if the inner OR is true (allowing a recursive tree). |
| 62 | Or(Box<Or>), |
| 63 | /// A leaf node. |
| 64 | Attribute(ProcessAttribute), |
| 65 | /// Invert the match result of the inner prefix. |
| 66 | /// |
| 67 | /// TODO: Also support reading with "not". |
| 68 | Negate(Box<Prefix>), |
| 69 | } |
| 70 | |
| 71 | impl Prefix { |
| 72 | pub(super) fn check(&self, process: &ProcessHarvest, is_using_command: bool) -> bool { |
| 73 | match self { |
| 74 | Prefix::Or(or) => or.check(process, is_using_command), |
| 75 | Prefix::Attribute(attribute) => attribute.check(process, is_using_command), |
| 76 | Prefix::Negate(inner) => !inner.check(process, is_using_command), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn process_in_quotes( |
| 81 | query: &mut VecDeque<String>, options: &QueryOptions, |
| 82 | ) -> QueryResult<Self> { |
| 83 | if let Some(queue_top) = query.pop_front() { |
| 84 | if queue_top == "\"" { |
| 85 | // This means we hit something like "". Return an empty prefix, and to deal |
| 86 | // with the close quote checker, add one to the top of the |
| 87 | // stack. Ugly fix but whatever. |
| 88 | query.push_front("\"".to_string()); |
| 89 | |
| 90 | Ok(Prefix::Attribute(ProcessAttribute::Empty)) |
| 91 | } else { |
| 92 | let mut intern_string = vec![queue_top]; |
| 93 | |
| 94 | // TODO: I think this should consume the quote...? Might need to check the other |
| 95 | // spot we process quotes. |
| 96 | while let Some(next_str) = query.front() { |
| 97 | if next_str == "\"" { |
| 98 | break; |
| 99 | } else { |
| 100 | intern_string.push(query.pop_front().expect("we just peeked at the front")); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | let quoted_string = intern_string.join(" "); |
| 105 | |
| 106 | Ok(Prefix::Attribute(new_string_attribute( |
| 107 | PrefixType::Name, |
| 108 | "ed_string, |
| 109 | options, |
| 110 | )?)) |
| 111 | } |
| 112 | } else { |
| 113 | // Uh oh, there's nothing left in the stack, but we're inside quotes! |
| 114 | Err(QueryError::new("Missing closing quotation")) |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | impl QueryProcessor for Prefix { |
| 120 | fn process(query: &mut VecDeque<String>, options: &QueryOptions) -> QueryResult<Self> |
| 121 | where |
| 122 | Self: Sized, |
| 123 | { |
| 124 | if let Some(curr) = query.pop_front() { |
| 125 | if curr == "(" { |
| 126 | if query.is_empty() { |
| 127 | return Err(QueryError::new("Missing closing parentheses")); |
| 128 | } |
| 129 | |
| 130 | let mut list_of_ors = VecDeque::new(); |
| 131 | |
| 132 | while let Some(in_paren_query_top) = query.front() { |
| 133 | if in_paren_query_top != ")" { |
| 134 | list_of_ors.push_back(Or::process(query, options)?); |
| 135 | } else { |
| 136 | break; |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | let Some(front) = list_of_ors.pop_front() else { |
| 141 | return Err(QueryError::new("No values within parentheses group")); |
| 142 | }; |
| 143 | |
| 144 | // Now convert this back to a OR... |
| 145 | // TODO: is there a better way to do this than converting it? |
| 146 | let initial_or = Or { |
| 147 | lhs: And { |
| 148 | lhs: Prefix::Or(Box::new(front)), |
| 149 | rhs: None, |
| 150 | }, |
| 151 | rhs: None, |
| 152 | }; |
| 153 | let returned_or = list_of_ors.into_iter().fold(initial_or, |lhs, rhs| Or { |
| 154 | lhs: And { |
| 155 | lhs: Prefix::Or(Box::new(lhs)), |
| 156 | rhs: Some(Box::new(Prefix::Or(Box::new(rhs)))), |
| 157 | }, |
| 158 | rhs: None, |
| 159 | }); |
| 160 | |
| 161 | return if let Some(close_paren) = query.pop_front() { |
| 162 | if close_paren == ")" { |
| 163 | Ok(Prefix::Or(Box::new(returned_or))) |
| 164 | } else { |
| 165 | Err(QueryError::new("Missing closing parentheses")) |
| 166 | } |
| 167 | } else { |
| 168 | Err(QueryError::new("Missing closing parentheses")) |
| 169 | }; |
| 170 | } else if curr == ")" { |
| 171 | return Err(QueryError::new("Missing opening parentheses")); |
| 172 | } else if curr == "!" { |
| 173 | // Negation prefix: `!<expr>` inverts the match of the following |
| 174 | // expression. Handles: |
| 175 | // - Groups (`!(a or b)`) |
| 176 | // - Quoted names (`!"foo"`) |
| 177 | // - Bare names (`!foo`) |
| 178 | // - Stacked `!` (`!!foo`). |
| 179 | match query.front().map(|s| s.as_str()) { |
| 180 | None | Some("=") | Some(">") | Some("<") | Some(")") => { |
| 181 | return Err(QueryError::new( |
| 182 | "`!` must be followed by an expression; use `\"!\"` to match a literal `!`", |
| 183 | )); |
| 184 | } |
| 185 | Some(next) if next != "(" && next != "\"" && next != "!" => { |
| 186 | let next: Result<PrefixType, QueryError> = next.parse(); |
| 187 | if !matches!(next, Ok(PrefixType::Name)) { |
| 188 | return Err(QueryError::new( |
| 189 | "`!` cannot be applied to a prefix keyword; use `!=`, `<=`, `>=` or group with `!(...)` instead", |
| 190 | )); |
| 191 | } |
| 192 | } |
| 193 | _ => {} |
| 194 | } |
| 195 | let inner = Prefix::process(query, options)?; |
| 196 | return Ok(Prefix::Negate(Box::new(inner))); |
| 197 | } else if curr == "\"" { |
| 198 | // Similar to parentheses, trap and check for missing closing quotes. Note, |
| 199 | // however, that we will DIRECTLY call another process_prefix |
| 200 | // call... |
| 201 | |
| 202 | let prefix = Prefix::process_in_quotes(query, options)?; |
| 203 | return if let Some(close_quote) = query.pop_front() { |
| 204 | if close_quote == "\"" { |
| 205 | Ok(prefix) |
| 206 | } else { |
| 207 | Err(QueryError::new("Missing closing quotation")) |
| 208 | } |
| 209 | } else { |
| 210 | Err(QueryError::new("Missing closing quotation")) |
| 211 | }; |
| 212 | } else { |
| 213 | // Get prefix type. |
| 214 | let prefix_type = curr.parse::<PrefixType>()?; |
| 215 | |
| 216 | // TODO: Separate these cases here and below. |
| 217 | let content = if let PrefixType::Name = prefix_type { |
| 218 | Some(curr) |
| 219 | } else { |
| 220 | query.pop_front() |
| 221 | }; |
| 222 | |
| 223 | if let Some(content) = content { |
| 224 | match &prefix_type { |
| 225 | PrefixType::Name => { |
| 226 | return Ok(Prefix::Attribute(new_string_attribute( |
| 227 | prefix_type, |
| 228 | &content, |
| 229 | options, |
| 230 | )?)); |
| 231 | } |
| 232 | PrefixType::Pid | PrefixType::State | PrefixType::User => { |
| 233 | // We have to check if someone put an (in)equality check... |
| 234 | if content == "=" || content == "!=" { |
| 235 | let negate = content.starts_with('!'); |
| 236 | |
| 237 | // Check next string if possible |
| 238 | if let Some(string_value) = query.pop_front() { |
| 239 | if string_value == "!" { |
| 240 | return Err(QueryError::new( |
| 241 | "`!` is reserved; use `\"!\"` to match the literal character", |
| 242 | )); |
| 243 | } |
| 244 | // TODO: [Query] Need to consider the following cases: |
| 245 | // - (test) |
| 246 | // - (test |
| 247 | // - test) |
| 248 | // These are split into 2 to 3 different strings due to |
| 249 | // parentheses being |
| 250 | // delimiters in our query system. |
| 251 | // |
| 252 | // Do we want these to be valid? They should, as a string, |
| 253 | // right? |
| 254 | |
| 255 | // We also must check if this value is wrapped in quotes! |
| 256 | let final_value = if string_value == "\"" { |
| 257 | let mut intern_string = vec![]; |
| 258 | |
| 259 | // Keep parsing until we either hit another quotation or we |
| 260 | // error. |
| 261 | while let Some(next_string) = query.pop_front() { |
| 262 | if next_string == "\"" { |
| 263 | break; |
| 264 | } |
| 265 | |
| 266 | intern_string.push(next_string); |
| 267 | } |
| 268 | |
| 269 | intern_string.join(" ") |
| 270 | } else { |
| 271 | string_value |
| 272 | }; |
| 273 | |
| 274 | let inner_attribute = Prefix::Attribute(new_string_attribute( |
| 275 | prefix_type, |
| 276 | &final_value, |
| 277 | options, |
| 278 | )?); |
| 279 | |
| 280 | return Ok(if negate { |
| 281 | Prefix::Negate(Box::new(inner_attribute)) |
| 282 | } else { |
| 283 | inner_attribute |
| 284 | }); |
| 285 | } |
| 286 | } else if content == "!" { |
| 287 | return Err(QueryError::new( |
| 288 | "`!` is reserved; use `\"!\"` to match the literal character", |
| 289 | )); |
| 290 | } else { |
| 291 | return Ok(Prefix::Attribute(new_string_attribute( |
| 292 | prefix_type, |
| 293 | &content, |
| 294 | options, |
| 295 | )?)); |
| 296 | } |
| 297 | } |
| 298 | PrefixType::Time => { |
| 299 | let mut condition: Option<QueryComparison> = None; |
| 300 | let mut duration_string: Option<String> = None; |
| 301 | |
| 302 | if content == "=" { |
| 303 | condition = Some(QueryComparison::Equal); |
| 304 | duration_string = query.pop_front(); |
| 305 | } else if content == "!=" { |
| 306 | condition = Some(QueryComparison::NotEqual); |
| 307 | duration_string = query.pop_front(); |
| 308 | } else if content == ">" || content == "<" { |
| 309 | if let Some(queue_next) = query.pop_front() { |
| 310 | if queue_next == "=" { |
| 311 | condition = Some(if content == ">" { |
| 312 | QueryComparison::GreaterOrEqual |
| 313 | } else { |
| 314 | QueryComparison::LessOrEqual |
| 315 | }); |
| 316 | duration_string = query.pop_front(); |
| 317 | } else { |
| 318 | condition = Some(if content == ">" { |
| 319 | QueryComparison::Greater |
| 320 | } else { |
| 321 | QueryComparison::Less |
| 322 | }); |
| 323 | duration_string = Some(queue_next); |
| 324 | } |
| 325 | } else { |
| 326 | return Err(QueryError::missing_value()); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | if let Some(condition) = condition { |
| 331 | let duration = parse_duration( |
| 332 | &duration_string.ok_or(QueryError::missing_value())?, |
| 333 | ) |
| 334 | .map_err(|err| QueryError::new(err.to_string()))?; |
| 335 | |
| 336 | return Ok(Prefix::Attribute(new_time_attribute( |
| 337 | prefix_type, |
| 338 | TimeQuery { |
| 339 | condition, |
| 340 | duration, |
| 341 | }, |
| 342 | )?)); |
| 343 | } |
| 344 | } |
| 345 | _ => { |
| 346 | // Assume it's some numerical value. Now we gotta parse the content... yay. |
| 347 | // Note that for numerical parsing, we handle unit parsing later, not here. |
| 348 | |
| 349 | let mut condition: Option<QueryComparison> = None; |
| 350 | let mut value: Option<f64> = None; |
| 351 | |
| 352 | // TODO: Jeez, what the heck did I write here... add some tests and |
| 353 | // clean this up in the future. |
| 354 | if content == "=" { |
| 355 | condition = Some(QueryComparison::Equal); |
| 356 | if let Some(queue_next) = query.pop_front() { |
| 357 | value = queue_next.parse::<f64>().ok(); |
| 358 | } else { |
| 359 | return Err(QueryError::missing_value()); |
| 360 | } |
| 361 | } else if content == "!=" { |
| 362 | condition = Some(QueryComparison::NotEqual); |
| 363 | if let Some(queue_next) = query.pop_front() { |
| 364 | value = queue_next.parse::<f64>().ok(); |
| 365 | } else { |
| 366 | return Err(QueryError::missing_value()); |
| 367 | } |
| 368 | } else if content == ">" || content == "<" { |
| 369 | // We also have to check if the next string is an "="... |
| 370 | if let Some(queue_next) = query.pop_front() { |
| 371 | if queue_next == "=" { |
| 372 | condition = Some(if content == ">" { |
| 373 | QueryComparison::GreaterOrEqual |
| 374 | } else { |
| 375 | QueryComparison::LessOrEqual |
| 376 | }); |
| 377 | if let Some(queue_next_next) = query.pop_front() { |
| 378 | value = queue_next_next.parse::<f64>().ok(); |
| 379 | } else { |
| 380 | return Err(QueryError::missing_value()); |
| 381 | } |
| 382 | } else { |
| 383 | condition = Some(if content == ">" { |
| 384 | QueryComparison::Greater |
| 385 | } else { |
| 386 | QueryComparison::Less |
| 387 | }); |
| 388 | value = queue_next.parse::<f64>().ok(); |
| 389 | } |
| 390 | } else { |
| 391 | return Err(QueryError::missing_value()); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | if let Some(condition) = condition |
| 396 | && let Some(read_value) = value |
| 397 | { |
| 398 | // Note that the values *might* have a unit or need to be parsed |
| 399 | // differently based on the |
| 400 | // prefix type! |
| 401 | |
| 402 | // TODO: Support this without spaces? |
| 403 | |
| 404 | let mut value = read_value; |
| 405 | |
| 406 | match prefix_type { |
| 407 | PrefixType::MemBytes |
| 408 | | PrefixType::ReadPerSecond |
| 409 | | PrefixType::WritePerSecond |
| 410 | | PrefixType::TotalRead |
| 411 | | PrefixType::TotalWrite => { |
| 412 | process_prefix_units(query, &mut value); |
| 413 | } |
| 414 | #[cfg(feature = "gpu")] |
| 415 | PrefixType::GpuMemoryBytes => { |
| 416 | process_prefix_units(query, &mut value); |
| 417 | } |
| 418 | _ => {} |
| 419 | } |
| 420 | |
| 421 | return Ok(Prefix::Attribute(new_numerical_attribute( |
| 422 | prefix_type, |
| 423 | NumericalQuery { condition, value }, |
| 424 | )?)); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | } else { |
| 429 | return Err(QueryError::new("Missing argument for search prefix")); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | // TODO: Give more information here (e.g. closest query?), though this is moreso |
| 435 | // meant as a fallback. |
| 436 | Err(QueryError::new("Invalid query")) |
| 437 | } |
| 438 | } |