Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
49 changes: 46 additions & 3 deletions jans-cedarling/cedarling/src/lock/health_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! The `HealthTicker` collects statuses from all registered checks on each tick.

use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::sync::{Arc, RwLock};

use serde::{Deserialize, Serialize};
Expand All @@ -22,15 +23,39 @@ pub(crate) enum HealthStatus {
Failure,
}

impl std::fmt::Display for HealthStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl Display for HealthStatus {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
HealthStatus::Success => write!(f, "success"),
HealthStatus::Failure => write!(f, "failure"),
}
}
}
Comment thread
dagregi marked this conversation as resolved.

/// Overall system health derived from registered checks
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SystemHealth {
Unknown,
Running,
Degraded,
}

impl SystemHealth {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::Running => "running",
Self::Degraded => "degraded",
}
}
}

impl Display for SystemHealth {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}

/// A registered health check with a name and callback.
struct RegisteredCheck {
name: String,
Expand All @@ -53,7 +78,7 @@ impl Default for HealthRegistry {
}

impl std::fmt::Debug for HealthRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HealthRegistry").finish_non_exhaustive()
}
}
Expand Down Expand Up @@ -97,6 +122,24 @@ impl HealthRegistry {
.map(|c| (c.name.clone(), (c.check)()))
.collect()
}

/// Compute overall health by reading registered checks directly
pub(crate) fn compute_status(&self) -> SystemHealth {
let checks = self
.checks
.read()
.expect("health registry read lock poisoned");
if checks.is_empty() {
SystemHealth::Unknown
} else if checks
.iter()
.all(|c| matches!((c.check)(), HealthStatus::Success))
{
SystemHealth::Running
} else {
SystemHealth::Degraded
}
}
}

#[cfg(test)]
Expand Down
17 changes: 9 additions & 8 deletions jans-cedarling/cedarling/src/lock/health_ticker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ use tokio::time::{MissedTickBehavior, interval};
use tokio_util::sync::CancellationToken;
use url::Url;

use super::health_registry::{HealthRegistry, HealthStatus};
use super::health_registry::HealthRegistry;
use super::transport::mapping::LockServerHealthEntry;
use super::transport::{AuditItem, AuditKind, AuditPayload, AuditTransport};
use crate::app_types::{ApplicationName, PdpID};
use crate::http::{JoinHandle, spawn_task};
use crate::lock::LockLogEntry;
use crate::lock::health_registry::{HealthStatus, SystemHealth};
use crate::log::{LogWriter, LoggerWeak};

pub(super) struct HealthTickerParams {
Expand Down Expand Up @@ -81,6 +82,7 @@ impl<T: AuditTransport + 'static> HealthTicker<T> {
payload: AuditPayload::Health(Box::new(entry)),
pdp_id: self.pdp_id,
app_name: self.app_name.clone(),
status: None,
};

let result = self
Expand All @@ -100,13 +102,12 @@ impl<T: AuditTransport + 'static> HealthTicker<T> {
let engine_status = self.registry.collect();

let overall_status = if engine_status.is_empty() {
"unknown"
SystemHealth::Unknown
} else if engine_status.values().all(|s| *s == HealthStatus::Success) {
"running"
SystemHealth::Running
} else {
"degraded"
}
.to_string();
SystemHealth::Degraded
};

