devops-models 0.1.0

Typed serde models for DevOps configuration formats: Kubernetes, Docker Compose, GitLab CI, GitHub Actions, Prometheus, Alertmanager, Helm, Ansible, and OpenAPI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::models::validation::{ConfigValidator, Diagnostic, Severity, YamlType};

// ═══════════════════════════════════════════════════════════════════════════
// Prometheus Configuration
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrometheusGlobal {
    #[serde(default)]
    pub scrape_interval: Option<String>,
    #[serde(default)]
    pub scrape_timeout: Option<String>,
    #[serde(default)]
    pub evaluation_interval: Option<String>,
    #[serde(default)]
    pub external_labels: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaticConfig {
    pub targets: Vec<String>,
    #[serde(default)]
    pub labels: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScrapeConfig {
    pub job_name: String,
    #[serde(default)]
    pub static_configs: Vec<StaticConfig>,
    #[serde(default)]
    pub scrape_interval: Option<String>,
    #[serde(default)]
    pub scrape_timeout: Option<String>,
    #[serde(default)]
    pub metrics_path: Option<String>,
    #[serde(default)]
    pub scheme: Option<String>,
    #[serde(default)]
    pub honor_labels: Option<bool>,
    #[serde(default)]
    pub honor_timestamps: Option<bool>,
    #[serde(default)]
    pub params: Option<serde_json::Value>,
    #[serde(default)]
    pub basic_auth: Option<serde_json::Value>,
    #[serde(default)]
    pub bearer_token: Option<String>,
    #[serde(default)]
    pub bearer_token_file: Option<String>,
    #[serde(default)]
    pub tls_config: Option<serde_json::Value>,
    #[serde(default)]
    pub relabel_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub metric_relabel_configs: Vec<serde_json::Value>,
    // Service discovery
    #[serde(default)]
    pub kubernetes_sd_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub consul_sd_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub dns_sd_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub file_sd_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub ec2_sd_configs: Vec<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertingAlertmanager {
    #[serde(default)]
    pub static_configs: Vec<StaticConfig>,
    #[serde(default)]
    pub scheme: Option<String>,
    #[serde(default)]
    pub path_prefix: Option<String>,
    #[serde(default)]
    pub timeout: Option<String>,
    #[serde(default)]
    pub tls_config: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertingConfig {
    #[serde(default)]
    pub alertmanagers: Vec<AlertingAlertmanager>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrometheusConfig {
    #[serde(default)]
    pub global: Option<PrometheusGlobal>,
    #[serde(default)]
    pub scrape_configs: Vec<ScrapeConfig>,
    #[serde(default)]
    pub rule_files: Vec<String>,
    #[serde(default)]
    pub alerting: Option<AlertingConfig>,
    #[serde(default)]
    pub remote_write: Vec<serde_json::Value>,
    #[serde(default)]
    pub remote_read: Vec<serde_json::Value>,
    #[serde(default)]
    pub storage: Option<serde_json::Value>,
}

impl PrometheusConfig {
    pub fn from_value(data: serde_json::Value) -> Result<Self, String> {
        serde_json::from_value(data)
            .map_err(|e| format!("Failed to parse Prometheus config: {e}"))
    }
}

/// Parse a Prometheus duration string to seconds (e.g., "30s", "1m", "5m")
fn parse_duration_secs(s: &str) -> Option<u64> {
    let s = s.trim();
    if let Some(rest) = s.strip_suffix('s') {
        return rest.parse().ok();
    }
    if let Some(rest) = s.strip_suffix('m') {
        return rest.parse::<u64>().ok().map(|m| m * 60);
    }
    if let Some(rest) = s.strip_suffix('h') {
        return rest.parse::<u64>().ok().map(|h| h * 3600);
    }
    if let Some(rest) = s.strip_suffix('d') {
        return rest.parse::<u64>().ok().map(|d| d * 86400);
    }
    None
}

impl ConfigValidator for PrometheusConfig {
    fn yaml_type(&self) -> YamlType { YamlType::Prometheus }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if self.scrape_configs.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: "No scrape_configs defined — Prometheus won't scrape any targets".into(),
                path: Some("scrape_configs".into()),
            });
        }
        // Check that job names are unique
        let mut job_names: HashMap<&str, usize> = HashMap::new();
        for sc in &self.scrape_configs {
            *job_names.entry(&sc.job_name).or_insert(0) += 1;
        }
        for (name, count) in &job_names {
            if *count > 1 {
                diags.push(Diagnostic {
                    severity: Severity::Error,
                    message: format!("Duplicate job_name '{}' found {} times", name, count),
                    path: Some("scrape_configs > job_name".into()),
                });
            }
        }
        diags
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();

        // Global scrape_interval check
        if let Some(global) = &self.global {
            if let Some(interval) = &global.scrape_interval
                && let Some(secs) = parse_duration_secs(interval)
                    && secs < 5 {
                        diags.push(Diagnostic {
                            severity: Severity::Warning,
                            message: format!("global.scrape_interval='{}' is very aggressive — may overload targets", interval),
                            path: Some("global > scrape_interval".into()),
                        });
                    }
            if let Some(timeout) = &global.scrape_timeout
                && let (Some(t_secs), Some(i_secs)) = (
                    parse_duration_secs(timeout),
                    global.scrape_interval.as_ref().and_then(|i| parse_duration_secs(i)),
                )
                    && t_secs > i_secs {
                        diags.push(Diagnostic {
                            severity: Severity::Warning,
                            message: format!("global.scrape_timeout ({}) > scrape_interval ({}) — scrapes may overlap", timeout, global.scrape_interval.as_deref().unwrap_or("?")),
                            path: Some("global > scrape_timeout".into()),
                        });
                    }
        }

        // Per-job checks
        for sc in &self.scrape_configs {
            if sc.static_configs.is_empty()
                && sc.kubernetes_sd_configs.is_empty()
                && sc.consul_sd_configs.is_empty()
                && sc.dns_sd_configs.is_empty()
                && sc.file_sd_configs.is_empty()
                && sc.ec2_sd_configs.is_empty()
            {
                diags.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("Job '{}': no targets or service discovery configured", sc.job_name),
                    path: Some(format!("scrape_configs > {}", sc.job_name)),
                });
            }
        }

        // Alerting check
        if self.alerting.is_none() && !self.rule_files.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "rule_files defined but no alerting config — alerts won't be delivered".into(),
                path: Some("alerting".into()),
            });
        }

        diags
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Alertmanager Configuration
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertmanagerGlobal {
    #[serde(default)]
    pub smtp_smarthost: Option<String>,
    #[serde(default)]
    pub smtp_from: Option<String>,
    #[serde(default)]
    pub smtp_auth_username: Option<String>,
    #[serde(default)]
    pub smtp_require_tls: Option<bool>,
    #[serde(default)]
    pub slack_api_url: Option<String>,
    #[serde(default)]
    pub pagerduty_url: Option<String>,
    #[serde(default)]
    pub resolve_timeout: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertmanagerRoute {
    #[serde(default)]
    pub receiver: Option<String>,
    #[serde(default)]
    pub group_by: Vec<String>,
    #[serde(default)]
    pub group_wait: Option<String>,
    #[serde(default)]
    pub group_interval: Option<String>,
    #[serde(default)]
    pub repeat_interval: Option<String>,
    #[serde(default, rename = "match")]
    pub match_labels: Option<HashMap<String, String>>,
    #[serde(default)]
    pub match_re: Option<HashMap<String, String>>,
    #[serde(default)]
    pub matchers: Vec<String>,
    #[serde(default)]
    pub routes: Vec<AlertmanagerRoute>,
    #[serde(default, rename = "continue")]
    pub continue_matching: Option<bool>,
    #[serde(default)]
    pub mute_time_intervals: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertmanagerReceiver {
    pub name: String,
    #[serde(default)]
    pub email_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub slack_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub pagerduty_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub webhook_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub opsgenie_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub victorops_configs: Vec<serde_json::Value>,
    #[serde(default)]
    pub pushover_configs: Vec<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertmanagerInhibitRule {
    #[serde(default)]
    pub source_match: Option<HashMap<String, String>>,
    #[serde(default)]
    pub source_match_re: Option<HashMap<String, String>>,
    #[serde(default)]
    pub source_matchers: Vec<String>,
    #[serde(default)]
    pub target_match: Option<HashMap<String, String>>,
    #[serde(default)]
    pub target_match_re: Option<HashMap<String, String>>,
    #[serde(default)]
    pub target_matchers: Vec<String>,
    #[serde(default)]
    pub equal: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertmanagerConfig {
    #[serde(default)]
    pub global: Option<AlertmanagerGlobal>,
    pub route: AlertmanagerRoute,
    #[serde(default)]
    pub receivers: Vec<AlertmanagerReceiver>,
    #[serde(default)]
    pub inhibit_rules: Vec<AlertmanagerInhibitRule>,
    #[serde(default)]
    pub templates: Vec<String>,
    #[serde(default)]
    pub time_intervals: Vec<serde_json::Value>,
    #[serde(default)]
    pub mute_time_intervals: Vec<serde_json::Value>,
}

impl AlertmanagerConfig {
    pub fn from_value(data: serde_json::Value) -> Result<Self, String> {
        serde_json::from_value(data)
            .map_err(|e| format!("Failed to parse Alertmanager config: {e}"))
    }
}

impl ConfigValidator for AlertmanagerConfig {
    fn yaml_type(&self) -> YamlType { YamlType::Alertmanager }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if self.route.receiver.is_none() {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: "Root route must have a 'receiver'".into(),
                path: Some("route > receiver".into()),
            });
        }
        if self.receivers.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: "No receivers defined".into(),
                path: Some("receivers".into()),
            });
        }
        // Check that route.receiver references a defined receiver
        let receiver_names: Vec<&str> = self.receivers.iter().map(|r| r.name.as_str()).collect();
        if let Some(root_receiver) = &self.route.receiver
            && !receiver_names.contains(&root_receiver.as_str()) {
                diags.push(Diagnostic {
                    severity: Severity::Error,
                    message: format!("Root route receiver '{}' is not defined", root_receiver),
                    path: Some("route > receiver".into()),
                });
            }
        // Check sub-route receivers
        check_route_receivers(&self.route, &receiver_names, &mut diags);
        diags
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        // Check for "null" receivers (no notification configs)
        for r in &self.receivers {
            if r.email_configs.is_empty()
                && r.slack_configs.is_empty()
                && r.pagerduty_configs.is_empty()
                && r.webhook_configs.is_empty()
                && r.opsgenie_configs.is_empty()
                && r.victorops_configs.is_empty()
                && r.pushover_configs.is_empty()
            {
                diags.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("Receiver '{}' has no notification channels configured — alerts will be silently dropped", r.name),
                    path: Some(format!("receivers > {}", r.name)),
                });
            }
        }
        // group_by check
        if self.route.group_by.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: "Root route has no group_by — all alerts will be grouped together".into(),
                path: Some("route > group_by".into()),
            });
        }
        diags
    }
}

fn check_route_receivers(route: &AlertmanagerRoute, receivers: &[&str], diags: &mut Vec<Diagnostic>) {
    for sub in &route.routes {
        if let Some(recv) = &sub.receiver
            && !receivers.contains(&recv.as_str()) {
                diags.push(Diagnostic {
                    severity: Severity::Error,
                    message: format!("Sub-route receiver '{}' is not defined", recv),
                    path: Some("route > routes > receiver".into()),
                });
            }
        check_route_receivers(sub, receivers, diags);
    }
}