opencode-cloud 25.1.3

CLI for managing opencode as a persistent cloud service
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
//! Logs command implementation
//!
//! Streams container logs with optional filtering, timestamps, and follow mode.

use crate::output::{format_docker_error_anyhow, log_level_style};
use anyhow::{Result, anyhow};
use clap::Args;
use console::style;
use futures_util::StreamExt;
use opencode_cloud_core::bollard::container::LogOutput;
use opencode_cloud_core::bollard::exec::{CreateExecOptions, StartExecOptions, StartExecResults};
use opencode_cloud_core::bollard::query_parameters::LogsOptions;
use opencode_cloud_core::docker::{
    DockerClient, active_resource_names, container_is_running, exec_command_exit_code,
};

/// Arguments for the logs command
#[derive(Args)]
pub struct LogsArgs {
    /// Number of lines to show (default: 50)
    #[arg(short = 'n', long = "lines", default_value = "50")]
    pub lines: String,

    /// Don't follow (one-shot dump)
    #[arg(long = "no-follow")]
    pub no_follow: bool,

    /// Prefix with timestamps
    #[arg(long)]
    pub timestamps: bool,

    /// Filter lines containing pattern
    #[arg(long)]
    pub grep: Option<String>,

    /// Show opencode-broker logs (requires systemd/journald in container)
    #[arg(long)]
    pub broker: bool,
}

fn active_container_name() -> String {
    active_resource_names().container_name
}

/// Stream logs from the opencode container
///
/// By default, shows the last 50 lines and follows new output.
/// Use --no-follow for one-shot dump.
/// Use --grep to filter lines.
///
/// In quiet mode, outputs raw lines without status messages or colors.
pub async fn cmd_logs(args: &LogsArgs, maybe_host: Option<&str>, quiet: bool) -> Result<()> {
    let container_name = active_container_name();
    // Resolve Docker client (local or remote)
    let (client, host_name) = crate::resolve_docker_client(maybe_host).await?;

    // For logs, optionally prefix each line with host name
    // This helps identify source when tailing multiple hosts
    let line_prefix = host_name
        .as_ref()
        .map(|n| format!("[{}] ", style(n).cyan()));

    // Verify connection
    client
        .verify_connection()
        .await
        .map_err(|e| format_docker_error_anyhow(&e))?;

    // Check if container exists
    let inspect_result = client
        .inner()
        .inspect_container(&container_name, None)
        .await;

    match inspect_result {
        Err(opencode_cloud_core::bollard::errors::Error::DockerResponseServerError {
            status_code: 404,
            ..
        }) => {
            return Err(anyhow!(
                "No container found. Run '{}' first.",
                style("occ start").cyan()
            ));
        }
        Err(e) => {
            return Err(anyhow!("Failed to inspect container: {e}"));
        }
        Ok(_) => {}
    }

    // Determine follow mode
    let follow = !args.no_follow;

    if args.broker {
        // Show status message if following broker logs
        if !quiet && follow {
            eprintln!(
                "{}",
                style("Following broker logs (Ctrl+C to exit)...").dim()
            );
            eprintln!();
        }
        return stream_broker_logs(args, &client, line_prefix.as_deref(), quiet).await;
    }

    // Show status message if following container logs
    if !quiet && follow {
        eprintln!("{}", style("Following logs (Ctrl+C to exit)...").dim());
        eprintln!();
    }

    // Create log options
    let options = LogsOptions {
        stdout: true,
        stderr: true,
        follow,
        tail: args.lines.clone(),
        timestamps: args.timestamps,
        ..Default::default()
    };

    // Get log stream
    let mut stream = client.inner().logs(&container_name, Some(options));

    // Process log stream
    while let Some(result) = stream.next().await {
        match result {
            Ok(output) => {
                if let Some(line) = log_output_to_line(output) {
                    emit_log_line(&line, args, line_prefix.as_deref(), quiet);
                }
            }
            Err(_) => {
                // Stream error - check if container stopped
                if follow
                    && !container_is_running(&client, &container_name)
                        .await
                        .unwrap_or(false)
                    && !quiet
                {
                    eprintln!();
                    eprintln!("{}", style("Container stopped").dim());
                }
                break;
            }
        }
    }

    Ok(())
}

