pub mod v2;
use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::freshness::{self, Horizon, Observation};
use crate::grammar::{self, Addr, IfaceId, Key, KeyError, KindToken, ZkKey};
use crate::slug::{chunk_slug, chunk_unslug};
pub const PROFILE: &str = "alarms.v1";
pub const IFACE: &str = "alarms.v1";
pub const NAME: &str = "alarms";
pub const VOCABULARY: &[&str] = &[];
pub const ALARMS: &str = "alarms/{alert_key}";
const ALARMS_CHUNK: &str = "alarms";
pub const TTL: Duration = Duration::from_secs(900);
pub const REFRESH: Duration = Duration::from_secs(450);
pub const MAX_ALARMS: u64 = 256;
pub const HOST: &str = "host";
pub const HOST_SCOPED_PREFIX: &str = "host.";
pub const UNNAMED: &str = "unnamed";
pub const MAX_TIME_MS: u64 = (1 << 53) - 1;
#[must_use]
pub fn horizon() -> Horizon {
Horizon::Within(TTL)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Major {
V1,
V2,
}
impl Major {
#[must_use]
pub const fn iface(self) -> &'static str {
match self {
Major::V1 => IFACE,
Major::V2 => v2::IFACE,
}
}
#[must_use]
pub fn named(iface: &str) -> Option<Major> {
[Major::V2, Major::V1]
.into_iter()
.find(|m| m.iface() == iface)
}
#[must_use]
pub fn of<'a>(interfaces: impl IntoIterator<Item = &'a str>) -> Option<Major> {
let mut found = None;
for iface in interfaces {
match Major::named(iface) {
Some(Major::V2) => return Some(Major::V2),
Some(Major::V1) => found = Some(Major::V1),
None => {}
}
}
found
}
}
#[must_use]
pub fn is_host_scoped(name: &str) -> bool {
name == HOST || name.starts_with(HOST_SCOPED_PREFIX)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unframed {
Rule,
LabelName(String),
LabelValue { name: String },
}
impl Unframed {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Rule => "rule",
Self::LabelName(_) => "label_name",
Self::LabelValue { .. } => "label_value",
}
}
}
impl fmt::Display for Unframed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rule => f.write_str("the rule is empty or holds a newline"),
Self::LabelName(n) => write!(f, "label name {n:?} is empty or holds a newline or '='"),
Self::LabelValue { name } => write!(f, "label {name:?}'s value holds a newline"),
}
}
}
fn fnv1a_64(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
fn frame(rule: &str, labels: &mut [(&str, &str)]) -> String {
labels.sort_unstable();
let mut input = String::from(rule);
for (name, value) in labels.iter() {
input.push('\n');
input.push_str(name);
input.push('=');
input.push_str(value);
}
input
}
fn render(input: &str) -> String {
key_hex(fnv1a_64(input.as_bytes()))
}
#[must_use]
pub fn key_hex(key: u64) -> String {
format!("{key:016x}")
}
#[must_use]
pub fn key_integer(key: &str) -> Option<u64> {
crate::chunk::is_lower_hex(key, 16)
.then(|| u64::from_str_radix(key, 16).ok())
.flatten()
}
pub fn alert_key<'a>(
rule: &str,
labels: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<String, Unframed> {
if rule.is_empty() || rule.contains('\n') {
return Err(Unframed::Rule);
}
let mut kept = Vec::new();
for (name, value) in labels {
if is_host_scoped(name) {
continue;
}
if name.is_empty() || name.contains(['\n', '=']) {
return Err(Unframed::LabelName(name.to_owned()));
}
if value.contains('\n') {
return Err(Unframed::LabelValue {
name: name.to_owned(),
});
}
kept.push((name, value));
}
Ok(render(&frame(rule, &mut kept)))
}
#[must_use]
pub fn sanitize<'a>(
rule: &str,
labels: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> (String, Vec<(String, String)>) {
let rule = rule.replace('\n', "_");
let rule = if rule.is_empty() {
UNNAMED.to_owned()
} else {
rule
};
let labels = labels
.into_iter()
.filter(|(n, _)| !is_host_scoped(n))
.map(|(n, v)| {
let n = n.replace(['\n', '='], "_");
(
if n.is_empty() { "_".to_owned() } else { n },
v.replace('\n', "_"),
)
})
.collect();
(rule, labels)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Derived {
pub key: String,
pub input: String,
pub framed: bool,
}
impl Derived {
#[must_use]
pub fn integer(&self) -> u64 {
fnv1a_64(self.input.as_bytes())
}
}
#[must_use]
pub fn derive<'a>(rule: &str, labels: impl IntoIterator<Item = (&'a str, &'a str)>) -> Derived {
let labels: Vec<(&str, &str)> = labels.into_iter().collect();
let framed = alert_key(rule, labels.iter().copied()).is_ok();
let (rule, sanitized) = sanitize(rule, labels);
let mut pairs: Vec<(&str, &str)> = sanitized
.iter()
.map(|(n, v)| (n.as_str(), v.as_str()))
.collect();
let input = frame(&rule, &mut pairs);
Derived {
key: render(&input),
input,
framed,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Info,
Warning,
Critical,
}
impl Severity {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Info => "info",
Self::Warning => "warning",
Self::Critical => "critical",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
match s {
"info" => Some(Self::Info),
"warning" => Some(Self::Warning),
"critical" => Some(Self::Critical),
_ => None,
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
Firing,
Resolved,
}
impl State {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Firing => "firing",
Self::Resolved => "resolved",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Alarm {
pub timestamp: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_at_ms: Option<u64>,
pub rule: String,
pub severity: Severity,
pub state: State,
pub summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub labels: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Invalid {
Json(String),
Schema(String),
TimeRange(&'static str),
}
impl Invalid {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Json(_) => "json",
Self::Schema(_) => "schema",
Self::TimeRange(_) => "time_range",
}
}
}
impl fmt::Display for Invalid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Json(why) => write!(f, "not strict JSON: {why}"),
Self::Schema(why) => write!(f, "outside alarms.v1.Alarm: {why}"),
Self::TimeRange(m) => write!(f, "{m} is outside 0 to 2^53-1 ms"),
}
}
}
fn time(v: &Value) -> Result<Option<u64>, ()> {
let Value::Number(n) = v else { return Err(()) };
if let Some(u) = n.as_u64() {
return Ok((u <= MAX_TIME_MS).then_some(u));
}
if n.is_i64() {
return Ok(None);
}
let f = n.as_f64().ok_or(())?;
if !f.is_finite() || f.fract() != 0.0 {
return Err(());
}
#[allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
Ok((f >= 0.0 && f <= MAX_TIME_MS as f64).then_some(f as u64))
}
impl Alarm {
pub fn from_json(v: &Value) -> Result<Self, Invalid> {
let schema = |why: String| Invalid::Schema(why);
let Value::Object(o) = v else {
return Err(schema("not an object".into()));
};
for m in ["timestamp", "rule", "severity", "state", "summary"] {
if !o.contains_key(m) {
return Err(schema(format!("/{m}: missing")));
}
}
let string = |m: &str| -> Result<Option<String>, Invalid> {
match o.get(m) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(Invalid::Schema(format!("/{m}: not a string"))),
}
};
let integer = |m: &'static str| -> Result<Option<Option<u64>>, Invalid> {
match o.get(m) {
None => Ok(None),
Some(t) => time(t)
.map(Some)
.map_err(|()| Invalid::Schema(format!("/{m}: not an integer"))),
}
};
let missing = |m: &str| Invalid::Schema(format!("/{m}: missing"));
let timestamp = integer("timestamp")?.ok_or_else(|| missing("timestamp"))?;
let observed_at_ms = integer("observed_at_ms")?;
let rule = string("rule")?.ok_or_else(|| missing("rule"))?;
let summary = string("summary")?.ok_or_else(|| missing("summary"))?;
let category = string("category")?;
let severity = match o.get("severity") {
Some(Value::String(s)) => Severity::parse(s),
_ => None,
}
.ok_or_else(|| schema("/severity: not info, warning or critical".into()))?;
let state = match o.get("state").and_then(Value::as_str) {
Some("firing") => State::Firing,
Some("resolved") => State::Resolved,
_ => return Err(schema("/state: not firing or resolved".into())),
};
let mut labels = BTreeMap::new();
match o.get("labels") {
None => {}
Some(Value::Object(l)) => {
for (n, v) in l {
let Value::String(v) = v else {
return Err(schema(format!("/labels/{n}: not a string")));
};
labels.insert(n.clone(), v.clone());
}
}
Some(_) => return Err(schema("/labels: not an object".into())),
}
let timestamp = timestamp.ok_or(Invalid::TimeRange("timestamp"))?;
let observed_at_ms = match observed_at_ms {
None => None,
Some(t) => Some(t.ok_or(Invalid::TimeRange("observed_at_ms"))?),
};
Ok(Self {
timestamp,
observed_at_ms,
rule,
severity,
state,
summary,
category,
labels,
})
}
pub fn label_pairs(&self) -> impl Iterator<Item = (&str, &str)> {
self.labels.iter().map(|(n, v)| (n.as_str(), v.as_str()))
}
#[must_use]
pub fn derive(&self) -> Derived {
derive(&self.rule, self.label_pairs())
}
#[must_use]
pub fn alert_key(&self) -> String {
self.derive().key
}
#[must_use]
pub fn check(&self) -> Vec<Problem> {
let mut out = Vec::new();
if let Some(o) = self.observed_at_ms {
if o < self.timestamp {
out.push(Problem::ObservedBeforeTimestamp);
}
if self.state == State::Resolved {
out.push(Problem::ObservedOnResolved);
}
}
if let Err(u) = alert_key(&self.rule, self.label_pairs()) {
out.push(Problem::Unframed(u));
}
for n in self.labels.keys() {
if !is_label_name(n) {
out.push(Problem::LabelName(n.clone()));
}
}
out
}
}
pub fn decode(bytes: &[u8]) -> Result<Alarm, Invalid> {
let text = std::str::from_utf8(bytes).map_err(|e| Invalid::Json(format!("not UTF-8: {e}")))?;
let v = crate::strict::parse_json(text).map_err(|e| Invalid::Json(e.to_string()))?;
Alarm::from_json(&v)
}
#[must_use]
pub fn is_label_name(name: &str) -> bool {
name.split('.').all(|seg| {
let mut cs = seg.bytes();
cs.next().is_some_and(|c| c.is_ascii_lowercase())
&& cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Gravity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Problem {
ObservedBeforeTimestamp,
ObservedOnResolved,
Unframed(Unframed),
LabelName(String),
}
impl Problem {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::ObservedBeforeTimestamp => "observed_before_timestamp",
Self::ObservedOnResolved => "observed_on_resolved",
Self::Unframed(_) => "unframed",
Self::LabelName(_) => "label_name_form",
}
}
#[must_use]
pub fn gravity(&self) -> Gravity {
match self {
Self::ObservedBeforeTimestamp | Self::ObservedOnResolved => Gravity::Error,
Self::Unframed(_) | Self::LabelName(_) => Gravity::Warning,
}
}
}
impl fmt::Display for Problem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ObservedBeforeTimestamp => f.write_str("observed_at_ms is before timestamp"),
Self::ObservedOnResolved => f.write_str("a resolved document carries observed_at_ms"),
Self::Unframed(u) => {
write!(f, "{u}, so the key is derived through the sanitizing step")
}
Self::LabelName(n) => write!(f, "label name {n:?} is not lowercase dotted snake_case"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum Sample<'a> {
Put(&'a Alarm),
Unreadable,
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Transition {
Raised,
Escalated,
Refreshed,
Confirmed,
Resolved,
Retired,
Unreadable,
}
impl Transition {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Raised => "raised",
Self::Escalated => "escalated",
Self::Refreshed => "refreshed",
Self::Confirmed => "confirmed",
Self::Resolved => "resolved",
Self::Retired => "retired",
Self::Unreadable => "unreadable",
}
}
}
impl fmt::Display for Transition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PutFacts<S, T> {
pub state: State,
pub severity: S,
pub at: T,
}
pub(crate) fn put_reads<S: PartialEq, T: PartialEq>(
held: Option<PutFacts<S, T>>,
put: PutFacts<S, T>,
equal: bool,
) -> Transition {
use Transition as T;
let Some(h) = held else {
return match put.state {
State::Firing => T::Raised,
State::Resolved => T::Resolved,
};
};
match (h.state, put.state) {
(State::Firing, State::Firing) if put.severity != h.severity => T::Escalated,
(State::Resolved, State::Firing) => T::Raised,
(State::Firing, State::Resolved) => T::Resolved,
(State::Firing, State::Firing) if put.at != h.at => T::Raised,
(State::Resolved, State::Resolved) if put.at != h.at => T::Resolved,
_ if equal => T::Confirmed,
_ => T::Refreshed,
}
}
pub(crate) fn delete_reads(held: Option<State>) -> Transition {
match held {
Some(State::Firing) => Transition::Resolved,
Some(State::Resolved) | None => Transition::Retired,
}
}
#[must_use]
pub fn transition(held: Option<&Alarm>, sample: Sample<'_>) -> Transition {
let facts = |a: &Alarm| PutFacts {
state: a.state,
severity: a.severity,
at: a.timestamp,
};
match sample {
Sample::Unreadable => Transition::Unreadable,
Sample::Delete => delete_reads(held.map(|h| h.state)),
Sample::Put(n) => put_reads(held.map(facts), facts(n), held == Some(n)),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Track {
pub held: Option<Alarm>,
}
impl Track {
pub fn apply(&mut self, sample: Sample<'_>) -> Transition {
let t = transition(self.held.as_ref(), sample);
self.held = match sample {
Sample::Put(a) => Some(a.clone()),
Sample::Unreadable | Sample::Delete => None,
};
t
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AlarmRef {
pub system: String,
pub service: String,
pub alert_key: String,
}
impl AlarmRef {
pub fn key(&self) -> Result<Key, KeyError> {
let addr = Addr::new(&self.system, &self.service)?;
let iface = IfaceId::new(NAME, 1)?;
grammar::data_key(
&addr,
&iface,
KindToken::State,
&[ALARMS_CHUNK, &chunk_slug(&self.alert_key)],
)
}
#[must_use]
pub fn from_key(key: &str) -> Option<Self> {
let ZkKey::Data {
addr,
iface,
kind: KindToken::State,
resource,
} = grammar::parse(key).ok()?
else {
return None;
};
if iface.to_string() != IFACE {
return None;
}
let [lit, chunk] = resource.as_slice() else {
return None;
};
if lit != ALARMS_CHUNK {
return None;
}
Some(Self {
system: addr.system.as_str().to_owned(),
service: addr.service.as_str().to_owned(),
alert_key: chunk_unslug(chunk)?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Listing {
Listed { token: bool },
NotListed,
Unread,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
Present(Listing),
Absent,
Incomplete,
AcrossFace { reachable: bool },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Latest {
Firing,
Resolved,
Deleted,
Undecodable,
}
#[derive(Debug, Clone, Copy)]
pub struct Reading<'a> {
pub presence: Presence,
pub observations: &'a [Observation],
pub latest: Option<Latest>,
pub previous_instance: bool,
pub held_whole: bool,
pub left_out: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
Yes,
No,
Unobservable,
NotAsked,
}
impl Answer {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::No => "no",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
impl fmt::Display for Answer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
Firing,
Resolved,
Deleted,
Stale,
Fresh,
NotFiring,
Absent,
NotListed,
PresenceIncomplete,
NoDescriptor,
FaceClosed,
NothingCrossed,
AcrossFace,
LastKnown,
PreviousInstance,
Incomplete,
NotRead,
NotHeld,
Undecodable,
Answered,
Window,
NoSeed,
SeedIncomplete,
NoMember,
WindowLost,
WindowShort,
OwnerGap,
WindowUnconfirmed,
AnyFiring,
NoneFiring,
OwnerUnobservable,
ScopeIncomplete,
AlarmUnobservable,
NoOwner,
Strict,
Sanitized,
Mismatch,
NoDocument,
Rebound,
Snapshot,
SnapshotIncomplete,
SnapshotRun,
Table,
NoWords,
NoRecord,
Unreadable,
Freshness(freshness::Reason),
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Firing => "firing",
Self::Resolved => "resolved",
Self::Deleted => "deleted",
Self::Stale => "stale",
Self::Fresh => "fresh",
Self::NotFiring => "not_firing",
Self::Absent => "absent",
Self::NotListed => "not_listed",
Self::PresenceIncomplete => "presence_incomplete",
Self::NoDescriptor => "no_descriptor",
Self::FaceClosed => "face_closed",
Self::NothingCrossed => "nothing_crossed",
Self::AcrossFace => "across_face",
Self::LastKnown => "last_known",
Self::PreviousInstance => "previous_instance",
Self::Incomplete => "incomplete",
Self::NotRead => "not_read",
Self::NotHeld => "not_held",
Self::Undecodable => "undecodable",
Self::Answered => "answered",
Self::Window => "window",
Self::NoSeed => "no_seed",
Self::SeedIncomplete => "seed_incomplete",
Self::NoMember => "no_member",
Self::WindowLost => "window_lost",
Self::WindowShort => "window_short",
Self::OwnerGap => "owner_gap",
Self::WindowUnconfirmed => "window_unconfirmed",
Self::AnyFiring => "any_firing",
Self::NoneFiring => "none_firing",
Self::OwnerUnobservable => "owner_unobservable",
Self::ScopeIncomplete => "scope_incomplete",
Self::AlarmUnobservable => "alarm_unobservable",
Self::NoOwner => "no_owner",
Self::Strict => "strict",
Self::Sanitized => "sanitized",
Self::Mismatch => "mismatch",
Self::NoDocument => "no_document",
Self::Rebound => "rebound",
Self::Snapshot => "snapshot",
Self::SnapshotIncomplete => "snapshot_incomplete",
Self::SnapshotRun => "snapshot_run",
Self::Table => "table",
Self::NoWords => "no_words",
Self::NoRecord => "no_record",
Self::Unreadable => "unreadable",
Self::Freshness(r) => r.as_str(),
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::Firing => "its owner says it fires, and confirmed it within 900 s",
Self::Resolved => "its owner put it resolved",
Self::Deleted => "its owner deleted it, which reads as resolved",
Self::Stale => "its owner has not confirmed it within 900 s",
Self::Fresh => "its owner confirmed it within 900 s",
Self::NotFiring => "it is not firing",
Self::Absent => "its owner is absent: presence's word, and its alarms are last-known",
Self::NotListed => "its owner's descriptor does not list alarms.v1",
Self::PresenceIncomplete => {
"its owner's token was not seen, and the presence read may be incomplete or refused"
}
Self::NoDescriptor => "its owner's descriptor could not be read",
Self::FaceClosed => "the constrained face does not let this reader reach its alarms",
Self::NothingCrossed => "nothing of it has crossed the constrained face",
Self::AcrossFace => {
"its owner is across a constrained face, where presence does not cross"
}
Self::LastKnown => "only an archive's last-known word was read, never current",
Self::PreviousInstance => {
"the latest put is an earlier instance's, which the present one has not made its own"
}
Self::Incomplete => "deliveries were lost, and no GET answered since",
Self::NotRead => "nothing of it was read",
Self::NotHeld => "its owner's alarms, known whole, do not hold it",
Self::Undecodable => "its latest put does not read as an alarms.v1 document",
Self::Answered => "its owner answered a complete GET",
Self::Window => {
"a complete GET drew nothing, and a lossless window longer than 900 s heard no alarm"
}
Self::NoSeed => "no GET of its alarms was made",
Self::SeedIncomplete => "the GET of its alarms ended at its timeout, or with an error",
Self::NoMember => "the GET drew nothing, which is no verdict (core O5)",
Self::WindowLost => "the window lost a delivery",
Self::WindowShort => "the window was no longer than 900 s",
Self::OwnerGap => "its owner was not present throughout the window",
Self::WindowUnconfirmed => {
"no heartbeat of its owner in the window said the reader holds its alarms"
}
Self::AnyFiring => "an alarm at or above the severity fires",
Self::NoneFiring => "no alarm at or above the severity fires",
Self::OwnerUnobservable => "an owner's alarms are not known whole",
Self::ScopeIncomplete => {
"the reads that found the owners in scope were not whole, so an owner they \
missed may fire"
}
Self::AlarmUnobservable => {
"an alarm that may be at or above the severity is unobservable"
}
Self::NoOwner => "no owner in scope was asked",
Self::Strict => "the key is the document's, by the strict recipe",
Self::Sanitized => "the key is the document's, through the sanitizing step",
Self::Mismatch => "the key is not the one its document derives",
Self::NoDocument => "a delete carries no document",
Self::Rebound => "another alarm's record is on its slot under its run, so it resolved",
Self::Snapshot => "its owner answered one complete snapshot of its alarms",
Self::SnapshotIncomplete => {
"the read drew no page of its alarms' snapshot, or a page is missing"
}
Self::SnapshotRun => {
"the snapshot's run is one no present descriptor states, an earlier instance's"
}
Self::Table => "the slot's record names a table's rule, which its table names",
Self::NoWords => "no words were read on the slot",
Self::NoRecord => "no record is held on the slot",
Self::Unreadable => "the slot's words do not read as alarms.v2.Words",
Self::Freshness(r) => r.says(),
}
}
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
pub answer: Answer,
pub reason: Reason,
}
impl Judged {
const fn new(answer: Answer, reason: Reason) -> Self {
Self { answer, reason }
}
}
fn premises(p: Presence) -> Option<Judged> {
use Answer::{NotAsked, Unobservable};
match p {
Presence::Absent => Some(Judged::new(NotAsked, Reason::Absent)),
Presence::Incomplete => Some(Judged::new(Unobservable, Reason::PresenceIncomplete)),
Presence::AcrossFace { reachable: false } => {
Some(Judged::new(Unobservable, Reason::FaceClosed))
}
Presence::Present(Listing::NotListed) => Some(Judged::new(NotAsked, Reason::NotListed)),
Presence::Present(Listing::Unread) => Some(Judged::new(Unobservable, Reason::NoDescriptor)),
Presence::AcrossFace { reachable: true } | Presence::Present(Listing::Listed { .. }) => {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Step5 {
Firing,
Undecodable,
Not(Reason),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Asked {
pub presence: Presence,
pub freshness: freshness::Judged,
pub lost: bool,
pub latest: Option<Step5>,
pub previous_instance: bool,
pub held_whole: bool,
pub left_out: bool,
}
impl Asked {
fn left_out(&self) -> bool {
self.held_whole && self.left_out
}
fn of(r: &Reading<'_>) -> Asked {
let lossy = r.observations.iter().any(|o| {
matches!(
o,
Observation::Subscribed {
complete: false,
..
}
)
});
let answered = r
.observations
.iter()
.any(|o| matches!(o, Observation::Got { reply: Some(_), .. }));
Asked {
presence: r.presence,
freshness: freshness::judge_all(&horizon(), r.observations),
lost: lossy && !answered,
latest: r.latest.map(|l| match l {
Latest::Firing => Step5::Firing,
Latest::Undecodable => Step5::Undecodable,
Latest::Resolved => Step5::Not(Reason::Resolved),
Latest::Deleted => Step5::Not(Reason::Deleted),
}),
previous_instance: r.previous_instance,
held_whole: r.held_whole,
left_out: r.left_out,
}
}
}
enum Read {
Done(Judged),
Judge {
firing: bool,
freshness: freshness::Judged,
},
}
fn read(r: &Asked, not_firing: impl Fn(Reason) -> Judged) -> Read {
use Answer::{NotAsked, Unobservable};
let f = r.freshness;
if f.verdict == freshness::Verdict::NotAsked && f.reason == freshness::Reason::LastKnown {
return Read::Done(Judged::new(NotAsked, Reason::LastKnown));
}
if r.lost && !r.left_out() {
return Read::Done(Judged::new(Unobservable, Reason::Incomplete));
}
let latest = if r.left_out() { None } else { r.latest };
match latest {
None if r.held_whole => Read::Done(not_firing(Reason::NotHeld)),
None => Read::Done(Judged::new(
Unobservable,
if matches!(r.presence, Presence::AcrossFace { .. }) {
Reason::NothingCrossed
} else {
Reason::NotRead
},
)),
Some(Step5::Not(reason)) => Read::Done(not_firing(reason)),
Some(Step5::Firing | Step5::Undecodable) if r.previous_instance => {
Read::Done(Judged::new(NotAsked, Reason::PreviousInstance))
}
Some(l @ (Step5::Firing | Step5::Undecodable)) => Read::Judge {
firing: l == Step5::Firing,
freshness: f,
},
}
}
pub(crate) fn firing_asked(r: &Asked) -> Judged {
use Answer::{No, Unobservable, Yes};
if let Some(j) = premises(r.presence) {
return j;
}
let (firing, f) = match read(r, |reason| Judged::new(No, reason)) {
Read::Done(j) => return j,
Read::Judge { firing, freshness } => (firing, freshness),
};
match f.verdict {
freshness::Verdict::Fresh if firing => Judged::new(Yes, Reason::Firing),
freshness::Verdict::Fresh => Judged::new(Unobservable, Reason::Undecodable),
freshness::Verdict::Stale
if f.reason == freshness::Reason::NoDelivery
&& matches!(r.presence, Presence::AcrossFace { .. }) =>
{
Judged::new(Unobservable, Reason::NothingCrossed)
}
freshness::Verdict::Stale => Judged::new(Unobservable, Reason::Stale),
freshness::Verdict::Unobservable | freshness::Verdict::NotAsked => {
Judged::new(Unobservable, Reason::Freshness(f.reason))
}
}
}
pub(crate) fn stale_firing_asked(r: &Asked) -> Judged {
use Answer::{No, NotAsked, Unobservable, Yes};
if let Some(j) = premises(r.presence) {
return j;
}
if matches!(r.presence, Presence::AcrossFace { .. }) {
return Judged::new(Unobservable, Reason::AcrossFace);
}
let f = match read(r, |_| Judged::new(NotAsked, Reason::NotFiring)) {
Read::Done(j) => return j,
Read::Judge { firing: false, .. } => {
return Judged::new(Unobservable, Reason::Undecodable);
}
Read::Judge { freshness, .. } => freshness,
};
match f.verdict {
freshness::Verdict::Stale => Judged::new(Yes, Reason::Stale),
freshness::Verdict::Fresh => Judged::new(No, Reason::Fresh),
freshness::Verdict::Unobservable | freshness::Verdict::NotAsked => {
Judged::new(Unobservable, Reason::Freshness(f.reason))
}
}
}
#[must_use]
pub fn firing(r: &Reading<'_>) -> Judged {
firing_asked(&Asked::of(r))
}
#[must_use]
pub fn stale_firing(r: &Reading<'_>) -> Judged {
stale_firing_asked(&Asked::of(r))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Seed {
Complete { members: usize },
Incomplete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window {
pub listened: Duration,
pub lossless: bool,
pub present_throughout: bool,
pub in_step: Option<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SetVerdict {
Established,
Unobservable,
NotAsked,
}
impl SetVerdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Established => "established",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SetJudged {
pub verdict: SetVerdict,
pub reason: Reason,
}
#[must_use]
pub fn owner_set(presence: Presence, seed: Option<Seed>, window: Option<Window>) -> SetJudged {
let j = |verdict, reason| SetJudged { verdict, reason };
use SetVerdict::{Established, NotAsked, Unobservable};
if let Some(p) = premises(presence) {
return j(
match p.answer {
Answer::NotAsked => NotAsked,
_ => Unobservable,
},
p.reason,
);
}
let members = match seed {
None => return j(Unobservable, Reason::NoSeed),
Some(Seed::Incomplete) => return j(Unobservable, Reason::SeedIncomplete),
Some(Seed::Complete { members }) => members,
};
let across = matches!(presence, Presence::AcrossFace { .. });
if let Some(w) = window {
if !w.lossless {
return j(Unobservable, Reason::WindowLost);
}
if !w.present_throughout && !across {
return j(Unobservable, Reason::OwnerGap);
}
}
if members > 0 {
return j(Established, Reason::Answered);
}
if across {
return j(Unobservable, Reason::AcrossFace);
}
match window {
None => j(Unobservable, Reason::NoMember),
Some(w) if w.listened <= TTL => j(Unobservable, Reason::WindowShort),
Some(w) if w.in_step == Some(false) => j(Unobservable, Reason::WindowUnconfirmed),
Some(_) => j(Established, Reason::Window),
}
}
#[derive(Debug, Clone, Copy)]
pub struct OwnerAlarms<'a> {
pub set: SetJudged,
pub alarms: &'a [(Judged, Option<Severity>)],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AnyFiring {
pub answer: Answer,
pub reason: Reason,
pub firing: usize,
pub established: usize,
pub unobservable: usize,
pub not_asked: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScopeRead {
Whole,
NotWhole,
}
#[must_use]
pub fn any_firing(at_least: Severity, owners: &[OwnerAlarms<'_>], scope: ScopeRead) -> AnyFiring {
let mut out = AnyFiring {
answer: Answer::No,
reason: Reason::NoneFiring,
firing: 0,
established: 0,
unobservable: 0,
not_asked: 0,
};
let mut alarm_doubt = false;
for o in owners {
match o.set.verdict {
SetVerdict::Established => out.established += 1,
SetVerdict::Unobservable => out.unobservable += 1,
SetVerdict::NotAsked => out.not_asked += 1,
}
for (j, sev) in o.alarms {
let high = sev.is_none_or(|s| s >= at_least);
match j.answer {
Answer::Yes if high && sev.is_some() => out.firing += 1,
Answer::Yes | Answer::Unobservable
if high && o.set.verdict == SetVerdict::Established =>
{
alarm_doubt = true;
}
_ => {}
}
}
}
(out.answer, out.reason) = if out.firing > 0 {
(Answer::Yes, Reason::AnyFiring)
} else if out.unobservable > 0 {
(Answer::Unobservable, Reason::OwnerUnobservable)
} else if scope == ScopeRead::NotWhole {
(Answer::Unobservable, Reason::ScopeIncomplete)
} else if alarm_doubt {
(Answer::Unobservable, Reason::AlarmUnobservable)
} else if out.established == 0 {
(Answer::NotAsked, Reason::NoOwner)
} else {
(Answer::No, Reason::NoneFiring)
};
out
}
#[derive(Debug, Clone, Copy)]
pub enum Payload<'a> {
Alarm(&'a Alarm),
Unreadable,
Deleted,
}
#[must_use]
pub fn rederives(alert_key: &str, payload: Payload<'_>) -> Judged {
match payload {
Payload::Deleted => Judged::new(Answer::NotAsked, Reason::NoDocument),
Payload::Unreadable => Judged::new(Answer::Unobservable, Reason::Undecodable),
Payload::Alarm(a) => {
let d = a.derive();
if d.key != alert_key {
Judged::new(Answer::No, Reason::Mismatch)
} else if d.framed {
Judged::new(Answer::Yes, Reason::Strict)
} else {
Judged::new(Answer::Yes, Reason::Sanitized)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn the_test_vector() {
let labels = [("peer", "r2"), ("port", "eth0"), ("host", "h-3fa9c2d41b7e")];
assert_eq!(
alert_key("link_down", labels).as_deref(),
Ok("a659f813308ad1da")
);
let d = derive("link_down", labels);
assert_eq!(d.input, "link_down\npeer=r2\nport=eth0");
assert_eq!(d.input.len(), 27);
assert!(d.framed);
assert_eq!(d.key, "a659f813308ad1da");
}
#[test]
fn host_scoped_labels_drop_out_first() {
assert!(is_host_scoped("host"));
assert!(is_host_scoped("host.id"));
assert!(is_host_scoped("host."));
assert!(!is_host_scoped("hostname"));
assert!(!is_host_scoped("Host"));
let with = alert_key("r", [("port", "1"), ("host.id", "a\nb"), ("host.=", "")]);
assert_eq!(with, alert_key("r", [("port", "1")]));
}
#[test]
fn sanitizing_is_the_identity_on_framed_input() {
let labels = [("b", "2"), ("a", "1"), ("host", "h")];
let (rule, s) = sanitize("r", labels);
assert_eq!(rule, "r");
assert_eq!(s, vec![("b".into(), "2".into()), ("a".into(), "1".into())]);
assert_eq!(
derive("r", labels).key,
alert_key("r", labels).expect("framed")
);
}
#[test]
fn unframed_input_is_sanitized_not_refused() {
assert_eq!(
alert_key("link\ndown", [("port", "22")]),
Err(Unframed::Rule)
);
let d = derive("link\ndown", [("port", "22")]);
assert!(!d.framed);
assert_eq!(Ok(d.key), alert_key("link_down", [("port", "22")]));
assert_eq!(derive("", []).input, "unnamed");
assert_eq!(derive("\n", []).input, "_");
assert_eq!(derive("x", [("", "1")]).input, "x\n_=1");
assert_eq!(
derive("x", [("a=b", "2"), ("a_b", "1")]).input,
"x\na_b=1\na_b=2"
);
}
fn doc(v: Value) -> Alarm {
Alarm::from_json(&v).expect("a document")
}
fn firing_doc() -> Value {
json!({"timestamp": 1000, "rule": "link_down", "severity": "warning",
"state": "firing", "summary": "s", "labels": {"peer": "r2"}})
}
#[test]
fn documents_read_as_the_schema_says() {
let a = doc(firing_doc());
assert_eq!(a.severity, Severity::Warning);
assert!(a.check().is_empty());
let mut v = firing_doc();
v["timestamp"] = json!(1000.0);
assert_eq!(doc(v).timestamp, 1000);
let mut v = firing_doc();
v["later"] = json!({"x": 1});
assert_eq!(doc(v), a);
for (m, bad) in [
("severity", json!("major")),
("state", json!("acked")),
("timestamp", json!(1.5)),
("labels", json!({"a": 1})),
("observed_at_ms", Value::Null),
] {
let mut v = firing_doc();
v[m] = bad;
assert_eq!(
Alarm::from_json(&v).map_err(|e| e.as_str()),
Err("schema"),
"{m}"
);
}
let mut v = firing_doc();
v["timestamp"] = json!(-1);
assert_eq!(Alarm::from_json(&v), Err(Invalid::TimeRange("timestamp")));
assert_eq!(serde_json::to_value(&a).unwrap(), firing_doc());
}
#[test]
fn a_payload_is_strict_json_first() {
let ok = br#"{"timestamp": 1000, "rule": "r", "severity": "info", "state": "firing", "summary": "s"}"#;
assert_eq!(decode(ok).expect("reads").rule, "r");
for (bad, why) in [
(
&br#"{"timestamp": 1, "rule": "r", "severity": "info", "severity": "critical", "state": "firing", "summary": "s"}"#[..],
"a duplicate member",
),
(
br#"{"timestamp": 1, "rule": "r", "severity": "info", "state": "firing", "summary": "s", "labels": {"a": "1", "a": "2"}}"#,
"a duplicate label",
),
(
br#"{"timestamp": NaN, "rule": "r", "severity": "info", "state": "firing", "summary": "s"}"#,
"NaN",
),
(
br#"{"timestamp": 1, "rule": "\ud800", "severity": "info", "state": "firing", "summary": "s"}"#,
"a lone surrogate",
),
(b"\xff", "not UTF-8"),
(
br#"{"timestamp": 1, "rule": "r", "severity": "info", "state": "firing", "summary": "s"} x"#,
"trailing text",
),
] {
assert_eq!(decode(bad).map_err(|e| e.as_str()), Err("json"), "{why}");
}
let schema = br#"{"timestamp": 1, "rule": "r", "severity": "major", "state": "firing", "summary": "s"}"#;
assert_eq!(decode(schema).map_err(|e| e.as_str()), Err("schema"));
}
#[test]
fn a_documents_problems() {
let mut v = firing_doc();
v["observed_at_ms"] = json!(999);
v["state"] = json!("resolved");
v["labels"] = json!({"Peer": "r2", "a=b": "c"});
let p: Vec<&str> = doc(v).check().iter().map(Problem::as_str).collect();
assert_eq!(
p,
[
"observed_before_timestamp",
"observed_on_resolved",
"unframed",
"label_name_form",
"label_name_form"
]
);
assert!(is_label_name("host.boot_id"));
assert!(is_label_name("if_index"));
assert!(!is_label_name("host."));
assert!(!is_label_name("_x"));
assert!(!is_label_name(""));
}
#[test]
fn transitions_take_the_state_from_the_document() {
let raise = doc(firing_doc());
let mut escalate = raise.clone();
escalate.severity = Severity::Critical;
escalate.timestamp = 2000;
let mut refresh = escalate.clone();
refresh.summary = "t".into();
refresh.observed_at_ms = Some(3000);
let mut resolve = refresh.clone();
resolve.state = State::Resolved;
resolve.timestamp = 4000;
resolve.observed_at_ms = None;
let mut t = Track::default();
let seen: Vec<Transition> = [
Sample::Put(&raise),
Sample::Put(&escalate),
Sample::Put(&refresh),
Sample::Put(&refresh),
Sample::Put(&resolve),
Sample::Delete,
Sample::Put(&raise),
Sample::Delete,
]
.into_iter()
.map(|s| t.apply(s))
.collect();
use Transition as T;
assert_eq!(
seen,
[
T::Raised,
T::Escalated,
T::Refreshed,
T::Confirmed,
T::Resolved,
T::Retired,
T::Raised,
T::Resolved
]
);
}
#[test]
fn a_ref_is_the_alarms_key() {
let r = AlarmRef {
system: "h-3fa9c2d41b7e".into(),
service: "snmp.router01".into(),
alert_key: "a659f813308ad1da".into(),
};
let k = r.key().expect("a key");
assert_eq!(
k.as_str(),
"zk2/h-3fa9c2d41b7e/snmp.router01/alarms.v1/state/alarms/a659f813308ad1da"
);
assert_eq!(AlarmRef::from_key(k.as_str()), Some(r));
assert_eq!(AlarmRef::from_key("zk2/a/b/health.v1/state/status"), None);
}
fn sub(age: u64) -> Observation {
Observation::Subscribed {
last: Some(freshness::Last::Put(Duration::from_secs(age))),
listened: Duration::from_secs(2000),
complete: true,
}
}
#[test]
fn firing_and_stale() {
let present = Presence::Present(Listing::Listed { token: true });
let fresh = [sub(10)];
let stale = [sub(1000)];
let r = |obs, latest| Reading {
presence: present,
observations: obs,
latest: Some(latest),
previous_instance: false,
held_whole: false,
left_out: false,
};
assert_eq!(firing(&r(&fresh, Latest::Firing)).answer, Answer::Yes);
assert_eq!(firing(&r(&stale, Latest::Firing)).reason, Reason::Stale);
assert_eq!(stale_firing(&r(&stale, Latest::Firing)).answer, Answer::Yes);
assert_eq!(firing(&r(&stale, Latest::Resolved)).answer, Answer::No);
assert_eq!(
firing(&Reading {
presence: Presence::Absent,
..r(&fresh, Latest::Firing)
})
.reason,
Reason::Absent
);
}
#[test]
fn a_scope_answers_no_only_when_known_whole() {
let est = owner_set(
Presence::Present(Listing::Listed { token: false }),
Some(Seed::Complete { members: 0 }),
Some(Window {
listened: Duration::from_secs(901),
lossless: true,
present_throughout: true,
in_step: None,
}),
);
assert_eq!(est.verdict, SetVerdict::Established);
let warn = [(
Judged::new(Answer::Yes, Reason::Firing),
Some(Severity::Warning),
)];
let one = [OwnerAlarms {
set: est,
alarms: &warn,
}];
let a = any_firing(Severity::Critical, &one, ScopeRead::Whole);
assert_eq!((a.answer, a.firing), (Answer::No, 0));
let a = any_firing(Severity::Warning, &one, ScopeRead::Whole);
assert_eq!((a.answer, a.firing), (Answer::Yes, 1));
assert_eq!(
any_firing(Severity::Info, &[], ScopeRead::Whole).answer,
Answer::NotAsked
);
let a = any_firing(Severity::Critical, &one, ScopeRead::NotWhole);
assert_eq!(
(a.answer, a.reason),
(Answer::Unobservable, Reason::ScopeIncomplete)
);
assert_eq!(
any_firing(Severity::Info, &[], ScopeRead::NotWhole).reason,
Reason::ScopeIncomplete
);
assert_eq!(
any_firing(Severity::Warning, &one, ScopeRead::NotWhole).answer,
Answer::Yes,
"a yes whatever else is unknown"
);
}
#[test]
fn a_key_the_establishing_get_left_out_is_not_held() {
let lossy = [
Observation::Subscribed {
last: Some(freshness::Last::Put(Duration::from_secs(600))),
listened: Duration::from_secs(2000),
complete: false,
},
Observation::Got {
reply: None,
clock: freshness::ClockTrust::Trusted {
delta: freshness::DEFAULT_DELTA,
},
},
];
let r = Reading {
presence: Presence::Present(Listing::Listed { token: true }),
observations: &lossy,
latest: Some(Latest::Firing),
previous_instance: false,
held_whole: true,
left_out: true,
};
let pair = |j: Judged| (j.answer, j.reason);
assert_eq!(pair(firing(&r)), (Answer::No, Reason::NotHeld));
assert_eq!(
pair(stale_firing(&r)),
(Answer::NotAsked, Reason::NotFiring)
);
let not_established = Reading {
held_whole: false,
..r
};
assert_eq!(
pair(firing(¬_established)),
(Answer::Unobservable, Reason::Incomplete)
);
let answered_or_newer = Reading {
left_out: false,
..r
};
assert_eq!(
pair(firing(&answered_or_newer)),
(Answer::Unobservable, Reason::Incomplete)
);
}
}