-
Notifications
You must be signed in to change notification settings - Fork 30
[cron] full implementation #382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Wandalen
wants to merge
4
commits into
rustcoreutils:main
Choose a base branch
from
Wandalen:cron
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,710
−2
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
[package] | ||
name = "posixutils-cron" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] | ||
gettext-rs = { workspace = true } | ||
plib = { path = "../plib" } | ||
clap = { workspace = true } | ||
libc = { workspace = true } | ||
chrono = { workspace = true } | ||
|
||
[[bin]] | ||
name = "crontab" | ||
path = "src/bin/crontab.rs" | ||
|
||
[[bin]] | ||
name = "crond" | ||
path = "src/bin/crond.rs" | ||
|
||
[[bin]] | ||
name = "main" | ||
path = "src/main.rs" | ||
|
||
[lib] | ||
path = "./src/lib.rs" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
// | ||
// Copyright (c) 2024 Hemi Labs, Inc. | ||
// | ||
// This file is part of the posixutils-rs project covered under | ||
// the MIT License. For the full license text, please see the LICENSE | ||
// file in the root directory of this project. | ||
// SPDX-License-Identifier: MIT | ||
// | ||
|
||
use chrono::Local; | ||
use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; | ||
use posixutils_cron::job::Database; | ||
use std::env; | ||
use std::error::Error; | ||
use std::fs; | ||
use std::str::FromStr; | ||
|
||
fn parse_cronfile(username: &str) -> Result<Database, Box<dyn Error>> { | ||
#[cfg(target_os = "linux")] | ||
let file = format!("/var/spool/cron/{username}"); | ||
#[cfg(target_os = "macos")] | ||
let file = format!("/var/at/tabs/{username}"); | ||
let s = fs::read_to_string(&file)?; | ||
Ok(s.lines() | ||
.filter_map(|x| Database::from_str(x).ok()) | ||
.fold(Database(vec![]), |acc, next| acc.merge(next))) | ||
} | ||
|
||
fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Needs signal handling |
||
setlocale(LocaleCategory::LcAll, ""); | ||
textdomain("posixutils-rs")?; | ||
bind_textdomain_codeset("posixutils-rs", "UTF-8")?; | ||
|
||
let Ok(logname) = env::var("LOGNAME") else { | ||
panic!("Could not obtain the user's logname.") | ||
}; | ||
|
||
// Daemon setup | ||
unsafe { | ||
use libc::*; | ||
|
||
let pid = fork(); | ||
if pid > 0 { | ||
return Ok(()); | ||
} | ||
|
||
setsid(); | ||
chdir(b"/\0" as *const _ as *const c_char); | ||
|
||
close(STDIN_FILENO); | ||
close(STDOUT_FILENO); | ||
close(STDERR_FILENO); | ||
} | ||
|
||
// Daemon code | ||
|
||
loop { | ||
let db = parse_cronfile(&logname)?; | ||
let Some(x) = db.nearest_job() else { | ||
sleep(60); | ||
continue; | ||
}; | ||
let Some(next_exec) = x.next_execution(&Local::now().naive_local()) else { | ||
sleep(60); | ||
continue; | ||
}; | ||
let now = Local::now(); | ||
let diff = now.naive_local() - next_exec; | ||
let sleep_time = diff.num_seconds(); | ||
|
||
if sleep_time < 60 { | ||
sleep(sleep_time as u32); | ||
x.run_job()?; | ||
} else { | ||
sleep(60); | ||
} | ||
} | ||
} | ||
|
||
fn sleep(target: u32) { | ||
unsafe { libc::sleep(target) }; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
// | ||
// Copyright (c) 2024 Hemi Labs, Inc. | ||
// | ||
// This file is part of the posixutils-rs project covered under | ||
// the MIT License. For the full license text, please see the LICENSE | ||
// file in the root directory of this project. | ||
// SPDX-License-Identifier: MIT | ||
// | ||
|
||
use clap::Parser; | ||
|
||
use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; | ||
use std::env; | ||
use std::fs; | ||
use std::fs::File; | ||
use std::io::{ErrorKind, Read, Result, Write}; | ||
use std::process::{exit, ExitStatus}; | ||
|
||
#[derive(Parser)] | ||
struct CronArgs { | ||
#[arg(short, long, help = gettext("edit user's crontab"))] | ||
edit: bool, | ||
#[arg(short, long, help = gettext("list user's crontab"))] | ||
list: bool, | ||
#[arg(short, long, help = gettext("delete user's crontab"))] | ||
remove: bool, | ||
#[arg(name = "FILE", help = gettext("file to replace user's current crontab with"))] | ||
file: Option<String>, | ||
} | ||
|
||
fn print_usage(err: &str) { | ||
let name = env::args().next().unwrap(); | ||
eprintln!("{name}: usage error: {err}"); | ||
eprintln!("usage:\t{name} [ FILE ]"); | ||
eprintln!("\t{name} [ -e | -l | -r ]"); | ||
eprintln!("\t-e\t- edit user's crontab"); | ||
eprintln!("\t-l\t- list user's crontab"); | ||
eprintln!("\t-r\t- delete user's crontab"); | ||
} | ||
|
||
fn list_crontab(path: &str) -> Result<String> { | ||
fs::read_to_string(path) | ||
} | ||
|
||
fn remove_crontab(path: &str) -> Result<()> { | ||
fs::remove_file(path) | ||
} | ||
|
||
fn edit_crontab(path: &str) -> Result<ExitStatus> { | ||
File::create(path)?; | ||
let editor = env::var("EDITOR").unwrap_or("vi".to_string()); | ||
let shell = env::var("SHELL").unwrap_or("sh".to_string()); | ||
let args = ["-c".to_string(), format!("{editor} {path}")]; | ||
std::process::Command::new(shell).args(args).status() | ||
} | ||
|
||
fn replace_crontab(from: &str, to: &str) -> Result<()> { | ||
let mut source = File::open(from)?; | ||
let mut target = File::create(to)?; | ||
let mut buffer = Vec::new(); | ||
|
||
source.read_to_end(&mut buffer)?; | ||
target.write_all(&buffer)?; | ||
|
||
Ok(()) | ||
} | ||
|
||
fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { | ||
setlocale(LocaleCategory::LcAll, ""); | ||
textdomain("posixutils-rs")?; | ||
bind_textdomain_codeset("posixutils-rs", "UTF-8")?; | ||
|
||
let args = CronArgs::parse(); | ||
let Ok(logname) = env::var("LOGNAME") else { | ||
println!("Could not obtain the user's logname."); | ||
exit(1); | ||
}; | ||
#[cfg(target_os = "linux")] | ||
let path = format!("/var/spool/cron/{logname}"); | ||
#[cfg(target_os = "macos")] | ||
let path = format!("/var/spool/cron/{logname}"); | ||
|
||
let opt_count = [args.edit, args.list, args.remove, args.file.is_some()] | ||
.into_iter() | ||
.map(|x| x as i32) | ||
.sum::<i32>(); | ||
if opt_count > 1 { | ||
print_usage("Too many options specified."); | ||
exit(1); | ||
} | ||
|
||
if opt_count < 1 { | ||
print_usage("Not enough options specified."); | ||
exit(1); | ||
} | ||
|
||
if args.edit { | ||
match edit_crontab(&path) { | ||
Ok(status) => exit(status.code().unwrap_or(0)), | ||
Err(err) => { | ||
match err.kind() { | ||
ErrorKind::NotFound => println!("No crontab file has been found."), | ||
ErrorKind::PermissionDenied => { | ||
println!("Permission to access user's crontab file denied.") | ||
} | ||
ErrorKind::Interrupted => println!("crontab was interrupted."), | ||
ErrorKind::OutOfMemory => println!("crontab exceeded available memory."), | ||
_ => println!("Unknown error: {}", err), | ||
} | ||
exit(1); | ||
} | ||
} | ||
} | ||
|
||
if args.list { | ||
match list_crontab(&path) { | ||
Ok(content) => println!("{}", content), | ||
Err(err) => { | ||
match err.kind() { | ||
ErrorKind::NotFound => println!("No crontab file has been found."), | ||
ErrorKind::PermissionDenied => { | ||
println!("Permission to access user's crontab file denied.") | ||
} | ||
ErrorKind::Interrupted => println!("crontab was interrupted."), | ||
ErrorKind::OutOfMemory => println!("crontab exceeded available memory."), | ||
_ => println!("Unknown error: {}", err), | ||
} | ||
exit(1); | ||
} | ||
} | ||
} | ||
|
||
if args.remove { | ||
match remove_crontab(&path) { | ||
Ok(()) => println!("Removed crontab file"), | ||
Err(err) => { | ||
match err.kind() { | ||
ErrorKind::NotFound => println!("No crontab file has been found."), | ||
ErrorKind::PermissionDenied => { | ||
println!("Permission to access user's crontab file denied.") | ||
} | ||
ErrorKind::Interrupted => println!("crontab was interrupted."), | ||
ErrorKind::OutOfMemory => println!("crontab exceeded available memory."), | ||
_ => println!("Unknown error: {}", err), | ||
} | ||
exit(1); | ||
} | ||
} | ||
} | ||
|
||
if let Some(file) = args.file { | ||
match replace_crontab(&file, &path) { | ||
Ok(()) => println!("Replaced crontab file with {file}"), | ||
Err(err) => { | ||
match err.kind() { | ||
ErrorKind::NotFound => { | ||
println!("Crontab file or user-specified file has not been found.") | ||
} | ||
ErrorKind::PermissionDenied => println!( | ||
"Permission to access user's crontab file or user-specified file denied." | ||
), | ||
ErrorKind::Interrupted => println!("crontab was interrupted."), | ||
ErrorKind::OutOfMemory => println!("crontab exceeded available memory."), | ||
_ => println!("Unknown error: {}", err), | ||
} | ||
exit(1); | ||
} | ||
} | ||
} | ||
|
||
Ok(()) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There should not be a binary called "main", just crontab and crond