/// Stream opencode-broker logs from systemd journal inside the container
async fn stream_broker_logs(
    args: &LogsArgs,
    client: &DockerClient,
    line_prefix: Option<&str>,
    quiet: bool,
) -> Result<()> {
    if ensure_systemd_available(client).await? {
        let cmd = build_broker_journalctl_command(args)?;
        let exec_id = create_broker_exec(client, cmd).await?;
        stream_broker_exec_output(args, client, &exec_id, line_prefix, quiet).await
    } else {
        if !quiet {
            eprintln!(
                "{}",
                style("Systemd/journald not available. Falling back to container logs (filtered).")
                    .yellow()
            );
            eprintln!();
        }
        stream_broker_logs_from_container(args, client, line_prefix, quiet).await
    }
}

async fn ensure_systemd_available(client: &DockerClient) -> Result<bool> {
    let container_name = active_container_name();
    let systemd_available = exec_command_exit_code(
        client,
        &container_name,
        vec!["test", "-d", "/run/systemd/system"],
    )
    .await
    .unwrap_or(1)
        == 0;

    Ok(systemd_available)
}

fn build_broker_journalctl_command(args: &LogsArgs) -> Result<Vec<String>> {
    let mut cmd = vec![
        "journalctl".to_string(),
        "--no-pager".to_string(),
        "-u".to_string(),
        "opencode-broker".to_string(),
    ];

    if args.timestamps {
        cmd.push("-o".to_string());
        cmd.push("short-iso".to_string());
        cmd.push("--no-hostname".to_string());
    } else {
        cmd.push("-o".to_string());
        cmd.push("cat".to_string());
    }

    let lines = args.lines.trim();
    if lines.eq_ignore_ascii_case("all") {
        // no -n flag
    } else if !lines.is_empty() && lines.chars().all(|c| c.is_ascii_digit()) {
        cmd.push("-n".to_string());
        cmd.push(lines.to_string());
    } else {
        return Err(anyhow!(
            "Invalid value for --lines with --broker. Use a number or 'all'."
        ));
    }

    if !args.no_follow {
        cmd.push("-f".to_string());
    }

    Ok(cmd)
}

async fn create_broker_exec(client: &DockerClient, cmd: Vec<String>) -> Result<String> {
    let container_name = active_container_name();
    let exec_config = CreateExecOptions {
        attach_stdout: Some(true),
        attach_stderr: Some(true),
        cmd: Some(cmd),
        user: Some("root".to_string()),
        ..Default::default()
    };

    let exec = client
        .inner()
        .create_exec(&container_name, exec_config)
        .await
        .map_err(|e| anyhow!("Failed to create exec for broker logs: {e}"))?;

    Ok(exec.id)
}

async fn stream_broker_exec_output(
    args: &LogsArgs,
    client: &DockerClient,
    exec_id: &str,
    line_prefix: Option<&str>,
    quiet: bool,
) -> Result<()> {
    let container_name = active_container_name();
    let start_config = StartExecOptions {
        detach: false,
        ..Default::default()
    };

    match client
        .inner()
        .start_exec(exec_id, Some(start_config))
        .await
        .map_err(|e| anyhow!("Failed to start broker log stream: {e}"))?
    {
        StartExecResults::Attached {
            output: mut stream, ..
        } => {
            while let Some(result) = stream.next().await {
                match result {
                    Ok(output) => {
                        if let Some(line) = log_output_to_line(output) {
                            emit_log_line(&line, args, line_prefix, quiet);
                        }
                    }
                    Err(_) => {
                        if !args.no_follow
                            && !container_is_running(client, &container_name)
                                .await
                                .unwrap_or(false)
                            && !quiet
                        {
                            eprintln!();
                            eprintln!("{}", style("Container stopped").dim());
                        }
                        break;
                    }
                }
            }
        }
        StartExecResults::Detached => {
            return Err(anyhow!(
                "Exec unexpectedly detached while streaming broker logs"
            ));
        }
    }

    Ok(())
}