LockServerHealthEntry {
creation_date: now.clone(),
Expand All @@ -116,7 +117,7 @@ impl<T: AuditTransport + 'static> HealthTicker<T> {
.as_ref()
.map_or_else(String::new, |n| n.0.to_string()),
node_name: self.pdp_id.to_string(),
status: overall_status,
status: overall_status.to_string(),
engine_status,
}
}
Expand All @@ -125,7 +126,7 @@ impl<T: AuditTransport + 'static> HealthTicker<T> {
#[cfg(test)]
mod test {
use super::*;
use crate::lock::transport::TransportResult;
use crate::lock::{health_registry::HealthStatus, transport::TransportResult};
use std::sync::Arc;
use url::Url;

Expand Down
11 changes: 9 additions & 2 deletions jans-cedarling/cedarling/src/lock/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,10 +410,17 @@ impl LockService {

impl LockService {
/// Queue a typed audit item for delivery to the Lock Server
pub(crate) fn dispatch_audit(&self, item: AuditItem) {
pub(crate) fn dispatch_audit(&self, mut item: AuditItem) {
let (worker, worker_name) = match &item.payload {
AuditPayload::Decision(_) => (self.log_worker.as_ref(), "log"),
AuditPayload::Metric(_) => (self.telemetry_worker.as_ref(), "telemetry"),
AuditPayload::Metric(_) => {
let status = self
.health_registry
.as_ref()
.map(HealthRegistry::compute_status);
item.status = status;
(self.telemetry_worker.as_ref(), "telemetry")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The worker name can also be an enum

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be an overkill since it's only used for a single time logging

},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
AuditPayload::Health(_) => return,
};

Expand Down
37 changes: 33 additions & 4 deletions jans-cedarling/cedarling/src/lock/transport/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::lock::health_registry::HealthStatus;
use crate::lock::health_registry::{HealthStatus, SystemHealth};
use crate::lock::transport::{AuditItem, AuditPayload, TransportError};
use crate::log::DecisionLogEntry;

Expand Down Expand Up @@ -171,7 +171,10 @@ impl TryFrom<&AuditItem> for LockServerMetricsEntry {
.ok_or(MappingValidationError::MissingField)?,
service: item.app_name.as_ref().map(|n| n.0.to_string()),
node_name: item.pdp_id.to_string(),
status: "running".to_string(),
status: item
.status
.map_or("unknown", SystemHealth::as_str)
.to_string(),
interval_secs: entry.interval_secs,
policy_stats: entry.policy_stats.clone(),
error_counters: entry.error_counters.clone(),
Expand Down Expand Up @@ -237,6 +240,7 @@ mod test {

use super::*;
use crate::common::app_types::{ApplicationName, PdpID};
use crate::lock::health_registry::SystemHealth;
use crate::lock::transport::test_utils::{decision_audit_item, metric_audit_item};
use crate::log::{
BaseLogEntry, Decision, DecisionLogEntry, DiagnosticsSummary, LogTokensInfo,
Expand Down Expand Up @@ -394,7 +398,7 @@ mod test {

assert_eq!(lock_entry.service.as_deref(), Some("jans-auth"));
assert_eq!(lock_entry.node_name, pdp_id.to_string());
assert_eq!(lock_entry.status, "running");
assert_eq!(lock_entry.status, SystemHealth::Unknown.as_str());
Comment thread
dagregi marked this conversation as resolved.
assert_eq!(lock_entry.interval_secs, 60);
assert_eq!(lock_entry.policy_stats.get("allow_read_docs"), Some(&340));
assert_eq!(
Expand Down Expand Up @@ -424,12 +428,37 @@ mod test {
LockServerMetricsEntry::try_from(&item).expect("map to LockServerMetricsEntry");

assert_eq!(lock_entry.service, None);
assert_eq!(lock_entry.status, "running");
assert_eq!(lock_entry.status, SystemHealth::Unknown.as_str());
assert_eq!(lock_entry.interval_secs, 30);
assert!(lock_entry.policy_stats.is_empty());
assert!(lock_entry.error_counters.is_empty());
}

#[test]
fn metrics_log_entry_passes_through_degraded_status() {
let base = BaseLogEntry::new_metric(crate::log::gen_uuid7());

let metrics_entry = MetricsLogEntry {
base,
policy_stats: HashMap::new(),
error_counters: HashMap::new(),
operational_stats: HashMap::new(),
interval_secs: 60,
};

let mut item = metric_audit_item(
metrics_entry,
PdpID::new(),
Some(ApplicationName::from("svc".to_string())),
);
item.status = Some(SystemHealth::Degraded);

let lock_entry =
LockServerMetricsEntry::try_from(&item).expect("map to LockServerMetricsEntry");

assert_eq!(lock_entry.status, SystemHealth::Degraded.as_str());
}

#[test]
fn map_entries_skips_bad_entries_and_keeps_good_ones() {
let mut bad = test_decision_entry();
Expand Down
2 changes: 2 additions & 0 deletions jans-cedarling/cedarling/src/lock/transport/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use async_trait::async_trait;
use url::Url;

use crate::app_types::{ApplicationName, PdpID};
use crate::lock::health_registry::SystemHealth;
use crate::log::{DecisionLogEntry, MetricsLogEntry};
use mapping::LockServerHealthEntry;

Expand Down Expand Up @@ -42,6 +43,7 @@ pub(crate) struct AuditItem {
pub payload: AuditPayload,
pub pdp_id: PdpID,
pub app_name: Option<ApplicationName>,
pub status: Option<SystemHealth>,
}

/// Result type for transport operations.
Expand Down
3 changes: 3 additions & 0 deletions jans-cedarling/cedarling/src/lock/transport/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub(crate) fn decision_audit_item(
payload: AuditPayload::Decision(Box::new(entry)),
pdp_id,
app_name,
status: None,
}
}

Expand All @@ -40,6 +41,7 @@ pub(crate) fn metric_audit_item(
payload: AuditPayload::Metric(Box::new(entry)),
pdp_id,
app_name,
status: None,
}
}

Expand Down Expand Up @@ -133,5 +135,6 @@ pub(crate) fn sample_health_item() -> AuditItem {
})),
pdp_id: PdpID::new(),
app_name: None,
status: None,
}
}
2 changes: 1 addition & 1 deletion jans-cedarling/cedarling/src/log/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ pub(crate) trait Loggable:
/// Convert into an [`AuditPayload`] for Lock Server dispatch.
/// Override for types that should be forwarded to the Lock Server
/// The default returns `None` (no dispatch)
fn into_audit_payload(self) -> Option<AuditPayload> {
fn to_audit_payload(&self) -> Option<AuditPayload> {
None
}
}
Expand Down
8 changes: 4 additions & 4 deletions jans-cedarling/cedarling/src/log/log_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,8 @@ impl Loggable for DecisionLogEntry {
self.base.get_log_level()
}

fn into_audit_payload(self) -> Option<AuditPayload> {
Some(AuditPayload::Decision(Box::new(self)))
fn to_audit_payload(&self) -> Option<AuditPayload> {
Some(AuditPayload::Decision(Box::new(self.clone())))
}
}

Expand All @@ -426,8 +426,8 @@ impl Loggable for MetricsLogEntry {
self.base.get_log_level()
}

fn into_audit_payload(self) -> Option<AuditPayload> {
Some(AuditPayload::Metric(Box::new(self)))
fn to_audit_payload(&self) -> Option<AuditPayload> {
Some(AuditPayload::Metric(Box::new(self.clone())))
}
}

Expand Down
7 changes: 4 additions & 3 deletions jans-cedarling/cedarling/src/log/log_strategy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,13 @@ impl LogStrategy {
.read()
.expect("obtain lock_service read lock")
.as_ref()
&& let Some(payload) = entry.clone().into_audit_payload()
&& let Some(payload) = entry.to_audit_payload()
{
let item = AuditItem {
payload,
pdp_id: self.pdp_id,
app_name: self.app_name.clone(),
status: None,
};
lock_service.dispatch_audit(item);
}
Expand Down Expand Up @@ -211,8 +212,8 @@ impl<Entry: Loggable + Indexed> Loggable for LogEntryWithClientInfo<Entry> {
self.entry.get_log_level()
}

fn into_audit_payload(self) -> Option<crate::lock::AuditPayload> {
self.entry.into_audit_payload()
fn to_audit_payload(&self) -> Option<crate::lock::AuditPayload> {
self.entry.to_audit_payload()
}
}

Expand Down