feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
pub async fn health(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
let Json(devices) = crate::api::devices(State(s), h, Path(t)).await?;
|
||||
Ok(Json(
|
||||
json!({"items":devices["items"],"next_cursor":null,"completeness":devices["completeness"],"truncated":devices["truncated"],"as_of":Utc::now(),"health":"unknown","source_id":"stored_agent_observations"}),
|
||||
))
|
||||
}
|
||||
#[derive(Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LogQuery {
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub unit: String,
|
||||
pub since: DateTime<Utc>,
|
||||
pub until: DateTime<Utc>,
|
||||
pub max_lines: u32,
|
||||
pub live: bool,
|
||||
pub idempotency_key: Option<String>,
|
||||
}
|
||||
pub async fn query(
|
||||
s: &crate::State,
|
||||
p: &crate::auth::Principal,
|
||||
i: LogQuery,
|
||||
) -> Result<Value, crate::jobs::Error> {
|
||||
crate::jobs::scope(p, i.tenant_id, true)?;
|
||||
let action = rmm_domain::jobs::Action::QueryLogs {
|
||||
unit: i.unit.clone(),
|
||||
since: i.since,
|
||||
until: i.until,
|
||||
max_lines: i.max_lines,
|
||||
};
|
||||
if !action.validate() {
|
||||
return Err(crate::jobs::Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"VALIDATION_ERROR",
|
||||
));
|
||||
}
|
||||
if i.live {
|
||||
let request_hash = rmm_domain::jobs::hash(&serde_json::to_vec(&i)?);
|
||||
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
let key = i
|
||||
.idempotency_key
|
||||
.as_ref()
|
||||
.filter(|k| !k.is_empty() && k.len() <= 128)
|
||||
.ok_or(crate::jobs::Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
if let Some(row)=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(key).fetch_optional(&mut *dedup).await?{
|
||||
if row.get::<String,_>("request_hash")!=request_hash{return Err(crate::jobs::Error(StatusCode::CONFLICT,"IDEMPOTENCY_CONFLICT"))}
|
||||
let plan=row.get("plan_id");let key=key.clone();dedup.commit().await?;
|
||||
return crate::jobs::submit(s,p,i.tenant_id,plan,crate::jobs::Submit{idempotency_key:key}).await;
|
||||
}
|
||||
dedup.commit().await?;
|
||||
let key = i.idempotency_key.ok_or(crate::jobs::Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
let plan = crate::jobs::plan(
|
||||
s,
|
||||
p,
|
||||
i.tenant_id,
|
||||
crate::jobs::PlanInput {
|
||||
targets: crate::jobs::Targets {
|
||||
asset_ids: vec![i.asset_id],
|
||||
},
|
||||
action,
|
||||
execution_identity: "agent_service".into(),
|
||||
schedule: crate::jobs::Schedule {
|
||||
not_before: Utc::now(),
|
||||
start_before: Utc::now() + chrono::Duration::hours(1),
|
||||
},
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 262144,
|
||||
rollout: crate::jobs::Rollout {
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
},
|
||||
reason: format!("Requested live logs for {}", i.unit),
|
||||
artifact_ids: vec![],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let id = plan["plan_id"]
|
||||
.as_str()
|
||||
.and_then(|v| Uuid::parse_str(v).ok())
|
||||
.ok_or(crate::jobs::Error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO live_query_requests VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(i.tenant_id)
|
||||
.bind(&p.name)
|
||||
.bind(&key)
|
||||
.bind(&request_hash)
|
||||
.bind(id)
|
||||
.execute(&mut *dedup)
|
||||
.await?;
|
||||
let canonical=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&key).fetch_one(&mut *dedup).await?;
|
||||
if canonical.get::<String, _>("request_hash") != request_hash {
|
||||
return Err(crate::jobs::Error(
|
||||
StatusCode::CONFLICT,
|
||||
"IDEMPOTENCY_CONFLICT",
|
||||
));
|
||||
}
|
||||
let id = canonical.get("plan_id");
|
||||
dedup.commit().await?;
|
||||
return crate::jobs::submit(
|
||||
s,
|
||||
p,
|
||||
i.tenant_id,
|
||||
id,
|
||||
crate::jobs::Submit {
|
||||
idempotency_key: key,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM assets WHERE asset_id=$1)")
|
||||
.bind(i.asset_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !exists {
|
||||
return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
let rows=sqlx::query("SELECT j.job_id,j.payload,j.result FROM jobs j WHERE j.asset_id=$1 AND j.state='succeeded' AND j.result IS NOT NULL ORDER BY job_id LIMIT 100").bind(i.asset_id).fetch_all(&mut *tx).await?;
|
||||
let mut items = Vec::new();
|
||||
let mut size = 0;
|
||||
let mut lines = 0usize;
|
||||
let mut truncated = false;
|
||||
for r in rows {
|
||||
let payload: rmm_domain::jobs::JobPayload =
|
||||
serde_json::from_slice(&r.get::<Vec<u8>, _>("payload"))?;
|
||||
if let rmm_domain::jobs::Action::QueryLogs {
|
||||
unit, since, until, ..
|
||||
} = payload.action
|
||||
&& unit == i.unit
|
||||
&& since >= i.since
|
||||
&& until <= i.until
|
||||
{
|
||||
let result: Value = r.get("result");
|
||||
let len = result.to_string().len();
|
||||
let stdout = result.get("stdout").and_then(Value::as_array);
|
||||
let count = stdout
|
||||
.map(|bytes| {
|
||||
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
|
||||
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if size + len > 262144 || lines + count > i.max_lines as usize {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
size += len;
|
||||
lines += count;
|
||||
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":unit,"observed_from":since,"observed_until":until,"result":result}));
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(
|
||||
json!({"state":"ready","items":items,"next_cursor":null,"completeness":"partial","truncated":truncated,"as_of":Utc::now(),"source_id":"authorized_job_results"}),
|
||||
)
|
||||
}
|
||||
pub async fn logs(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Json(i): Json<LogQuery>,
|
||||
) -> Result<Json<Value>, crate::jobs::Error> {
|
||||
let p = s
|
||||
.auth
|
||||
.principal(&s, &h, i.live)
|
||||
.await
|
||||
.map_err(|s| crate::jobs::Error(s, "FORBIDDEN"))?;
|
||||
if t != i.tenant_id {
|
||||
return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
Ok(Json(query(&s, &p, i).await?))
|
||||
}
|
||||
Reference in New Issue
Block a user