mielin-cli 0.1.0-rc.1

Command-line interface and control plane for MielinOS distributed agent mesh
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Remote Management for MielinCTL
//!
//! Provides capabilities to manage remote MielinOS nodes through
//! the CLI, enabling centralized control of distributed deployments.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Remote node configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteNode {
    /// Unique node identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Node address (host:port)
    pub address: String,
    /// Authentication method
    pub auth: AuthMethod,
    /// Connection options
    #[serde(default)]
    pub options: ConnectionOptions,
    /// Node tags for grouping
    #[serde(default)]
    pub tags: Vec<String>,
    /// Node description
    #[serde(default)]
    pub description: String,
}

/// Authentication method for remote connections
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum AuthMethod {
    /// No authentication (insecure)
    None,
    /// API key authentication
    ApiKey {
        /// API key value
        key: String,
    },
    /// Certificate-based authentication
    Certificate {
        /// Path to client certificate
        cert_path: String,
        /// Path to private key
        key_path: String,
        /// Optional CA certificate path
        ca_path: Option<String>,
    },
    /// Token-based authentication
    Token {
        /// Bearer token
        token: String,
    },
}

/// Connection options for remote nodes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionOptions {
    /// Connection timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
    /// Enable TLS
    #[serde(default = "default_true")]
    pub tls: bool,
    /// Verify SSL certificates
    #[serde(default = "default_true")]
    pub verify_ssl: bool,
    /// Maximum retry attempts
    #[serde(default = "default_retries")]
    pub max_retries: u32,
}

fn default_timeout() -> u64 {
    30
}

fn default_true() -> bool {
    true
}

fn default_retries() -> u32 {
    3
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            timeout_secs: default_timeout(),
            tls: default_true(),
            verify_ssl: default_true(),
            max_retries: default_retries(),
        }
    }
}

/// Remote command execution request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteCommand {
    /// Command to execute
    pub command: String,
    /// Command arguments
    pub args: Vec<String>,
    /// Environment variables
    #[serde(default)]
    pub env: HashMap<String, String>,
}

/// Remote command execution result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteCommandResult {
    /// Node ID
    pub node_id: String,
    /// Exit code
    pub exit_code: i32,
    /// Standard output
    pub stdout: String,
    /// Standard error
    pub stderr: String,
    /// Execution duration in milliseconds
    pub duration_ms: u64,
}

/// Remote node manager
pub struct RemoteManager {
    /// Remote nodes configuration
    nodes: HashMap<String, RemoteNode>,
    /// Configuration file path
    config_path: PathBuf,
}

impl RemoteManager {
    /// Create a new remote manager
    pub fn new() -> Result<Self> {
        let config_path = Self::get_config_path()?;

        let mut manager = RemoteManager {
            nodes: HashMap::new(),
            config_path,
        };

        // Load existing configuration if it exists
        if manager.config_path.exists() {
            manager.load_config()?;
        }

        Ok(manager)
    }

    /// Get the default configuration file path
    pub fn get_config_path() -> Result<PathBuf> {
        let config_dir =
            dirs::config_dir().ok_or_else(|| anyhow::anyhow!("Failed to get config directory"))?;
        let mielin_dir = config_dir.join("mielin");

        // Create directory if it doesn't exist
        if !mielin_dir.exists() {
            fs::create_dir_all(&mielin_dir).context("Failed to create mielin config directory")?;
        }

        Ok(mielin_dir.join("remote_nodes.toml"))
    }

    /// Load remote nodes configuration from file
    pub fn load_config(&mut self) -> Result<()> {
        debug!(
            "Loading remote nodes configuration from {:?}",
            self.config_path
        );

        let content = fs::read_to_string(&self.config_path)
            .context("Failed to read remote nodes configuration")?;

        let nodes: HashMap<String, RemoteNode> =
            toml::from_str(&content).context("Failed to parse remote nodes configuration")?;

        self.nodes = nodes;
        info!("Loaded {} remote node(s)", self.nodes.len());

        Ok(())
    }

    /// Save remote nodes configuration to file
    pub fn save_config(&self) -> Result<()> {
        debug!(
            "Saving remote nodes configuration to {:?}",
            self.config_path
        );

        let content = toml::to_string_pretty(&self.nodes)
            .context("Failed to serialize remote nodes configuration")?;

        fs::write(&self.config_path, content)
            .context("Failed to write remote nodes configuration")?;

        info!("Saved {} remote node(s)", self.nodes.len());
        Ok(())
    }

