mockforge-chaos 0.3.21

Chaos engineering features for MockForge - fault injection and resilience testing
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Multi-cluster orchestration support
//!
//! Execute chaos orchestrations across multiple Kubernetes clusters simultaneously.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Multi-cluster orchestration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiClusterOrchestration {
    pub name: String,
    pub description: Option<String>,
    pub clusters: Vec<ClusterTarget>,
    pub synchronization: SyncMode,
    pub orchestration: serde_json::Value,
    pub failover_policy: FailoverPolicy,
}

/// Target cluster configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterTarget {
    pub name: String,
    pub context: String,
    pub namespace: String,
    pub region: Option<String>,
    pub priority: u32,
    pub enabled: bool,
}

/// Synchronization mode for multi-cluster execution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SyncMode {
    Parallel,   // Execute on all clusters simultaneously
    Sequential, // Execute one cluster at a time
    Rolling,    // Rolling execution with configurable window
    Canary,     // Execute on canary cluster first, then others
}

/// Failover policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailoverPolicy {
    pub enabled: bool,
    pub max_failures: usize,
    pub continue_on_cluster_failure: bool,
}

/// Multi-cluster execution status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiClusterStatus {
    pub orchestration_name: String,
    pub start_time: DateTime<Utc>,
    pub end_time: Option<DateTime<Utc>>,
    pub overall_status: ExecutionStatus,
    pub cluster_statuses: HashMap<String, ClusterExecutionStatus>,
    pub total_clusters: usize,
    pub successful_clusters: usize,
    pub failed_clusters: usize,
}

/// Execution status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ExecutionStatus {
    Pending,
    Running,
    Completed,
    Failed,
    PartialSuccess,
}

/// Status for individual cluster
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterExecutionStatus {
    pub cluster_name: String,
    pub status: ExecutionStatus,
    pub start_time: Option<DateTime<Utc>>,
    pub end_time: Option<DateTime<Utc>>,
    pub progress: f64,
    pub error: Option<String>,
    pub metrics: ClusterMetrics,
}

/// Metrics for cluster execution
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ClusterMetrics {
    pub steps_completed: usize,
    pub steps_total: usize,
    pub failures: usize,
    pub avg_latency_ms: f64,
    pub error_rate: f64,
}

/// Multi-cluster orchestrator
pub struct MultiClusterOrchestrator {
    orchestrations: HashMap<String, MultiClusterOrchestration>,
    statuses: HashMap<String, MultiClusterStatus>,
}

impl MultiClusterOrchestrator {
    /// Create a new multi-cluster orchestrator
    pub fn new() -> Self {
        Self {
            orchestrations: HashMap::new(),
            statuses: HashMap::new(),
        }
    }

    /// Register a multi-cluster orchestration
    pub fn register(&mut self, orchestration: MultiClusterOrchestration) {
        self.orchestrations.insert(orchestration.name.clone(), orchestration);
    }

    /// Execute a multi-cluster orchestration
    pub async fn execute(&mut self, name: &str) -> Result<MultiClusterStatus, String> {
        let orchestration = self
            .orchestrations
            .get(name)
            .ok_or_else(|| format!("Orchestration '{}' not found", name))?
            .clone();

        let start_time = Utc::now();
        let mut cluster_statuses = HashMap::new();

        // Initialize cluster statuses
        for cluster in &orchestration.clusters {
            if cluster.enabled {
                cluster_statuses.insert(
                    cluster.name.clone(),
                    ClusterExecutionStatus {
                        cluster_name: cluster.name.clone(),
                        status: ExecutionStatus::Pending,
                        start_time: None,
                        end_time: None,
                        progress: 0.0,
                        error: None,
                        metrics: ClusterMetrics::default(),
                    },
                );
            }
        }

        let mut status = MultiClusterStatus {
            orchestration_name: name.to_string(),
            start_time,
            end_time: None,
            overall_status: ExecutionStatus::Running,
            cluster_statuses: cluster_statuses.clone(),
            total_clusters: orchestration.clusters.iter().filter(|c| c.enabled).count(),
            successful_clusters: 0,
            failed_clusters: 0,
        };

        // Execute based on synchronization mode
        match orchestration.synchronization {
            SyncMode::Parallel => {
                self.execute_parallel(&orchestration, &mut status).await?;
            }
            SyncMode::Sequential => {
                self.execute_sequential(&orchestration, &mut status).await?;
            }
            SyncMode::Rolling => {
                self.execute_rolling(&orchestration, &mut status).await?;
            }
            SyncMode::Canary => {
                self.execute_canary(&orchestration, &mut status).await?;
            }
        }

        status.end_time = Some(Utc::now());

        // Determine overall status
        if status.failed_clusters == 0 {
            status.overall_status = ExecutionStatus::Completed;
        } else if status.successful_clusters > 0 {
            status.overall_status = ExecutionStatus::PartialSuccess;
        } else {
            status.overall_status = ExecutionStatus::Failed;
        }

        self.statuses.insert(name.to_string(), status.clone());

        Ok(status)
    }

