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
//! GitOps workflow support for chaos orchestrations
//!
//! Provides integration with GitOps tools like Flux and ArgoCD for
//! managing chaos orchestrations declaratively.

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

/// GitOps repository configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitOpsConfig {
    /// Repository URL
    pub repo_url: String,
    /// Branch to watch
    pub branch: String,
    /// Path within repository
    pub path: PathBuf,
    /// Sync interval in seconds
    pub sync_interval_seconds: u64,
    /// Authentication
    pub auth: GitOpsAuth,
    /// Auto-sync enabled
    pub auto_sync: bool,
    /// Prune on sync (delete removed orchestrations)
    pub prune: bool,
}

/// Authentication for Git repository
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum GitOpsAuth {
    #[serde(rename = "ssh")]
    SSH { private_key_path: PathBuf },
    #[serde(rename = "token")]
    Token { token: String },
    #[serde(rename = "basic")]
    Basic { username: String, password: String },
}

/// GitOps sync status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncStatus {
    pub last_sync: DateTime<Utc>,
    pub commit_hash: String,
    pub status: SyncState,
    pub orchestrations_synced: usize,
    pub errors: Vec<String>,
}

/// Sync state
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SyncState {
    Synced,
    OutOfSync,
    Syncing,
    Failed,
}

/// Orchestration manifest in GitOps repository
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrchestrationManifest {
    pub file_path: PathBuf,
    pub content: serde_json::Value,
    pub hash: String,
    pub last_modified: DateTime<Utc>,
}

/// GitOps manager
pub struct GitOpsManager {
    config: GitOpsConfig,
    manifests: HashMap<String, OrchestrationManifest>,
    last_sync_status: Option<SyncStatus>,
}

impl GitOpsManager {
    /// Create a new GitOps manager
    pub fn new(config: GitOpsConfig) -> Self {
        Self {
            config,
            manifests: HashMap::new(),
            last_sync_status: None,
        }
    }

    /// Sync orchestrations from Git repository
    pub async fn sync(&mut self) -> Result<SyncStatus, String> {
        // In a real implementation, this would:
        // 1. Clone/pull the Git repository
        // 2. Scan for orchestration YAML files
        // 3. Parse and validate them
        // 4. Apply changes (create/update/delete orchestrations)
        // 5. Return sync status

        let start_time = Utc::now();

        // Simulate sync process
        let manifests = self.discover_manifests().await?;
        let _changes: Vec<()> = self.calculate_changes(&manifests)?;

        // Apply changes - not implemented
        let mut errors = Vec::new();

        // Cleanup (prune) if enabled
        if self.config.prune {
            if let Err(e) = self.prune_removed_orchestrations(&manifests).await {
                errors.push(format!("Failed to prune: {}", e));
            }
        }

        let status = SyncStatus {
            last_sync: start_time,
            commit_hash: "abc123def456".to_string(), // Would be actual git hash
            status: if errors.is_empty() {
                SyncState::Synced
            } else {
                SyncState::Failed
            },
            orchestrations_synced: manifests.len(),
            errors,
        };

        self.last_sync_status = Some(status.clone());
        Ok(status)
    }

    /// Discover orchestration manifests in repository
    async fn discover_manifests(&self) -> Result<Vec<OrchestrationManifest>, String> {
        // In real implementation: scan repository for YAML files
        Ok(Vec::new())
    }

    /// Calculate changes between current and desired state
    fn calculate_changes(&self, _manifests: &[OrchestrationManifest]) -> Result<Vec<()>, String> {
        // Compare manifests with currently deployed orchestrations
        // Return list of changes (create, update, delete)
        Ok(Vec::new())
    }

    /// Prune orchestrations that are no longer in Git
    async fn prune_removed_orchestrations(
        &mut self,
        current_manifests: &[OrchestrationManifest],
    ) -> Result<(), String> {
        let current_names: Vec<String> = current_manifests
            .iter()
            .map(|m| m.file_path.to_string_lossy().to_string())
            .collect();

        self.manifests.retain(|name, _| current_names.contains(name));

        Ok(())
    }

    /// Get current sync status
    pub fn get_status(&self) -> Option<&SyncStatus> {
        self.last_sync_status.as_ref()
    }

    /// Check if auto-sync is enabled
    pub fn is_auto_sync_enabled(&self) -> bool {
        self.config.auto_sync
    }

    /// Get sync interval
    pub fn get_sync_interval(&self) -> u64 {
        self.config.sync_interval_seconds
    }

    /// Start auto-sync loop
    pub async fn start_auto_sync(&mut self) -> Result<(), String> {
        if !self.config.auto_sync {
            return Err("Auto-sync is not enabled".to_string());
        }

        loop {
            match self.sync().await {
                Ok(status) => {
                    println!("Sync completed: {:?}", status.status);
                }
                Err(e) => {
                    eprintln!("Sync failed: {}", e);
                }
            }

            tokio::time::sleep(tokio::time::Duration::from_secs(self.config.sync_interval_seconds))
                .await;
        }
    }
}