    /// Add a remote node
    pub fn add_node(&mut self, node: RemoteNode) -> Result<()> {
        if self.nodes.contains_key(&node.id) {
            anyhow::bail!("Remote node already exists: {}", node.id);
        }

        let id = node.id.clone();
        self.nodes.insert(id.clone(), node);
        self.save_config()?;

        info!("Added remote node: {}", id);
        Ok(())
    }

    /// Remove a remote node
    pub fn remove_node(&mut self, id: &str) -> Result<()> {
        if !self.nodes.contains_key(id) {
            anyhow::bail!("Remote node not found: {}", id);
        }

        self.nodes.remove(id);
        self.save_config()?;

        info!("Removed remote node: {}", id);
        Ok(())
    }

    /// Get a remote node by ID
    pub fn get_node(&self, id: &str) -> Option<&RemoteNode> {
        self.nodes.get(id)
    }

    /// List all remote nodes
    pub fn list_nodes(&self) -> Vec<&RemoteNode> {
        self.nodes.values().collect()
    }

    /// List nodes by tag
    pub fn list_nodes_by_tag(&self, tag: &str) -> Vec<&RemoteNode> {
        self.nodes
            .values()
            .filter(|n| n.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)))
            .collect()
    }

    /// Update a remote node
    pub fn update_node(&mut self, id: &str, node: RemoteNode) -> Result<()> {
        if !self.nodes.contains_key(id) {
            anyhow::bail!("Remote node not found: {}", id);
        }

        self.nodes.insert(id.to_string(), node);
        self.save_config()?;

        info!("Updated remote node: {}", id);
        Ok(())
    }

    /// Execute a command on a remote node
    pub async fn execute_command(
        &self,
        node_id: &str,
        command: RemoteCommand,
    ) -> Result<RemoteCommandResult> {
        let node = self
            .get_node(node_id)
            .ok_or_else(|| anyhow::anyhow!("Remote node not found: {}", node_id))?;

        debug!(
            "Executing command on remote node {}: {}",
            node_id, command.command
        );

        let start_time = std::time::Instant::now();

        // Execute command on remote node via HTTP
        let result = self.execute_remote_command(node, &command).await?;

        let duration_ms = start_time.elapsed().as_millis() as u64;

        Ok(RemoteCommandResult {
            node_id: node_id.to_string(),
            exit_code: result.exit_code,
            stdout: result.stdout,
            stderr: result.stderr,
            duration_ms,
        })
    }

    /// Execute command on remote node via HTTP
    async fn execute_remote_command(
        &self,
        node: &RemoteNode,
        command: &RemoteCommand,
    ) -> Result<RemoteCommandResult> {
        debug!(
            "Executing remote command on {}: {}",
            node.address, command.command
        );

        let start_time = std::time::Instant::now();

        // Build HTTP client with configured options
        let mut client_builder = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(node.options.timeout_secs));

        // Configure TLS if enabled
        if node.options.tls {
            client_builder = client_builder.danger_accept_invalid_certs(!node.options.verify_ssl);
        }

        let client = client_builder
            .build()
            .context("Failed to build HTTP client")?;

        // Construct API endpoint URL
        let url = if node.options.tls {
            format!("https://{}/api/v1/command", node.address)
        } else {
            format!("http://{}/api/v1/command", node.address)
        };

        // Build request with authentication
        let mut request_builder = client.post(&url).json(&serde_json::json!({
            "command": command.command,
            "args": command.args,
            "env": command.env,
        }));

        // Add authentication header based on method
        request_builder = match &node.auth {
            AuthMethod::None => request_builder,
            AuthMethod::ApiKey { key } => request_builder.header("X-API-Key", key),
            AuthMethod::Token { token } => {
                request_builder.header("Authorization", format!("Bearer {}", token))
            }
            AuthMethod::Certificate { .. } => {
                // Certificate-based auth would be configured in the TLS client builder
                request_builder
            }
        };

        // Execute request with retry logic
        let mut last_error = None;
        for attempt in 0..node.options.max_retries {
            if attempt > 0 {
                debug!("Retrying command execution (attempt {})", attempt + 1);
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }

            match request_builder
                .try_clone()
                .ok_or_else(|| anyhow::anyhow!("Failed to clone request"))?
                .send()
                .await
            {
                Ok(response) => {
                    let duration_ms = start_time.elapsed().as_millis() as u64;

                    if response.status().is_success() {
                        // Parse successful response
                        let result: serde_json::Value =
                            response.json().await.context("Failed to parse response")?;

                        return Ok(RemoteCommandResult {
                            node_id: node.id.clone(),
                            exit_code: result
                                .get("exit_code")
                                .and_then(|v| v.as_i64())
                                .unwrap_or(0) as i32,
                            stdout: result
                                .get("stdout")
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string(),
                            stderr: result
                                .get("stderr")
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string(),
                            duration_ms,
                        });
                    } else {
                        // Handle error response
                        let error_text = response
                            .text()
                            .await
                            .unwrap_or_else(|_| "Unknown error".to_string());

                        return Ok(RemoteCommandResult {
                            node_id: node.id.clone(),
                            exit_code: 1,
                            stdout: String::new(),
                            stderr: format!("HTTP error: {}", error_text),
                            duration_ms,
                        });
                    }
                }
                Err(e) => {
                    last_error = Some(e);
                }
            }
        }

        // All retries exhausted
        let duration_ms = start_time.elapsed().as_millis() as u64;
        Ok(RemoteCommandResult {
            node_id: node.id.clone(),
            exit_code: 1,
            stdout: String::new(),
            stderr: format!(
                "Connection failed after {} attempts: {}",
                node.options.max_retries,
                last_error
                    .map(|e| e.to_string())
                    .unwrap_or_else(|| "Unknown error".to_string())
            ),
            duration_ms,
        })
    }

    /// Test connection to a remote node
    pub async fn test_connection(&self, node_id: &str) -> Result<bool> {
        let node = self
            .get_node(node_id)
            .ok_or_else(|| anyhow::anyhow!("Remote node not found: {}", node_id))?;

        debug!("Testing connection to remote node: {}", node.address);

        // Build HTTP client with configured options
        let mut client_builder = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(node.options.timeout_secs));

        // Configure TLS if enabled
        if node.options.tls {
            client_builder = client_builder.danger_accept_invalid_certs(!node.options.verify_ssl);
        }

        let client = client_builder
            .build()
            .context("Failed to build HTTP client")?;

        // Construct health check URL
        let url = if node.options.tls {
            format!("https://{}/api/v1/health", node.address)
        } else {
            format!("http://{}/api/v1/health", node.address)
        };

        // Build request with authentication
        let mut request_builder = client.get(&url);

        // Add authentication header based on method
        request_builder = match &node.auth {
            AuthMethod::None => request_builder,
            AuthMethod::ApiKey { key } => request_builder.header("X-API-Key", key),
            AuthMethod::Token { token } => {
                request_builder.header("Authorization", format!("Bearer {}", token))
            }
            AuthMethod::Certificate { .. } => {
                // Certificate-based auth would be configured in the TLS client builder
                request_builder
            }
        };

        // Execute request with retry logic
        for attempt in 0..node.options.max_retries {
            if attempt > 0 {
                debug!("Retrying connection test (attempt {})", attempt + 1);
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }

            match request_builder
                .try_clone()
                .ok_or_else(|| anyhow::anyhow!("Failed to clone request"))?
                .send()
                .await
            {
                Ok(response) => {
                    if response.status().is_success() {
                        info!("Connection test successful for {}", node.name);
                        return Ok(true);
                    } else {
                        debug!("Connection test failed with status: {}", response.status());
                    }
                }
                Err(e) => {
                    debug!("Connection attempt {} failed: {}", attempt + 1, e);
                }
            }
        }

        // All connection attempts failed
        warn!(
            "Connection test failed for {} after {} attempts",
            node.name, node.options.max_retries
        );
        Ok(false)
    }

    /// Execute command on multiple nodes
    pub async fn execute_on_multiple(
        &self,
        node_ids: &[String],
        command: RemoteCommand,
    ) -> Result<Vec<RemoteCommandResult>> {
        let mut results = Vec::new();

        for node_id in node_ids {
            match self.execute_command(node_id, command.clone()).await {
                Ok(result) => results.push(result),
                Err(e) => {
                    warn!("Failed to execute command on {}: {}", node_id, e);
                    results.push(RemoteCommandResult {
                        node_id: node_id.clone(),
                        exit_code: 1,
                        stdout: String::new(),
                        stderr: format!("Error: {}", e),
                        duration_ms: 0,
                    });
                }
            }
        }

        Ok(results)
    }

    /// Import nodes from a configuration file
    pub fn import_nodes(&mut self, path: &Path) -> Result<usize> {
        if !path.exists() {
            anyhow::bail!("Import file not found: {:?}", path);
        }

        let content = fs::read_to_string(path).context("Failed to read import file")?;

        let imported_nodes: HashMap<String, RemoteNode> =
            toml::from_str(&content).context("Failed to parse import file")?;

        let count = imported_nodes.len();

        for (id, node) in imported_nodes {
            self.nodes.insert(id, node);
        }

        self.save_config()?;
        info!("Imported {} remote node(s)", count);

        Ok(count)
    }

    /// Export nodes to a configuration file
    pub fn export_nodes(&self, path: &Path) -> Result<()> {
        let content =
            toml::to_string_pretty(&self.nodes).context("Failed to serialize nodes for export")?;

        fs::write(path, content).context("Failed to write export file")?;

        info!("Exported {} remote node(s) to {:?}", self.nodes.len(), path);
        Ok(())
    }
}