    /// Execute on all clusters in parallel
    async fn execute_parallel(
        &self,
        orchestration: &MultiClusterOrchestration,
        status: &mut MultiClusterStatus,
    ) -> Result<(), String> {
        // In real implementation, spawn tasks for each cluster
        for cluster in &orchestration.clusters {
            if !cluster.enabled {
                continue;
            }

            match self.execute_on_cluster(cluster, &orchestration.orchestration).await {
                Ok(cluster_status) => {
                    status.cluster_statuses.insert(cluster.name.clone(), cluster_status);
                    status.successful_clusters += 1;
                }
                Err(e) => {
                    if let Some(cluster_status) = status.cluster_statuses.get_mut(&cluster.name) {
                        cluster_status.status = ExecutionStatus::Failed;
                        cluster_status.error = Some(e.clone());
                    }
                    status.failed_clusters += 1;

                    if !orchestration.failover_policy.continue_on_cluster_failure {
                        return Err(format!("Cluster {} failed: {}", cluster.name, e));
                    }
                }
            }
        }

        Ok(())
    }

    /// Execute on clusters sequentially
    async fn execute_sequential(
        &self,
        orchestration: &MultiClusterOrchestration,
        status: &mut MultiClusterStatus,
    ) -> Result<(), String> {
        for cluster in &orchestration.clusters {
            if !cluster.enabled {
                continue;
            }

            match self.execute_on_cluster(cluster, &orchestration.orchestration).await {
                Ok(cluster_status) => {
                    status.cluster_statuses.insert(cluster.name.clone(), cluster_status);
                    status.successful_clusters += 1;
                }
                Err(e) => {
                    if let Some(cluster_status) = status.cluster_statuses.get_mut(&cluster.name) {
                        cluster_status.status = ExecutionStatus::Failed;
                        cluster_status.error = Some(e.clone());
                    }
                    status.failed_clusters += 1;

                    if !orchestration.failover_policy.continue_on_cluster_failure {
                        return Err(format!("Cluster {} failed: {}", cluster.name, e));
                    }
                }
            }
        }

        Ok(())
    }

    /// Execute with rolling deployment
    async fn execute_rolling(
        &self,
        orchestration: &MultiClusterOrchestration,
        status: &mut MultiClusterStatus,
    ) -> Result<(), String> {
        // Rolling execution with window size of 1-2 clusters at a time
        let window_size = 2;
        let mut enabled_clusters: Vec<_> =
            orchestration.clusters.iter().filter(|c| c.enabled).collect();

        enabled_clusters.sort_by_key(|c| c.priority);

        for window in enabled_clusters.chunks(window_size) {
            for cluster in window {
                match self.execute_on_cluster(cluster, &orchestration.orchestration).await {
                    Ok(cluster_status) => {
                        status.cluster_statuses.insert(cluster.name.clone(), cluster_status);
                        status.successful_clusters += 1;
                    }
                    Err(e) => {
                        if let Some(cluster_status) = status.cluster_statuses.get_mut(&cluster.name)
                        {
                            cluster_status.status = ExecutionStatus::Failed;
                            cluster_status.error = Some(e.clone());
                        }
                        status.failed_clusters += 1;

                        if !orchestration.failover_policy.continue_on_cluster_failure {
                            return Err(format!("Cluster {} failed: {}", cluster.name, e));
                        }
                    }
                }
            }

            // Small delay between windows
            tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
        }

        Ok(())
    }

