volli 0.1.10

CLI frontend for volli
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
#![cfg_attr(test, allow(unused_crate_dependencies))]

use clap::{Args, CommandFactory, Parser, Subcommand};
use tracing_subscriber::EnvFilter;

mod commands;
mod namegen;

struct FilterWriter<W: std::io::Write> {
    inner: W,
    buf: Vec<u8>,
}

impl<W: std::io::Write> FilterWriter<W> {
    fn new(inner: W) -> Self {
        Self {
            inner,
            buf: Vec::new(),
        }
    }
}

impl<W: std::io::Write> std::io::Write for FilterWriter<W> {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        for &b in data {
            self.buf.push(b);
            if b == b'\n' {
                if !self
                    .buf
                    .windows(b"completions".len())
                    .any(|w| w == b"completions")
                {
                    self.inner.write_all(&self.buf)?;
                }
                self.buf.clear();
            }
        }
        Ok(data.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if !self.buf.is_empty()
            && !self
                .buf
                .windows(b"completions".len())
                .any(|w| w == b"completions")
        {
            self.inner.write_all(&self.buf)?;
        }
        self.buf.clear();
        self.inner.flush()
    }
}

fn default_profile() -> String {
    commands::utils::default_profile()
}

#[derive(Parser)]
#[command(name = "volli", about = "Distributed diagnostics CLI", version)]
struct Cli {
    /// Configuration profile name
    #[arg(long, global = true, default_value_t = default_profile(), value_hint = clap::ValueHint::Other)]
    profile: String,
    /// Increase verbosity (-v, -vv)
    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
    verbose: u8,
    /// Silence output
    #[arg(short, long, global = true, action = clap::ArgAction::SetTrue)]
    quiet: bool,
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Run as coordinator server
    Serve(ServeOpts),
    /// Run as cluster agent
    Agent(AgentOpts),
    /// Administrative tasks
    Admin(AdminOpts),
    /// Manage configuration profiles
    Profile(ProfileOpts),
    /// Generate shell completion script
    #[command(hide = true)]
    Completions { shell: clap_complete::Shell },
}

#[derive(Args)]
/// Options for the `admin` subcommand
struct AdminOpts {
    #[command(subcommand)]
    command: AdminCommand,
}

#[derive(Subcommand)]
enum AdminCommand {
    /// Print an agent join command
    AgentToken,
    /// Print a coordinator join command
    CoordToken,
}

#[derive(Args)]
/// Options for the `profile` subcommand
struct ProfileOpts {
    #[command(subcommand)]
    command: ProfileCommand,
}

#[derive(Args)]
/// Show profile details
struct ProfileShow {
    /// Profile name
    profile: String,
    /// Show coordinator profile only
    #[arg(long)]
    coord: bool,
    /// Show agent profile only
    #[arg(long)]
    agent: bool,
}

#[derive(Subcommand)]
enum ProfileCommand {
    /// List available profiles
    List,
    /// Show profile details
    Show(ProfileShow),
    /// Delete a profile
    Delete(ProfileDelete),
    /// Rename a profile
    Rename(ProfileRename),
    /// Update profile values
    Update(ProfileUpdate),
    /// Export a profile
    Export(ProfileExport),
    /// Import a profile
    Import(ProfileImport),
    /// Edit a profile in $EDITOR
    Edit(ProfileEdit),
}

#[derive(Args)]
/// Delete a profile
struct ProfileDelete {
    /// Profile name
    profile: String,
    /// Delete agent profile
    #[arg(long)]
    agent: bool,
    /// Delete server profile
    #[arg(long)]
    serve: bool,
}

#[derive(Args)]
/// Rename a profile
struct ProfileRename {
    /// Current profile name
    old: String,
    /// New profile name
    new: String,
    /// Rename coordinator profile
    #[arg(long)]
    coord: bool,
    /// Rename agent profile
    #[arg(long)]
    agent: bool,
}

#[derive(Args)]
/// Update profile fields
struct ProfileUpdate {
    /// Profile name
    profile: String,
    /// Add coordinator host
    #[arg(long)]
    add_join_host: Option<String>,
    /// Add coordinator from join token
    #[arg(long)]
    add_join_token: Option<String>,
    /// Remove coordinator host by index
    #[arg(long)]
    remove_join_index: Option<usize>,
    /// Join TCP port (use with --add-join-host)
    #[arg(long)]
    join_tcp_port: Option<u16>,
    /// Join QUIC port (use with --add-join-host)
    #[arg(long)]
    join_quic_port: Option<u16>,
    /// Bind host
    #[arg(long)]
    bind_host: Option<String>,
    /// TCP port
    #[arg(long)]
    tcp_port: Option<u16>,
    /// QUIC port
    #[arg(long)]
    quic_port: Option<u16>,
    /// Advertise host
    #[arg(long)]
    advertise_host: Option<String>,
    /// Agent connection whitelist (comma-separated CIDRs)
    #[arg(long)]
    agent_whitelist: Option<String>,
    /// Coordinator connection whitelist (comma-separated CIDRs)
    #[arg(long)]
    coord_whitelist: Option<String>,
    /// Agent secret
    #[arg(long)]
    agent_secret: Option<String>,
}

#[derive(Args)]
/// Export a profile
struct ProfileExport {
    /// Profile name
    profile: String,
    /// Export coordinator profile
    #[arg(long)]
    coord: bool,
    /// Export agent profile
    #[arg(long)]
    agent: bool,
    /// Write to stdout instead of file
    #[arg(long)]
    stdout: bool,
    /// Output file name
    #[arg(long)]
    output: Option<String>,
}

