|
| 1 | +use anyhow::{Context, Result}; |
| 2 | +use clap::Args; |
| 3 | +use colored::Colorize; |
| 4 | +use std::io::{Read, Write}; |
| 5 | +use std::net::TcpStream; |
| 6 | +use std::time::Duration; |
| 7 | + |
| 8 | +use crate::config::{self, Template}; |
| 9 | + |
| 10 | +#[derive(Args, Debug)] |
| 11 | +pub struct LogsArgs { |
| 12 | + /// EC2 instance public hostname or IP. |
| 13 | + #[arg(long, env = "TEE_EC2_HOST")] |
| 14 | + pub host: String, |
| 15 | + |
| 16 | + /// Override the default TCP port for the template. |
| 17 | + #[arg(long)] |
| 18 | + pub port: Option<u16>, |
| 19 | + |
| 20 | + /// Number of recent log lines to fetch (default: 100, max: 1000). |
| 21 | + #[arg(long, short = 'n', default_value = "100")] |
| 22 | + pub lines: usize, |
| 23 | + |
| 24 | + /// Poll for new logs continuously (every 2 seconds). |
| 25 | + #[arg(long, short = 'f')] |
| 26 | + pub follow: bool, |
| 27 | +} |
| 28 | + |
| 29 | +pub async fn run(args: LogsArgs, cli_template: Option<Template>) -> Result<()> { |
| 30 | + let cfg = config::NautilusConfig::load(None).unwrap_or_default(); |
| 31 | + let template = config::resolve_template(cli_template, &cfg)?; |
| 32 | + let port = args.port.unwrap_or(template.default_http_port()); |
| 33 | + let path = template.logs_path(); |
| 34 | + let n = args.lines.min(1000); |
| 35 | + |
| 36 | + if args.follow { |
| 37 | + follow_logs(&args.host, port, path, n)?; |
| 38 | + } else { |
| 39 | + let lines = fetch_logs(&args.host, port, path, n)?; |
| 40 | + for line in &lines { |
| 41 | + println!("{}", line); |
| 42 | + } |
| 43 | + if lines.is_empty() { |
| 44 | + println!("{}", "No log lines available.".dimmed()); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + Ok(()) |
| 49 | +} |
| 50 | + |
| 51 | +/// Fetch log lines from the enclave's /logs endpoint. |
| 52 | +fn fetch_logs(host: &str, port: u16, path: &str, n: usize) -> Result<Vec<String>> { |
| 53 | + let url_path = format!("{}?lines={}", path, n); |
| 54 | + let addr = format!("{host}:{port}"); |
| 55 | + |
| 56 | + let mut stream = TcpStream::connect(&addr) |
| 57 | + .with_context(|| format!("Cannot reach enclave at {addr}"))?; |
| 58 | + |
| 59 | + stream.set_read_timeout(Some(Duration::from_secs(5)))?; |
| 60 | + |
| 61 | + let req = format!( |
| 62 | + "GET {url_path} HTTP/1.1\r\nHost: {host}:{port}\r\nConnection: close\r\n\r\n" |
| 63 | + ); |
| 64 | + stream.write_all(req.as_bytes())?; |
| 65 | + |
| 66 | + let mut response = Vec::new(); |
| 67 | + stream.read_to_end(&mut response)?; |
| 68 | + let response_str = String::from_utf8_lossy(&response); |
| 69 | + |
| 70 | + let body = response_str |
| 71 | + .split("\r\n\r\n") |
| 72 | + .nth(1) |
| 73 | + .context("Invalid HTTP response")?; |
| 74 | + |
| 75 | + let json: serde_json::Value = |
| 76 | + serde_json::from_str(body).context("Failed to parse logs JSON")?; |
| 77 | + |
| 78 | + let lines = json["lines"] |
| 79 | + .as_array() |
| 80 | + .context("Response missing 'lines' array")? |
| 81 | + .iter() |
| 82 | + .filter_map(|v| v.as_str().map(String::from)) |
| 83 | + .collect(); |
| 84 | + |
| 85 | + Ok(lines) |
| 86 | +} |
| 87 | + |
| 88 | +/// Continuously poll for new logs every 2 seconds. |
| 89 | +fn follow_logs(host: &str, port: u16, path: &str, initial_n: usize) -> Result<()> { |
| 90 | + println!( |
| 91 | + "{} Following logs from {}:{} (Ctrl+C to stop)", |
| 92 | + "→".cyan(), |
| 93 | + host, |
| 94 | + port |
| 95 | + ); |
| 96 | + |
| 97 | + let mut last_count = 0; |
| 98 | + |
| 99 | + // First fetch: show initial_n lines |
| 100 | + match fetch_logs(host, port, path, initial_n) { |
| 101 | + Ok(lines) => { |
| 102 | + for line in &lines { |
| 103 | + println!("{}", line); |
| 104 | + } |
| 105 | + last_count = lines.len(); |
| 106 | + } |
| 107 | + Err(e) => { |
| 108 | + eprintln!("{} {}", "✗".red(), e); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + loop { |
| 113 | + std::thread::sleep(Duration::from_secs(2)); |
| 114 | + |
| 115 | + match fetch_logs(host, port, path, 1000) { |
| 116 | + Ok(lines) => { |
| 117 | + // Print only new lines (lines beyond what we last saw) |
| 118 | + if lines.len() > last_count { |
| 119 | + for line in &lines[last_count..] { |
| 120 | + println!("{}", line); |
| 121 | + } |
| 122 | + } |
| 123 | + last_count = lines.len(); |
| 124 | + } |
| 125 | + Err(_) => { |
| 126 | + // Silently retry on connection errors in follow mode |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | +} |
0 commit comments