Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# coreutils (uutils)
# * see the repository LICENSE, README, and CONTRIBUTING files for more information

# spell-checker:ignore (libs) bigdecimal datetime fundu gethostid kqueue libselinux mangen memmap procfs uuhelp
# spell-checker:ignore (libs) bigdecimal datetime serde bincode fundu gethostid kqueue libselinux mangen memmap procfs uuhelp

[package]
name = "coreutils"
Expand Down Expand Up @@ -491,10 +491,11 @@ tempfile = { workspace = true }
time = { workspace = true, features = ["local-offset"] }
unindent = "0.2.3"
uucore = { workspace = true, features = [
"entries",
"mode",
"entries",
"process",
"signals",
"utmpx",
] }
walkdir = { workspace = true }
hex-literal = "0.4.1"
Expand All @@ -509,6 +510,14 @@ rlimit = "0.10.1"
rand_pcg = "0.3.1"
xattr = { workspace = true }

# Specifically used in test_uptime::test_uptime_with_file_containing_valid_boot_time_utmpx_record
# to deserialize a utmpx struct into a binary file
[target.'cfg(all(target_family= "unix",not(target_os = "macos")))'.dev-dependencies]
serde = { version = "1.0.202", features = ["derive"] }
bincode = { version = "1.3.3" }
serde-big-array = "0.5.1"


[build-dependencies]
phf_codegen = { workspace = true }

Expand Down
1 change: 1 addition & 0 deletions src/uu/uptime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ path = "src/uptime.rs"
chrono = { workspace = true }
clap = { workspace = true }
uucore = { workspace = true, features = ["libc", "utmpx"] }
thiserror = { workspace = true }

[[bin]]
name = "uptime"
Expand Down
190 changes: 169 additions & 21 deletions src/uu/uptime/src/platform/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,166 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

// spell-checker:ignore (ToDO) getloadavg upsecs updays nusers loadavg boottime uphours upmins
// spell-checker:ignore getloadavg behaviour loadavg uptime upsecs updays upmins uphours boottime nusers utmpxname

use crate::options;
use crate::uu_app;

use chrono::{Local, TimeZone, Utc};
use clap::ArgMatches;
use std::ffi::OsString;
use std::fs;
use std::io;
use std::os::unix::fs::FileTypeExt;
use thiserror::Error;
use uucore::error::set_exit_code;
use uucore::error::UError;
use uucore::show_error;

use uucore::libc::time_t;

use uucore::error::{UResult, USimpleError};

#[cfg(unix)]
use uucore::libc::getloadavg;

