zilliz 1.2.0

TUI and CLI tool for managing Zilliz Cloud clusters and Milvus operations
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
pub mod api;
pub mod cli;
pub mod config;
pub mod model;
pub mod service;
pub mod tui;

use anyhow::{bail, Result};
use clap::Parser;

use crate::cli::args::{Cli, Commands};
use crate::config::manager::ConfigManager;
use crate::model::loader::ModelLoader;

pub fn main_impl() {
    // Extract output format early so we can use it in error display
    let output_format = std::env::args()
        .collect::<Vec<_>>()
        .windows(2)
        .find_map(|w| {
            if w[0] == "-o" || w[0] == "--output" {
                Some(w[1].clone())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "table".to_string());

    let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
    if let Err(e) = rt.block_on(async_main()) {
        // Walk the error chain to find ApiError (may be wrapped by .context())
        let api_err = e
            .chain()
            .find_map(|cause| cause.downcast_ref::<api::error::ApiError>());
        let msg = if let Some(api_err) = api_err {
            match api_err {
                api::error::ApiError::Api { code, message } => {
                    cli::formatter::format_error(&output_format, *code, message)
                }
                other => cli::formatter::format_error_simple(&output_format, &format!("{}", other)),
            }
        } else {
            cli::formatter::format_error_simple(&output_format, &format!("{:#}", e))
        };
        eprintln!("{}", msg);
        std::process::exit(1);
    }
}

async fn async_main() -> Result<()> {
    let cli_args = Cli::parse();

    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env().add_directive("zilliz=info".parse()?),
        )
        .with_writer(std::io::stderr)
        .init();

    let config_mgr = ConfigManager::new(None)?;
    let models = ModelLoader::load_builtin()?;

    // Custom grouped help: intercept --help
    if cli_args.help {
        match &cli_args.command {
            None => {
                // Top-level: show custom grouped help
                print!("{}", cli::help::render_help(&models));
            }
            Some(Commands::External(args)) => {
                // Resource/operation help from JSON models
                let resource_name = args.first().map(|s| s.as_str()).unwrap_or("");
                let op_name = args.get(1).map(|s| s.as_str());

                if let Some(resource) = cli::help::find_resource(&models, resource_name) {
                    match op_name {
                        Some(op) if resource.operations.contains_key(op) => {
                            print!(
                                "{}",
                                cli::help::render_operation_help(
                                    resource_name,
                                    op,
                                    &resource.operations[op]
                                )
                            );
                        }
                        Some(op) => {
                            let ops: Vec<_> =
                                resource.operations.keys().map(|s| s.as_str()).collect();
                            bail!(
                                "Unknown operation '{}' for resource '{}'. Available operations: {}",
                                op, resource_name, ops.join(", ")
                            );
                        }
                        None => {
                            print!(
                                "{}",
                                cli::help::render_resource_help(resource_name, resource)
                            );
                        }
                    }
                } else if let Some(help) =
                    cli::help::render_hand_written_resource_help(resource_name)
                {
                    // Hand-written resource (e.g. alert): show resource or op help
                    match op_name {
                        Some(op) if cli::help::is_hand_written_op(resource_name, op) => {
                            if let Some(desc) =
                                cli::help::hand_written_op_description(resource_name, op)
                            {
                                println!(
                                    "{}\n\nUsage: zilliz {} {} [OPTIONS]",
                                    desc, resource_name, op
                                );
                            }
                        }
                        Some(op) => {
                            bail!(
                                "Unknown operation '{}' for resource '{}'.",
                                op,
                                resource_name
                            );
                        }
                        None => {
                            print!("{}", help);
                        }
                    }
                } else {
                    let names = cli::help::available_resources(&models);
                    bail!(
                        "Unknown resource '{}'. Available resources: {}",
                        resource_name,
                        names.join(", ")
                    );
                }
            }
            Some(cmd) => {
                // Clap-native subcommand: delegate to clap's built-in help
                cli::help::print_subcommand_help(cli::help::subcommand_name(cmd))?;
            }
        }
        return Ok(());
    }

    let output_format = cli_args.output.as_deref().unwrap_or("table");
    let output_opts = cli::dispatch::OutputOpts {
        format: output_format,
        query: cli_args.query.as_deref(),
        no_header: cli_args.no_header,
        wait: false,
        api_key: None,
    };

    match cli_args.command {
        None => {
            tui::run(models, config_mgr).await?;
        }
        Some(Commands::Configure { subcmd }) => {
            cli::configure::run(&config_mgr, subcmd).await?;
        }
        Some(Commands::Context {
            subcmd: Some(ctx_cmd),
        }) => {
            cli::context::run(
                &models,
                &config_mgr,
                ctx_cmd,
                output_format,
                output_opts.api_key,
            )
            .await?;
        }
        Some(Commands::Context { subcmd: None }) => {
            cli::help::print_subcommand_help("context")?;
        }
        Some(Commands::Version) => {
            cli::version::run(output_format);
        }
        Some(Commands::Login {
            no_browser,
            api_key,
        }) => {
            let auth_config = models
                .control_plane
                .auth
                .as_ref()
                .expect("Auth config not found in control-plane.json");
            cli::auth::login(&config_mgr, auth_config, no_browser, api_key.as_deref()).await?;
        }
        Some(Commands::Logout) => {
            cli::auth::logout(&config_mgr)?;
        }
        Some(Commands::Auth {
            subcmd: Some(auth_cmd),
        }) => {
            cli::auth_cmd::run(&config_mgr, auth_cmd)?;
        }
        Some(Commands::Auth { subcmd: None }) => {
            cli::help::print_subcommand_help("auth")?;
        }
        Some(Commands::Completion {
            subcmd: Some(comp_cmd),
        }) => {
            cli::completion::run(comp_cmd)?;
        }
        Some(Commands::Completion { subcmd: None }) => {
            cli::help::print_subcommand_help("completion")?;
        }
        Some(Commands::External(args)) => {
            // Clap doesn't extract global flags from external subcommands, so we
            // must strip them manually before dispatching.
            let wants_help = args.iter().any(|a| a == "-h" || a == "--help");

            // Global flags that take a value (--flag value)
            const GLOBAL_VALUE_FLAGS: &[&str] = &["-o", "--output", "--query", "--api-key"];
            // Global flags that are boolean (--flag, no value)
            const GLOBAL_BOOL_FLAGS: &[&str] = &["-h", "--help", "--no-header"];
            // Flags only applicable to external subcommands (not global)
            const EXT_BOOL_FLAGS: &[&str] = &["-a", "--all", "--wait"];

            let mut filtered_args: Vec<&str> = Vec::new();
            let mut ext_output: Option<&str> = None;
            let mut ext_query: Option<&str> = None;
            let mut ext_api_key: Option<&str> = None;
            let mut ext_all = false;
            let mut ext_no_header = false;
            let mut ext_wait = false;
            {
                let str_args: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
                let mut i = 0;
                while i < str_args.len() {
                    if GLOBAL_BOOL_FLAGS.contains(&str_args[i])
                        || EXT_BOOL_FLAGS.contains(&str_args[i])
                    {
                        match str_args[i] {
                            "-a" | "--all" => ext_all = true,
                            "--no-header" => ext_no_header = true,
                            "--wait" => ext_wait = true,
                            _ => {}
                        }
                        i += 1;
                    } else if GLOBAL_VALUE_FLAGS.contains(&str_args[i]) {
                        if let Some(&val) = str_args.get(i + 1).filter(|v| !v.starts_with('-')) {
                            match str_args[i] {
                                "-o" | "--output" => ext_output = Some(val),
                                "--query" => ext_query = Some(val),
                                "--api-key" => ext_api_key = Some(val),
                                _ => {}
                            }
                            i += 2;
                        } else {
                            i += 1;
                        }
                    } else {
                        filtered_args.push(str_args[i]);
                        i += 1;
                    }
                }
            }

            // Override output opts with any global flags found in external args
            let ext_format_owned = ext_output.map(|s| s.to_string());
            let ext_query_owned = ext_query.map(|s| s.to_string());
            let ext_api_key_owned = ext_api_key.map(|s| s.to_string());
            let output_opts = cli::dispatch::OutputOpts {
                format: ext_format_owned.as_deref().unwrap_or(output_opts.format),
                query: ext_query_owned.as_deref().or(output_opts.query),
                no_header: output_opts.no_header || ext_no_header,
                wait: output_opts.wait || ext_wait,
                api_key: ext_api_key_owned.as_deref().or(output_opts.api_key),
            };
            let fetch_all = ext_all;

            if wants_help {
                let resource_name = filtered_args.first().copied().unwrap_or("");
                let op_name = filtered_args.get(1).copied();
                if let Some(resource) = cli::help::find_resource(&models, resource_name) {
                    match op_name {
                        Some(op) if resource.operations.contains_key(op) => {
                            print!(
                                "{}",
                                cli::help::render_operation_help(
                                    resource_name,
                                    op,
                                    &resource.operations[op]
                                )
                            );
                        }
                        Some(op) if cli::help::is_hand_written_op(resource_name, op) => {
                            // Hand-written command: dispatch with --help in args
                            let help_args = vec!["--help".to_string()];
                            match (resource_name, op) {
                                ("backup", "create") => {
                                    cli::backup::create(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("cluster", "create") => {
                                    cli::cluster::create(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("cluster", "metrics") => {
                                    cli::metrics::run_from_args(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("collection", "metrics") => {
                                    cli::metrics::run_from_args_for_collection(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("billing", "usage") => {
                                    cli::billing::usage(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("billing", "invoices") => {
                                    cli::billing::invoices(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                ("billing", "download-invoice") => {
                                    cli::billing::download_invoice(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                _ => {
                                    // Fallback: show minimal help from description
                                    if let Some(desc) =
                                        cli::help::hand_written_op_description(resource_name, op)
                                    {
                                        println!(
                                            "{}\n\nUsage: zilliz {} {} [OPTIONS]",
                                            desc, resource_name, op
                                        );
                                    }
                                }
                            }
                        }
                        Some(op) => {
                            let mut ops: Vec<_> =
                                resource.operations.keys().map(|s| s.as_str()).collect();
                            // Include hand-written ops in the error's available list
                            for &(res, hw_op, _) in cli::help::hand_written_ops() {
                                if res == resource_name && !ops.contains(&hw_op) {
                                    ops.push(hw_op);
                                }
                            }
                            bail!(
                                "Unknown operation '{}' for resource '{}'. Available operations: {}",
                                op, resource_name, ops.join(", ")
                            );
                        }
                        None => {
                            print!(
                                "{}",
                                cli::help::render_resource_help(resource_name, resource)
                            );
                        }
                    }
                } else if cli::help::is_hand_written_resource(resource_name) {
                    match op_name {
                        Some(op) if cli::help::is_hand_written_op(resource_name, op) => {
                            let help_args = vec![op.to_string(), "--help".to_string()];
                            match resource_name {
                                "alert" => {
                                    cli::alert::run_from_args(
                                        &models,
                                        &config_mgr,
                                        &help_args,
                                        &output_opts,
                                    )
                                    .await?;
                                }
                                _ => {
                                    if let Some(desc) =
                                        cli::help::hand_written_op_description(resource_name, op)
                                    {
                                        println!(
                                            "{}\n\nUsage: zilliz {} {} [OPTIONS]",
                                            desc, resource_name, op
                                        );
                                    }
                                }
                            }
                        }
                        Some(op) => {
                            bail!(
                                "Unknown operation '{}' for resource '{}'. Available: list, create, update, delete, enable, disable",
                                op, resource_name
                            );
                        }
                        None => {
                            if let Some(help) =
                                cli::help::render_hand_written_resource_help(resource_name)
                            {
                                print!("{}", help);
                            }
                        }
                    }
                } else {
                    let names = cli::help::available_resources(&models);
                    bail!(
                        "Unknown resource '{}'. Available resources: {}",
                        resource_name,
                        names.join(", ")
                    );
                }
                return Ok(());
            }

            let resource = filtered_args.first().copied().unwrap_or("");
            let operation = filtered_args.get(1).copied().unwrap_or("");
            let rest: Vec<String> = if filtered_args.len() > 2 {
                filtered_args[2..].iter().map(|s| s.to_string()).collect()
            } else {
                vec![]
            };

            // No operation given: show resource help
            if operation.is_empty() {
                if let Some(res) = cli::help::find_resource(&models, resource) {
                    print!("{}", cli::help::render_resource_help(resource, res));
                } else if let Some(help) = cli::help::render_hand_written_resource_help(resource) {
                    print!("{}", help);
                } else {
                    let names = cli::help::available_resources(&models);
                    bail!(
                        "Unknown resource '{}'. Available resources: {}",
                        resource,
                        names.join(", ")
                    );
                }
                return Ok(());
            }

            // Intercept hand-written commands before model dispatch
            match (resource, operation) {
                ("alert", op) => {
                    let mut alert_args = vec![op.to_string()];
                    alert_args.extend(rest);
                    cli::alert::run_from_args(&models, &config_mgr, &alert_args, &output_opts).await?;
                }
                ("backup", "create") => {
                    cli::backup::create(&models, &config_mgr, &rest, &output_opts).await?;
                }
                ("cluster", "create") => {
                    cli::cluster::create(&models, &config_mgr, &rest, &output_opts).await?;
                }
                ("cluster", "metrics") => {
                    cli::metrics::run_from_args(&models, &config_mgr, &rest, &output_opts).await?;
                }
                ("collection", "metrics") => {
                    cli::metrics::run_from_args_for_collection(&models, &config_mgr, &rest, &output_opts)
                        .await?;
                }
                ("billing", "usage") => {
                    cli::billing::usage(&models, &config_mgr, &rest, &output_opts).await?;
                }
                ("billing", "invoices") => {
                    cli::billing::invoices(&models, &config_mgr, &rest, &output_opts).await?;
                }
                ("billing", "download-invoice") => {
                    cli::billing::download_invoice(&models, &config_mgr, &rest, &output_opts).await?;
                }
                _ => {
                    cli::dispatch::run(
                        &models,
                        &config_mgr,
                        resource,
                        operation,
                        &rest,
                        &output_opts,
                        fetch_all,
                    )
                    .await?;
                }
            }
        }
    }

    Ok(())
}