/// Flux integration
pub mod flux {
    use super::*;

    /// Flux Kustomization configuration
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct FluxKustomization {
        pub api_version: String,
        pub kind: String,
        pub metadata: FluxMetadata,
        pub spec: FluxSpec,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct FluxMetadata {
        pub name: String,
        pub namespace: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct FluxSpec {
        pub interval: String,
        pub path: String,
        pub prune: bool,
        pub source_ref: SourceRef,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct SourceRef {
        pub kind: String,
        pub name: String,
    }

    impl FluxKustomization {
        /// Create a new Flux Kustomization for MockForge orchestrations
        pub fn new_for_orchestrations(
            name: String,
            namespace: String,
            git_repo: String,
            path: String,
        ) -> Self {
            Self {
                api_version: "kustomize.toolkit.fluxcd.io/v1".to_string(),
                kind: "Kustomization".to_string(),
                metadata: FluxMetadata {
                    name: name.clone(),
                    namespace,
                },
                spec: FluxSpec {
                    interval: "5m".to_string(),
                    path,
                    prune: true,
                    source_ref: SourceRef {
                        kind: "GitRepository".to_string(),
                        name: git_repo,
                    },
                },
            }
        }

        /// Convert to YAML
        pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
            serde_yaml::to_string(self)
        }
    }
}

/// ArgoCD integration
pub mod argocd {
    use super::*;

    /// ArgoCD Application configuration
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ArgoApplication {
        pub api_version: String,
        pub kind: String,
        pub metadata: ArgoMetadata,
        pub spec: ArgoSpec,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ArgoMetadata {
        pub name: String,
        pub namespace: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ArgoSpec {
        pub project: String,
        pub source: ArgoSource,
        pub destination: ArgoDestination,
        pub sync_policy: Option<SyncPolicy>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct ArgoSource {
        pub repo_url: String,
        pub target_revision: String,
        pub path: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ArgoDestination {
        pub server: String,
        pub namespace: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct SyncPolicy {
        pub automated: Option<AutomatedSync>,
        pub sync_options: Vec<String>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AutomatedSync {
        pub prune: bool,
        #[serde(rename = "selfHeal")]
        pub self_heal: bool,
    }

    impl ArgoApplication {
        /// Create a new ArgoCD Application for MockForge orchestrations
        pub fn new_for_orchestrations(
            name: String,
            namespace: String,
            repo_url: String,
            path: String,
            auto_sync: bool,
        ) -> Self {
            Self {
                api_version: "argoproj.io/v1alpha1".to_string(),
                kind: "Application".to_string(),
                metadata: ArgoMetadata {
                    name: name.clone(),
                    namespace: namespace.clone(),
                },
                spec: ArgoSpec {
                    project: "default".to_string(),
                    source: ArgoSource {
                        repo_url,
                        target_revision: "HEAD".to_string(),
                        path,
                    },
                    destination: ArgoDestination {
                        server: "https://kubernetes.default.svc".to_string(),
                        namespace,
                    },
                    sync_policy: if auto_sync {
                        Some(SyncPolicy {
                            automated: Some(AutomatedSync {
                                prune: true,
                                self_heal: true,
                            }),
                            sync_options: vec!["CreateNamespace=true".to_string()],
                        })
                    } else {
                        None
                    },
                },
            }
        }

        /// Convert to YAML
        pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
            serde_yaml::to_string(self)
        }
    }
}

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

    #[test]
    fn test_gitops_manager_creation() {
        let config = GitOpsConfig {
            repo_url: "https://github.com/example/chaos-configs".to_string(),
            branch: "main".to_string(),
            path: PathBuf::from("orchestrations"),
            sync_interval_seconds: 300,
            auth: GitOpsAuth::Token {
                token: "test-token".to_string(),
            },
            auto_sync: true,
            prune: true,
        };

        let manager = GitOpsManager::new(config);
        assert!(manager.is_auto_sync_enabled());
        assert_eq!(manager.get_sync_interval(), 300);
    }

    #[test]
    fn test_flux_kustomization() {
        let kustomization = flux::FluxKustomization::new_for_orchestrations(
            "chaos-orchestrations".to_string(),
            "chaos-testing".to_string(),
            "chaos-repo".to_string(),
            "./orchestrations".to_string(),
        );

        assert_eq!(kustomization.metadata.name, "chaos-orchestrations");
        assert!(kustomization.spec.prune);
    }

    #[test]
    fn test_argocd_application() {
        let app = argocd::ArgoApplication::new_for_orchestrations(
            "chaos-app".to_string(),
            "chaos-testing".to_string(),
            "https://github.com/example/chaos".to_string(),
            "./orchestrations".to_string(),
            true,
        );

        assert_eq!(app.metadata.name, "chaos-app");
        assert!(app.spec.sync_policy.is_some());
    }
}