Skip to main content

grow_graylog/
models.rs

1//! REST models of Graylog Open (system, inputs, streams, index sets) and time helpers.
2
3use std::time::{Duration, SystemTime, UNIX_EPOCH};
4
5use serde::{Deserialize, Deserializer, Serialize};
6use serde_json::{Map, Value};
7
8/// GELF UDP input class.
9pub const INPUT_TYPE_GELF_UDP: &str = "org.graylog2.inputs.gelf.udp.GELFUDPInput";
10/// GELF TCP input class.
11pub const INPUT_TYPE_GELF_TCP: &str = "org.graylog2.inputs.gelf.tcp.GELFTCPInput";
12/// GELF HTTP input class.
13pub const INPUT_TYPE_GELF_HTTP: &str = "org.graylog2.inputs.gelf.http.GELFHttpInput";
14/// OpenTelemetry (gRPC) input class.
15pub const INPUT_TYPE_OTEL_GRPC: &str = "org.graylog.inputs.otel.OTelGrpcInput";
16/// Input state of a started input.
17pub const INPUT_STATE_RUNNING: &str = "RUNNING";
18/// Input state of an input that could not start (for example a busy port).
19pub const INPUT_STATE_FAILED: &str = "FAILED";
20
21/// Stream rule type: exact match.
22pub const STREAM_RULE_EXACT: i64 = 1;
23/// Stream rule type: regular expression.
24pub const STREAM_RULE_REGEX: i64 = 2;
25/// Stream rule type: greater than.
26pub const STREAM_RULE_GREATER: i64 = 3;
27/// Stream rule type: smaller than.
28pub const STREAM_RULE_SMALLER: i64 = 4;
29/// Stream rule type: field presence.
30pub const STREAM_RULE_PRESENCE: i64 = 5;
31/// Stream rule type: contains.
32pub const STREAM_RULE_CONTAINS: i64 = 6;
33/// Stream rule type: always match.
34pub const STREAM_RULE_ALWAYS_MATCH: i64 = 7;
35/// Stream rule type: match input.
36pub const STREAM_RULE_MATCH_INPUT: i64 = 8;
37
38/// Parses ISO-8601 timestamps (`Z` or offset) and Graylog's `yyyy-MM-dd HH:mm:ss.SSS` (UTC).
39pub(crate) fn parse_graylog_time(s: &str) -> Option<SystemTime> {
40    let s = s.trim();
41    if s.is_empty() {
42        return None;
43    }
44    // Numeric offset (+hh:mm / -hh:mm) after the time part.
45    if s.len() > 16 {
46        let (base, tail) = s.split_at(s.len() - 6);
47        let b = tail.as_bytes();
48        if (b[0] == b'+' || b[0] == b'-') && b[3] == b':' {
49            let h: u64 = tail[1..3].parse().ok()?;
50            let m: u64 = tail[4..].parse().ok()?;
51            let t = humantime::parse_rfc3339_weak(base).ok()?;
52            let off = Duration::from_secs(h * 3600 + m * 60);
53            return if b[0] == b'+' {
54                t.checked_sub(off)
55            } else {
56                t.checked_add(off)
57            };
58        }
59    }
60    humantime::parse_rfc3339_weak(s.trim_end_matches('Z')).ok()
61}
62
63/// Formats a time as Graylog's ISO-8601 UTC form with milliseconds (`2026-11-18T20:23:12.920Z`).
64pub(crate) fn format_graylog_time(t: SystemTime) -> String {
65    let t = if t < UNIX_EPOCH { UNIX_EPOCH } else { t };
66    let ms = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as u64;
67    let rounded = UNIX_EPOCH + Duration::from_millis(ms);
68    humantime::format_rfc3339_millis(rounded).to_string()
69}
70
71fn de_time<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SystemTime>, D::Error> {
72    let v = Option::<Value>::deserialize(d)?;
73    Ok(v.as_ref()
74        .and_then(Value::as_str)
75        .and_then(parse_graylog_time))
76}
77
78fn de_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
79    Ok(match Option::<Value>::deserialize(d)? {
80        Some(Value::String(s)) => s,
81        _ => String::new(),
82    })
83}
84
85fn de_bool<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
86    Ok(matches!(
87        Option::<Value>::deserialize(d)?,
88        Some(Value::Bool(true))
89    ))
90}
91
92fn de_i64<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
93    Ok(Option::<Value>::deserialize(d)?
94        .as_ref()
95        .and_then(Value::as_i64)
96        .unwrap_or(0))
97}
98
99fn de_map<'de, D: Deserializer<'de>>(d: D) -> Result<Map<String, Value>, D::Error> {
100    Ok(match Option::<Value>::deserialize(d)? {
101        Some(Value::Object(m)) => m,
102        _ => Map::new(),
103    })
104}
105
106fn de_rules<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<StreamRule>, D::Error> {
107    Ok(Option::<Vec<StreamRule>>::deserialize(d)?.unwrap_or_default())
108}
109
110/// Node information (`GET /api/system`).
111#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
112pub struct SystemInfo {
113    /// `graylog-server`.
114    #[serde(default, deserialize_with = "de_string")]
115    pub facility: String,
116    /// Release code name.
117    #[serde(default, deserialize_with = "de_string")]
118    pub codename: String,
119    /// Node id.
120    #[serde(default, deserialize_with = "de_string")]
121    pub node_id: String,
122    /// Cluster id.
123    #[serde(default, deserialize_with = "de_string")]
124    pub cluster_id: String,
125    /// Full version, for example `7.0.16+58e0f6e`.
126    #[serde(default, deserialize_with = "de_string")]
127    pub version: String,
128    /// Node start time.
129    #[serde(default, deserialize_with = "de_time")]
130    pub started_at: Option<SystemTime>,
131    /// Host name of the node.
132    #[serde(default, deserialize_with = "de_string")]
133    pub hostname: String,
134    /// Lifecycle (`running`, …).
135    #[serde(default, deserialize_with = "de_string")]
136    pub lifecycle: String,
137    /// Load-balancer status (`alive`, …).
138    #[serde(default, deserialize_with = "de_string")]
139    pub lb_status: String,
140    /// Server time zone.
141    #[serde(default, deserialize_with = "de_string")]
142    pub timezone: String,
143    /// Operating system description.
144    #[serde(default, deserialize_with = "de_string")]
145    pub operating_system: String,
146    /// Whether the node is the cluster leader.
147    #[serde(default, deserialize_with = "de_bool")]
148    pub is_leader: bool,
149    /// Whether the node processes messages.
150    #[serde(default, deserialize_with = "de_bool")]
151    pub is_processing: bool,
152}
153
154/// A message input (`GET /api/system/inputs`).
155#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
156pub struct Input {
157    /// Input id.
158    #[serde(default, deserialize_with = "de_string")]
159    pub id: String,
160    /// Title.
161    #[serde(default, deserialize_with = "de_string")]
162    pub title: String,
163    /// Input class, for example [`INPUT_TYPE_GELF_TCP`].
164    #[serde(default, rename = "type", deserialize_with = "de_string")]
165    pub input_type: String,
166    /// Display name of the type.
167    #[serde(default, deserialize_with = "de_string")]
168    pub name: String,
169    /// Whether the input runs on every node.
170    #[serde(default, deserialize_with = "de_bool")]
171    pub global: bool,
172    /// Node of a local input.
173    #[serde(default, deserialize_with = "de_string")]
174    pub node: String,
175    /// Creation time.
176    #[serde(default, deserialize_with = "de_time")]
177    pub created_at: Option<SystemTime>,
178    /// Creator.
179    #[serde(default, deserialize_with = "de_string")]
180    pub creator_user_id: String,
181    /// Configuration. Secret attributes come back as `{"is_set": bool}` objects.
182    #[serde(default, deserialize_with = "de_map")]
183    pub attributes: Map<String, Value>,
184    /// Static fields added to every message.
185    #[serde(default, deserialize_with = "de_map")]
186    pub static_fields: Map<String, Value>,
187}
188
189impl Input {
190    /// The `port` attribute (0 when absent).
191    pub fn port(&self) -> u16 {
192        match self.attributes.get("port") {
193            Some(Value::Number(n)) => n
194                .as_u64()
195                .or_else(|| n.as_f64().map(|f| f as u64))
196                .and_then(|p| u16::try_from(p).ok())
197                .unwrap_or(0),
198            Some(Value::String(s)) => s.trim().parse().unwrap_or(0),
199            _ => 0,
200        }
201    }
202
203    /// The `bind_address` attribute (empty when absent).
204    pub fn bind_address(&self) -> &str {
205        self.attributes
206            .get("bind_address")
207            .and_then(Value::as_str)
208            .unwrap_or("")
209    }
210}
211
212/// Runtime state of an input (`GET /api/system/inputstates/{id}`).
213#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
214pub struct InputState {
215    /// Input id.
216    #[serde(default, deserialize_with = "de_string")]
217    pub id: String,
218    /// `RUNNING`, `STARTING`, `FAILED`, `STOPPED`, …
219    #[serde(default, deserialize_with = "de_string")]
220    pub state: String,
221    /// Start time.
222    #[serde(default, deserialize_with = "de_time")]
223    pub started_at: Option<SystemTime>,
224    /// Failure details.
225    #[serde(default, deserialize_with = "de_string")]
226    pub detailed_message: String,
227    /// The input.
228    #[serde(default, rename = "message_input")]
229    pub input: Input,
230}
231
232/// One rule of a stream.
233#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
234pub struct StreamRule {
235    /// Rule id (ignored when creating).
236    #[serde(default, deserialize_with = "de_string", skip_serializing)]
237    pub id: String,
238    /// Message field.
239    #[serde(default, deserialize_with = "de_string")]
240    pub field: String,
241    /// Rule type ([`STREAM_RULE_EXACT`], …).
242    #[serde(default, rename = "type", deserialize_with = "de_i64")]
243    pub rule_type: i64,
244    /// Value to compare.
245    #[serde(default, deserialize_with = "de_string")]
246    pub value: String,
247    /// Negates the rule.
248    #[serde(default, deserialize_with = "de_bool")]
249    pub inverted: bool,
250    /// Description.
251    #[serde(default, deserialize_with = "de_string")]
252    pub description: String,
253}
254
255impl StreamRule {
256    /// An exact-match rule `field == value`.
257    pub fn exact(field: impl Into<String>, value: impl Into<String>) -> Self {
258        StreamRule {
259            field: field.into(),
260            rule_type: STREAM_RULE_EXACT,
261            value: value.into(),
262            ..StreamRule::default()
263        }
264    }
265}
266
267/// A stream.
268#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
269pub struct Stream {
270    /// Stream id.
271    #[serde(default, deserialize_with = "de_string")]
272    pub id: String,
273    /// Title.
274    #[serde(default, deserialize_with = "de_string")]
275    pub title: String,
276    /// Description.
277    #[serde(default, deserialize_with = "de_string")]
278    pub description: String,
279    /// Routing rules.
280    #[serde(default, deserialize_with = "de_rules")]
281    pub rules: Vec<StreamRule>,
282    /// Whether the stream is paused.
283    #[serde(default, deserialize_with = "de_bool")]
284    pub disabled: bool,
285    /// Target index set.
286    #[serde(default, deserialize_with = "de_string")]
287    pub index_set_id: String,
288    /// Whether this is the default stream.
289    #[serde(default, deserialize_with = "de_bool")]
290    pub is_default: bool,
291    /// `AND` or `OR`.
292    #[serde(default, deserialize_with = "de_string")]
293    pub matching_type: String,
294    /// Whether matches leave the default stream.
295    #[serde(default, deserialize_with = "de_bool")]
296    pub remove_matches_from_default_stream: bool,
297    /// Creation time.
298    #[serde(default, deserialize_with = "de_time")]
299    pub created_at: Option<SystemTime>,
300    /// Creator.
301    #[serde(default, deserialize_with = "de_string")]
302    pub creator_user_id: String,
303}
304
305/// One page of streams.
306#[derive(Debug, Clone, Default, PartialEq)]
307pub struct StreamPage {
308    /// Streams of this page.
309    pub streams: Vec<Stream>,
310    /// Streams matching the query.
311    pub total: u64,
312    /// Page number (1-based).
313    pub page: u32,
314    /// Page size.
315    pub per_page: u32,
316}
317
318/// An index set.
319#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
320pub struct IndexSet {
321    /// Index set id.
322    #[serde(default, deserialize_with = "de_string")]
323    pub id: String,
324    /// Title.
325    #[serde(default, deserialize_with = "de_string")]
326    pub title: String,
327    /// Description.
328    #[serde(default, deserialize_with = "de_string")]
329    pub description: String,
330    /// Index prefix.
331    #[serde(default, deserialize_with = "de_string")]
332    pub index_prefix: String,
333    /// Whether this is the default index set.
334    #[serde(default, deserialize_with = "de_bool")]
335    pub default: bool,
336    /// Whether it is writable.
337    #[serde(default, deserialize_with = "de_bool")]
338    pub writable: bool,
339    /// Shards per index.
340    #[serde(default, deserialize_with = "de_i64")]
341    pub shards: i64,
342    /// Replicas per index.
343    #[serde(default, deserialize_with = "de_i64")]
344    pub replicas: i64,
345}