Files
rust-discovery/crates/agent/src/jobs.rs
T

239 lines
9.6 KiB
Rust

use anyhow::Result;
#[cfg(test)]
use prost::Message;
#[cfg(test)]
use rmm_domain::jobs::hash;
use rmm_domain::jobs::{Action, JobPayload};
use rmm_privileged_helper::Binding;
use rmm_protocol::*;
use rusqlite::Connection;
#[cfg(test)]
use uuid::Uuid;
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
let Action::RunScript { interpreter, .. } = &job.action else {
return false;
};
if unsafe { libc::geteuid() } == 0
|| !job.action.valid_execution_identity(&job.execution_identity)
{
return false;
}
match job.execution_identity.as_str() {
"root" => {
job.action.full_maintenance()
&& binding.is_some_and(|b| crate::helper_sync::script_supported(b, job))
}
"agent_service" => match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
},
_ => false,
}
}
pub use rmm_agent_core::jobs::{
ack, denied_request, event, events, interrupted, interrupted_request, next, no_start,
permit_request, recover_interrupted_outcome, requesting, reserve_request, result, transition,
};
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
supported_with_binding(job, Some(binding))
})
}
/// all new effects stop. Do not paper over this with a new start request.
#[cfg(test)]
pub fn begin_session(db: &Connection) -> Result<bool> {
let inserted = db.execute(
"INSERT OR IGNORE INTO safety(key,value) VALUES('connected','1')",
[],
)?;
Ok(inserted == 1)
}
#[cfg(test)]
pub fn uncertain(db: &Connection) -> Result<Vec<(JobOffer, String)>> {
let mut statement = db.prepare(
"SELECT offer,grant_id FROM job_attempts WHERE state IN ('requesting','running')",
)?;
let bytes = statement
.query_map([], |r| {
Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
bytes
.into_iter()
.map(|(bytes, grant)| Ok((JobOffer::decode(bytes.as_slice())?, grant)))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::storage;
fn fixture() -> (std::path::PathBuf, Binding, JobOffer) {
let path = std::env::temp_dir().join(format!("rmm-agent-jobs-{}", Uuid::new_v4()));
storage::prepare_dir(&path).unwrap();
let binding = Binding {
tenant_id: Uuid::new_v4(),
asset_id: Uuid::new_v4(),
agent_id: Uuid::new_v4(),
enrollment_generation: 1,
assignment_version: 2,
public_key_hex: "00".repeat(32),
};
let now = chrono::Utc::now();
let job = JobPayload {
schema_version: 1,
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: 1,
assignment_version: 2,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(10),
max_runtime_seconds: 10,
max_output_bytes: 4096,
};
let bytes = rmm_domain::jobs::encode(&job).unwrap();
let offer = JobOffer {
job_id: job.job_id.to_string(),
attempt_id: job.attempt_id.to_string(),
authorization_id: Uuid::new_v4().to_string(),
plan_hash: hash(b"plan"),
job_payload_hash: hash(&bytes),
payload_bytes: bytes,
};
(path, binding, offer)
}
#[test]
fn sqlite_reopen_offer_dedup_and_no_new_permit_after_ambiguity() {
let (path, binding, offer) = fixture();
let mut db = storage::open(&path).unwrap();
let job = binding.job(&offer.payload_bytes).unwrap();
if unsafe { libc::geteuid() } == 0 {
assert!(!supported_with_binding(&job, Some(&binding)));
assert!(accept(&db, &binding, &offer).is_err());
} else {
assert!(accept(&db, &binding, &offer).unwrap());
assert!(!accept(&db, &binding, &offer).unwrap());
let mut changed = offer.clone();
changed.plan_hash = hash(b"different plan");
assert!(accept(&db, &binding, &changed).is_err());
assert!(begin_session(&db).unwrap());
let envelope = Envelope {
message_id: Uuid::new_v4().to_string(),
sequence: storage::next_sequence(&mut db).unwrap(),
payload: Some(Payload::JobAccepted(JobAccepted {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
job_payload_hash: offer.job_payload_hash.clone(),
journal_proof: "durable".into(),
})),
..Default::default()
};
event(&db, &envelope).unwrap();
reserve_request(&db, &offer).unwrap();
assert!(reserve_request(&db, &offer).is_err());
assert!(next(&db).unwrap().is_none());
drop(db);
db = storage::open(&path).unwrap();
assert!(!begin_session(&db).unwrap());
assert_eq!(uncertain(&db).unwrap().len(), 1);
assert_eq!(events(&db).unwrap(), vec![envelope.clone()]);
assert_eq!(transition(&db, &offer, "unknown", "").unwrap(), 1);
assert!(next(&db).unwrap().is_none());
assert!(!accept(&db, &binding, &offer).unwrap());
ack(&mut db, &envelope.message_id).unwrap();
assert!(events(&db).unwrap().is_empty());
assert!(next(&db).unwrap().is_none());
}
drop(db);
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn cancellation_expiry_and_atomic_event_rollback() {
let (path, binding, offer) = fixture();
let mut db = storage::open(&path).unwrap();
if unsafe { libc::geteuid() } != 0 {
accept(&db, &binding, &offer).unwrap();
db.execute("UPDATE job_attempts SET cancel_requested=1", [])
.unwrap();
assert!(reserve_request(&db, &offer).is_err());
let cancelled = no_start("cancelled", "CANCELLED");
assert_eq!(cancelled.evidence["not_started"], true);
let tx = db.transaction().unwrap();
assert_eq!(transition(&tx, &offer, "cancelled", "").unwrap(), 1);
let e = Envelope {
message_id: Uuid::new_v4().to_string(),
payload: Some(Payload::JobResult(result(&offer, 1, "", cancelled))),
..Default::default()
};
event(&tx, &e).unwrap();
tx.rollback().unwrap();
assert!(events(&db).unwrap().is_empty());
assert!(next(&db).unwrap().is_none());
let expired = no_start("expired", "DEADLINE_EXPIRED");
assert_eq!(expired.evidence["not_started"], true);
assert_eq!(transition(&db, &offer, "expired", "").unwrap(), 1);
assert!(next(&db).unwrap().is_none());
} else {
assert!(accept(&db, &binding, &offer).is_err());
}
drop(db);
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn legacy_actions_and_unbound_root_are_rejected_before_any_reservation() {
let (path, binding, offer) = fixture();
let mut job = binding.job(&offer.payload_bytes).unwrap();
job.execution_identity = "root".into();
assert!(!supported_with_binding(&job, Some(&binding)));
for identity in ["agent_service", "root"] {
job.execution_identity = identity.into();
job.action = Action::Reboot {
reason: "legacy fixture".into(),
reconnect_timeout_seconds: 60,
dependency_group: "test".into(),
};
assert!(!supported_with_binding(&job, Some(&binding)));
job.action = Action::RefreshInventory {
scope: "linux.base".into(),
};
assert!(!supported_with_binding(&job, Some(&binding)));
}
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn scheduled_future_job_does_not_starve_ready_job() {
let (path, binding, offer) = fixture();
let db = storage::open(&path).unwrap();
if unsafe { libc::geteuid() } != 0 {
let mut future = offer.clone();
let mut job: JobPayload = serde_json::from_slice(&future.payload_bytes).unwrap();
job.job_id = Uuid::new_v4();
job.attempt_id = Uuid::new_v4();
job.not_before = chrono::Utc::now() + chrono::Duration::minutes(1);
future.job_id = job.job_id.to_string();
future.attempt_id = job.attempt_id.to_string();
future.payload_bytes = rmm_domain::jobs::encode(&job).unwrap();
future.job_payload_hash = hash(&future.payload_bytes);
accept(&db, &binding, &future).unwrap();
accept(&db, &binding, &offer).unwrap();
assert_eq!(next(&db).unwrap().unwrap().job_id, offer.job_id);
}
drop(db);
std::fs::remove_dir_all(path).unwrap();
}
}