async fn stream_broker_logs_from_container(
    args: &LogsArgs,
    client: &DockerClient,
    line_prefix: Option<&str>,
    quiet: bool,
) -> Result<()> {
    let container_name = active_container_name();
    let follow = !args.no_follow;
    let options = LogsOptions {
        stdout: true,
        stderr: true,
        follow,
        tail: args.lines.clone(),
        timestamps: args.timestamps,
        ..Default::default()
    };

    let mut stream = client.inner().logs(&container_name, Some(options));

    while let Some(result) = stream.next().await {
        match result {
            Ok(output) => {
                if let Some(line) = log_output_to_line(output) {
                    if should_skip_broker_fallback_line(&line, args) {
                        continue;
                    }
                    emit_log_line(&line, args, line_prefix, quiet);
                }
            }
            Err(_) => {
                if follow
                    && !container_is_running(client, &container_name)
                        .await
                        .unwrap_or(false)
                    && !quiet
                {
                    eprintln!();
                    eprintln!("{}", style("Container stopped").dim());
                }
                break;
            }
        }
    }

    Ok(())
}

fn should_skip_broker_fallback_line(line: &str, args: &LogsArgs) -> bool {
    if args.grep.is_some() {
        return false;
    }

    !broker_log_matches(line)
}

fn broker_log_matches(line: &str) -> bool {
    line.contains("opencode_broker::") || line.contains("opencode-broker")
}

fn log_output_to_line(output: LogOutput) -> Option<String> {
    match output {
        LogOutput::StdOut { message } | LogOutput::StdErr { message } => {
            Some(String::from_utf8_lossy(&message).to_string())
        }
        _ => None,
    }
}

pub(crate) fn emit_log_line(line: &str, args: &LogsArgs, prefix: Option<&str>, quiet: bool) {
    if let Some(pattern) = args.grep.as_deref()
        && !line.contains(pattern)
    {
        return;
    }

    if quiet {
        print_line(line, prefix);
    } else if console::colors_enabled() {
        print_styled_line(line, prefix);
    } else {
        print_line(line, prefix);
    }
}

/// Print a log line, ensuring newline at end
fn print_line(line: &str, prefix: Option<&str>) {
    let output = match prefix {
        Some(p) => format!("{p}{line}"),
        None => line.to_string(),
    };
    if output.ends_with('\n') {
        print!("{output}");
    } else {
        println!("{output}");
    }
}

/// Print a styled log line based on log level
fn print_styled_line(line: &str, prefix: Option<&str>) {
    let styled = log_level_style(line);
    let output = match prefix {
        Some(p) => format!("{p}{styled}"),
        None => styled.to_string(),
    };
    if output.ends_with('\n') {
        print!("{output}");
    } else {
        println!("{output}");
    }
}

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

    #[test]
    fn logs_args_defaults() {
        // Test that defaults are applied correctly via clap
        // We can't easily test clap defaults here, but we can test
        // the parsing logic
        let args = LogsArgs {
            lines: "50".to_string(),
            no_follow: false,
            timestamps: false,
            grep: None,
            broker: false,
        };

        assert_eq!(args.lines, "50");
        assert!(!args.no_follow);
        assert!(!args.timestamps);
        assert!(args.grep.is_none());
    }

    #[test]
    fn print_line_adds_newline_when_missing() {
        // This is a basic test - the actual print happens to stdout
        // We just verify the logic
        let line_without_newline = "test line";
        let line_with_newline = "test line\n";

        assert!(!line_without_newline.ends_with('\n'));
        assert!(line_with_newline.ends_with('\n'));
    }

    #[test]
    fn grep_filter_logic() {
        // Test grep filtering logic
        let pattern = "ERROR";
        let matching_line = "2024-01-01 ERROR: something failed";
        let non_matching_line = "2024-01-01 INFO: all good";

        assert!(matching_line.contains(pattern));
        assert!(!non_matching_line.contains(pattern));
    }

    #[test]
    fn follow_mode_from_no_follow_flag() {
        // follow = !args.no_follow
        let args_follow = LogsArgs {
            lines: "50".to_string(),
            no_follow: false,
            timestamps: false,
            grep: None,
            broker: false,
        };
        assert!(!args_follow.no_follow);

        let args_no_follow = LogsArgs {
            lines: "50".to_string(),
            no_follow: true,
            timestamps: false,
            grep: None,
            broker: false,
        };
        assert!(args_no_follow.no_follow);
    }
}