    /// Execute with canary strategy
    async fn execute_canary(
        &self,
        orchestration: &MultiClusterOrchestration,
        status: &mut MultiClusterStatus,
    ) -> Result<(), String> {
        // Find canary cluster (highest priority)
        let mut enabled_clusters: Vec<_> =
            orchestration.clusters.iter().filter(|c| c.enabled).collect();

        enabled_clusters.sort_by_key(|c| std::cmp::Reverse(c.priority));

        if enabled_clusters.is_empty() {
            return Err("No enabled clusters".to_string());
        }

        // Execute on canary first
        let canary = enabled_clusters[0];
        match self.execute_on_cluster(canary, &orchestration.orchestration).await {
            Ok(cluster_status) => {
                status.cluster_statuses.insert(canary.name.clone(), cluster_status);
                status.successful_clusters += 1;
            }
            Err(e) => {
                return Err(format!("Canary cluster {} failed: {}", canary.name, e));
            }
        }

        // If canary succeeded, execute on remaining clusters
        for cluster in &enabled_clusters[1..] {
            match self.execute_on_cluster(cluster, &orchestration.orchestration).await {
                Ok(cluster_status) => {
                    status.cluster_statuses.insert(cluster.name.clone(), cluster_status);
                    status.successful_clusters += 1;
                }
                Err(e) => {
                    if let Some(cluster_status) = status.cluster_statuses.get_mut(&cluster.name) {
                        cluster_status.status = ExecutionStatus::Failed;
                        cluster_status.error = Some(e.clone());
                    }
                    status.failed_clusters += 1;

                    if !orchestration.failover_policy.continue_on_cluster_failure {
                        return Err(format!("Cluster {} failed: {}", cluster.name, e));
                    }
                }
            }
        }

        Ok(())
    }

    /// Execute orchestration on a single cluster
    async fn execute_on_cluster(
        &self,
        cluster: &ClusterTarget,
        _orchestration: &serde_json::Value,
    ) -> Result<ClusterExecutionStatus, String> {
        // In real implementation:
        // 1. Connect to cluster using context
        // 2. Deploy orchestration
        // 3. Monitor execution
        // 4. Collect metrics

        // Simulated execution
        Ok(ClusterExecutionStatus {
            cluster_name: cluster.name.clone(),
            status: ExecutionStatus::Completed,
            start_time: Some(Utc::now()),
            end_time: Some(Utc::now()),
            progress: 1.0,
            error: None,
            metrics: ClusterMetrics {
                steps_completed: 5,
                steps_total: 5,
                failures: 0,
                avg_latency_ms: 125.0,
                error_rate: 0.0,
            },
        })
    }

    /// Get status of a multi-cluster orchestration
    pub fn get_status(&self, name: &str) -> Option<&MultiClusterStatus> {
        self.statuses.get(name)
    }

    /// List all registered orchestrations
    pub fn list_orchestrations(&self) -> Vec<String> {
        self.orchestrations.keys().cloned().collect()
    }
}

impl Default for MultiClusterOrchestrator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_multi_cluster_orchestrator_creation() {
        let orchestrator = MultiClusterOrchestrator::new();
        assert_eq!(orchestrator.list_orchestrations().len(), 0);
    }

    #[test]
    fn test_register_orchestration() {
        let mut orchestrator = MultiClusterOrchestrator::new();

        let orch = MultiClusterOrchestration {
            name: "test-orch".to_string(),
            description: Some("Test".to_string()),
            clusters: vec![ClusterTarget {
                name: "cluster-1".to_string(),
                context: "kind-cluster-1".to_string(),
                namespace: "default".to_string(),
                region: Some("us-east-1".to_string()),
                priority: 1,
                enabled: true,
            }],
            synchronization: SyncMode::Parallel,
            orchestration: serde_json::json!({}),
            failover_policy: FailoverPolicy {
                enabled: true,
                max_failures: 1,
                continue_on_cluster_failure: true,
            },
        };

        orchestrator.register(orch);
        assert_eq!(orchestrator.list_orchestrations().len(), 1);
    }
}