#[cfg(windows)]
extern "C" {
fn GetTickCount() -> uucore::libc::uint32_t;
}
#[derive(Debug, Error)]
pub enum UptimeError {
// io::Error wrapper
#[error("couldn't get boot time: {0}")]
IoErr(#[from] io::Error),

#[error("couldn't get boot time: Is a directory")]
TargetIsDir,

#[error("couldn't get boot time: Illegal seek")]
TargetIsFifo,
#[error("extra operand '{0}'")]
ExtraOperandError(String),
}
impl UError for UptimeError {
fn code(&self) -> i32 {
1
}
}

pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?;
let argument = matches.get_many::<OsString>(options::PATH);

let (boot_time, user_count) = process_utmpx();
let uptime = get_uptime(boot_time);
if uptime < 0 {
Err(USimpleError::new(1, "could not retrieve system uptime"))
} else {
if matches.get_flag(options::SINCE) {
let initial_date = Local
.timestamp_opt(Utc::now().timestamp() - uptime, 0)
.unwrap();
println!("{}", initial_date.format("%Y-%m-%d %H:%M:%S"));
// Switches to default uptime behaviour if there is no argument
if argument.is_none() {
return default_uptime(&matches);
}
let mut arg_iter = argument.unwrap();

let file_path = arg_iter.next().unwrap();
if let Some(path) = arg_iter.next() {
// Uptime doesn't attempt to calculate boot time if there is extra arguments.
// Its a fatal error
show_error!(
"{}",
UptimeError::ExtraOperandError(path.to_owned().into_string().unwrap())
);
set_exit_code(1);
return Ok(());
}
uptime_with_file(file_path)
}

#[cfg(unix)]
fn uptime_with_file(file_path: &OsString) -> UResult<()> {
// Uptime will print loadavg and time to stderr unless we encounter an extra operand.
let mut non_fatal_error = false;

// process_utmpx_from_file() doesn't detect or report failures, we check if the path is valid
// before proceeding with more operations.
let md_res = fs::metadata(file_path);
if let Ok(md) = md_res {
if md.is_dir() {
show_error!("{}", UptimeError::TargetIsDir);
non_fatal_error = true;
set_exit_code(1);
}
if md.file_type().is_fifo() {
show_error!("{}", UptimeError::TargetIsFifo);
non_fatal_error = true;
set_exit_code(1);
}
} else if let Err(e) = md_res {
non_fatal_error = true;
set_exit_code(1);
show_error!("{}", UptimeError::IoErr(e));
}
// utmpxname() returns an -1 , when filename doesn't end with 'x' or its too long.
// Reference: `<https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/utmpxname.3.html>`

#[cfg(target_os = "macos")]
{
use std::os::unix::ffi::OsStrExt;
let bytes = file_path.as_os_str().as_bytes();

if bytes[bytes.len() - 1] != b'x' {
show_error!("couldn't get boot time");
print_time();
print!("up ???? days ??:??,");
print_nusers(0);
print_loadavg();
set_exit_code(1);
return Ok(());
}
}

if non_fatal_error {
print_time();
let upsecs = uptime;
print_uptime(upsecs);
print_nusers(user_count);
print!("up ???? days ??:??,");
print_nusers(0);
print_loadavg();
return Ok(());
}

print_time();
let (boot_time, user_count) = process_utmpx_from_file(file_path);
if let Some(time) = boot_time {
let upsecs = get_uptime_from_boot_time(time);
print_uptime(upsecs);
} else {
show_error!("couldn't get boot time");
set_exit_code(1);

print!("up ???? days ??:??,");
}

Ok(())
print_nusers(user_count);
print_loadavg();

Ok(())
}

/// Default uptime behaviour i.e. when no file argument is given.
fn default_uptime(matches: &ArgMatches) -> UResult<()> {
let (boot_time, user_count) = process_utmpx();
let uptime = get_uptime(boot_time);
if matches.get_flag(options::SINCE) {
let initial_date = Local
.timestamp_opt(Utc::now().timestamp() - uptime, 0)
.unwrap();
println!("{}", initial_date.format("%Y-%m-%d %H:%M:%S"));
return Ok(());
}

if uptime < 0 {
return Err(USimpleError::new(1, "could not retrieve system uptime"));
}
print_time();
let upsecs = uptime;
print_uptime(upsecs);
print_nusers(user_count);
print_loadavg();

Ok(())
}

#[cfg(unix)]
Expand Down Expand Up @@ -97,23 +214,54 @@ fn process_utmpx() -> (Option<time_t>, usize) {
(boot_time, nusers)
}

#[cfg(unix)]
fn process_utmpx_from_file(file: &OsString) -> (Option<time_t>, usize) {
use uucore::utmpx::*;

let mut nusers = 0;
let mut boot_time = None;

for line in Utmpx::iter_all_records_from(file) {
match line.record_type() {
USER_PROCESS => nusers += 1,
BOOT_TIME => {
let dt = line.login_time();
if dt.unix_timestamp() > 0 {
boot_time = Some(dt.unix_timestamp() as time_t);
}
}
_ => continue,
}
}
(boot_time, nusers)
}

#[cfg(windows)]
fn process_utmpx() -> (Option<time_t>, usize) {
(None, 0) // TODO: change 0 to number of users
}

fn print_nusers(nusers: usize) {
match nusers.cmp(&1) {
std::cmp::Ordering::Less => print!(" 0 users, "),
std::cmp::Ordering::Equal => print!("1 user, "),
std::cmp::Ordering::Greater => print!("{nusers} users, "),
_ => {}
};
}

fn print_time() {
let local_time = Local::now().time();

print!(" {} ", local_time.format("%H:%M:%S"));
print!(" {} ", local_time.format("%H:%M:%S"));
}

fn get_uptime_from_boot_time(boot_time: time_t) -> i64 {
let now = Local::now().timestamp();
#[cfg(target_pointer_width = "64")]
let boottime: i64 = boot_time;
#[cfg(not(target_pointer_width = "64"))]
let boottime: i64 = boot_time.into();
now - boottime
}

#[cfg(unix)]
Expand Down Expand Up @@ -154,8 +302,8 @@ fn print_uptime(upsecs: i64) {
match updays.cmp(&1) {
std::cmp::Ordering::Equal => print!("up {updays:1} day, {uphours:2}:{upmins:02}, "),
std::cmp::Ordering::Greater => {
print!("up {updays:1} days, {uphours:2}:{upmins:02}, ");
print!("up {updays:1} days {uphours:2}:{upmins:02}, ");
}
_ => print!("up {uphours:2}:{upmins:02}, "),
_ => print!("up {uphours:2}:{upmins:02}, "),
};
}
10 changes: 9 additions & 1 deletion src/uu/uptime/src/uptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use clap::{crate_version, Arg, ArgAction, Command};
use clap::{builder::ValueParser, crate_version, Arg, ArgAction, Command, ValueHint};

use uucore::{format_usage, help_about, help_usage};

Expand All @@ -13,6 +13,7 @@ const ABOUT: &str = help_about!("uptime.md");
const USAGE: &str = help_usage!("uptime.md");
pub mod options {
pub static SINCE: &str = "since";
pub static PATH: &str = "path";
}

#[uucore::main]
Expand All @@ -31,4 +32,11 @@ pub fn uu_app() -> Command {
.help("system up since")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::PATH)
.help("file to search boot time from")
.action(ArgAction::Append)
.value_parser(ValueParser::os_string())
.value_hint(ValueHint::AnyPath),
)
}
Loading