#[derive(Args)]
/// Import a profile
struct ProfileImport {
    /// YAML file to import
    file: String,
    /// Profile name override
    #[arg(long)]
    name: Option<String>,
    /// Overwrite existing profile
    #[arg(long)]
    force: bool,
}

#[derive(Args)]
/// Run the coordinator server
struct ProfileEdit {
    /// Profile name
    profile: String,
    /// Edit coordinator profile
    #[arg(long)]
    coord: bool,
    /// Edit agent profile
    #[arg(long)]
    agent: bool,
}

#[derive(Args)]
struct ServeOpts {
    /// Run as a daemon
    #[arg(short, long)]
    daemon: bool,
    /// Generate or overwrite coordinator credentials and exit
    #[arg(long)]
    bootstrap: bool,
    /// Skip confirmation prompts
    #[arg(long)]
    force: bool,
    /// Join existing coordinator using secret
    #[arg(long)]
    join: Option<String>,
    /// Address to bind listeners to
    #[arg(long)]
    bind: Option<String>,
    /// Hostname or IP advertised in join tokens
    #[arg(long, alias = "host")]
    advertise_host: Option<String>,
    /// Override host from join secret
    #[arg(long)]
    join_host: Option<String>,
    /// Override TCP port from join secret
    #[arg(long)]
    join_tcp_port: Option<u16>,
    /// Override QUIC port from join secret
    #[arg(long)]
    join_quic_port: Option<u16>,
    /// TCP port to listen on
    #[arg(long)]
    tcp_port: Option<u16>,
    /// QUIC port to listen on
    #[arg(long)]
    quic_port: Option<u16>,
    /// TLS certificate path
    #[arg(long)]
    cert: Option<String>,
    /// TLS private key path
    #[arg(long)]
    key: Option<String>,
    /// Directory for all profiles and secrets
    #[arg(long)]
    config_dir: Option<String>,
    /// Persist overrides back to the profile
    #[arg(long)]
    update_profile: bool,
}

#[derive(Args)]
/// Run the agent node
struct AgentOpts {
    /// Run as a daemon
    #[arg(short, long)]
    daemon: bool,
    /// Connection string host[:port]
    #[arg(default_value = "localhost")]
    connect: String,
    /// Join secret
    #[arg(long)]
    join: Option<String>,
    /// Overwrite existing profile when joining
    #[arg(long)]
    force: bool,
    /// Force protocol (tcp or quic)
    #[arg(long)]
    protocol: Option<String>,
    /// Override host from join secret
    #[arg(long)]
    join_host: Option<String>,
    /// Directory for all profiles and secrets
    #[arg(long)]
    config_dir: Option<String>,
    /// Persist overrides back to the profile
    #[arg(long)]
    update_profile: bool,
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    let level = if cli.quiet {
        "warn"
    } else {
        match cli.verbose {
            0 => {
                if cfg!(debug_assertions) {
                    "debug"
                } else {
                    "info"
                }
            }
            1 => "debug",
            _ => "trace",
        }
    };
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(level));
    tracing_subscriber::fmt().with_env_filter(filter).init();
    match cli.command {
        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            let stdout = std::io::stdout();
            let handle = stdout.lock();
            let mut writer = FilterWriter::new(handle);
            clap_complete::generate(shell, &mut cmd, "volli", &mut writer);
        }
        Commands::Serve(opts) => {
            commands::serve::run(cli.profile.clone(), opts).await;
        }
        Commands::Agent(opts) => {
            commands::agent::run(cli.profile.clone(), opts).await;
        }
        Commands::Admin(opts) => {
            commands::admin::run(cli.profile.clone(), opts).await;
        }
        Commands::Profile(opts) => {
            commands::profile::run(opts);
        }
    }
}

#[cfg(test)]

mod tests {
    use eyre::Report;
    async fn send_cmd(profile: &str, cmd: &str) -> Result<(), Report> {
        commands::utils::send_cmd(profile, cmd).await
    }

    fn cmd_socket_path(profile: &str) -> std::path::PathBuf {
        commands::utils::cmd_socket_path(profile)
    }

    fn export_path(profile: &str, output: Option<&str>) -> String {
        commands::utils::export_path(profile, output)
    }

    use super::*;
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    #[tokio::test]
    async fn send_cmd_missing_socket_errors() {
        let path = cmd_socket_path("missing");
        let _ = std::fs::remove_file(&path);
        let res = send_cmd("missing", "hi").await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn send_cmd_writes_and_reads() {
        let path = cmd_socket_path("ok");
        let _ = std::fs::remove_file(&path);
        let listener = tokio::net::UnixListener::bind(&path).unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut reader = tokio::io::BufReader::new(stream);
            let mut cmd = String::new();
            reader.read_line(&mut cmd).await.unwrap();
            assert_eq!(cmd, "ping\n");
            reader.get_mut().write_all(b"pong\n").await.unwrap();
        });
        send_cmd("ok", "ping").await.unwrap();
        server.await.unwrap();
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_path_defaults() {
        assert_eq!(export_path("p1", None), "p1.yaml");
        assert_eq!(export_path("p1", Some("out.yaml")), "out.yaml");
    }

    #[test]
    fn socket_path_contains_profile() {
        let path = cmd_socket_path("abc");
        let filename = path.file_name().unwrap().to_string_lossy();
        assert_eq!(filename, "volli-abc.sock");
    }
}