impl Default for RemoteManager {
    fn default() -> Self {
        Self::new().expect("Failed to create remote manager")
    }
}

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

    #[test]
    fn test_auth_method_serialization() {
        let auth = AuthMethod::ApiKey {
            key: "test-key".to_string(),
        };

        let toml_str = toml::to_string(&auth).unwrap();
        assert!(toml_str.contains("apikey"));
        assert!(toml_str.contains("test-key"));
    }

    #[test]
    fn test_connection_options_default() {
        let options = ConnectionOptions::default();

        assert_eq!(options.timeout_secs, 30);
        assert!(options.tls);
        assert!(options.verify_ssl);
        assert_eq!(options.max_retries, 3);
    }

    #[test]
    fn test_remote_node_serialization() {
        let node = RemoteNode {
            id: "node1".to_string(),
            name: "Test Node".to_string(),
            address: "localhost:8080".to_string(),
            auth: AuthMethod::None,
            options: ConnectionOptions::default(),
            tags: vec!["test".to_string()],
            description: "A test node".to_string(),
        };

        let toml_str = toml::to_string(&node).unwrap();
        assert!(toml_str.contains("node1"));
        assert!(toml_str.contains("Test Node"));
    }

    #[test]
    fn test_remote_command() {
        let mut env = HashMap::new();
        env.insert("TEST".to_string(), "value".to_string());

        let cmd = RemoteCommand {
            command: "test".to_string(),
            args: vec!["arg1".to_string()],
            env,
        };

        assert_eq!(cmd.command, "test");
        assert_eq!(cmd.args.len(), 1);
    }

    #[test]
    fn test_remote_manager_creation() {
        let manager = RemoteManager::new();
        assert!(manager.is_ok());

        // Note: manager may load existing nodes from config file
        // Just verify it was created successfully - no need to check length
    }

    #[test]
    fn test_add_and_remove_node() {
        let mut manager = RemoteManager::new().unwrap();

        // Use timestamp-based unique ID to avoid conflicts with persistent config
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_micros();
        let node_id = format!("test-node-{}", timestamp);

        let node = RemoteNode {
            id: node_id.clone(),
            name: "Test Node".to_string(),
            address: "localhost:8080".to_string(),
            auth: AuthMethod::None,
            options: ConnectionOptions::default(),
            tags: vec![],
            description: String::new(),
        };

        assert!(manager.add_node(node.clone()).is_ok());
        assert!(manager.get_node(&node_id).is_some());
        assert!(manager.remove_node(&node_id).is_ok());
        assert!(manager.get_node(&node_id).is_none());
    }

    #[test]
    fn test_list_nodes_by_tag() {
        let mut manager = RemoteManager::new().unwrap();

        // Use timestamp-based unique IDs to avoid conflicts with persistent config
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_micros();
        let node1_id = format!("test-tag-node1-{}", timestamp);
        let node2_id = format!("test-tag-node2-{}", timestamp);

        let node1 = RemoteNode {
            id: node1_id.clone(),
            name: "Node 1".to_string(),
            address: "localhost:8080".to_string(),
            auth: AuthMethod::None,
            options: ConnectionOptions::default(),
            tags: vec!["prod".to_string()],
            description: String::new(),
        };

        let node2 = RemoteNode {
            id: node2_id.clone(),
            name: "Node 2".to_string(),
            address: "localhost:8081".to_string(),
            auth: AuthMethod::None,
            options: ConnectionOptions::default(),
            tags: vec!["dev".to_string()],
            description: String::new(),
        };

        let _ = manager.add_node(node1);
        let _ = manager.add_node(node2);

        let prod_nodes = manager.list_nodes_by_tag("prod");
        assert!(prod_nodes.iter().any(|n| n.id == node1_id));

        // Clean up
        let _ = manager.remove_node(&node1_id);
        let _ = manager.remove_node(&node2_id);
    }
}