Skip to main content

cmd/
cli.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use clap::Parser;
16use cli::Tool;
17use common_telemetry::logging::{LoggingOptions, TracingOptions};
18use plugins::SubCommand;
19use snafu::ResultExt;
20use tracing_appender::non_blocking::WorkerGuard;
21
22use crate::options::GlobalOptions;
23use crate::{App, Result, error};
24pub const APP_NAME: &str = "greptime-cli";
25use async_trait::async_trait;
26
27pub struct Instance {
28    tool: Box<dyn Tool>,
29
30    // Keep the logging guard to prevent the worker from being dropped.
31    _guard: Vec<WorkerGuard>,
32}
33
34impl Instance {
35    pub fn new(tool: Box<dyn Tool>, guard: Vec<WorkerGuard>) -> Self {
36        Self {
37            tool,
38            _guard: guard,
39        }
40    }
41
42    pub async fn start(&mut self) -> Result<()> {
43        self.tool.do_work().await.context(error::StartCliSnafu)
44    }
45}
46
47#[async_trait]
48impl App for Instance {
49    fn name(&self) -> &str {
50        APP_NAME
51    }
52
53    async fn start(&mut self) -> Result<()> {
54        self.start().await
55    }
56
57    fn wait_signal(&self) -> bool {
58        false
59    }
60
61    async fn stop(&mut self) -> Result<()> {
62        Ok(())
63    }
64}
65
66#[derive(Parser)]
67pub struct Command {
68    #[clap(subcommand)]
69    cmd: SubCommand,
70}
71
72impl Command {
73    pub async fn build(&self, opts: LoggingOptions) -> Result<Instance> {
74        let guard = common_telemetry::init_global_logging(
75            APP_NAME,
76            &opts,
77            &TracingOptions::default(),
78            None,
79            None,
80        )
81        .context(crate::error::InitLoggingSnafu)?;
82
83        let tool = self.cmd.build().await.context(error::BuildCliSnafu)?;
84        let instance = Instance {
85            tool,
86            _guard: guard,
87        };
88        Ok(instance)
89    }
90
91    pub fn load_options(&self, global_options: &GlobalOptions) -> Result<LoggingOptions> {
92        let mut logging_opts = LoggingOptions::default();
93
94        if let Some(dir) = &global_options.log_dir {
95            logging_opts.dir.clone_from(dir);
96        }
97
98        logging_opts.level.clone_from(&global_options.log_level);
99
100        Ok(logging_opts)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use std::net::TcpListener;
107    use std::ops::RangeInclusive;
108
109    use clap::Parser;
110    use client::{Client, Database};
111    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
112    use common_grpc::channel_manager::ChannelManager;
113    use common_telemetry::logging::LoggingOptions;
114    use rand::Rng;
115
116    use crate::error::Result as CmdResult;
117    use crate::options::GlobalOptions;
118    use crate::{App, cli, standalone};
119
120    fn random_standalone_addrs() -> (String, String, String, String) {
121        let offset = choose_random_unused_port_offset(14000..=24000, 10);
122
123        (
124            format!("127.0.0.1:{}", 4000 + offset),
125            format!("127.0.0.1:{}", 4001 + offset),
126            format!("127.0.0.1:{}", 4002 + offset),
127            format!("127.0.0.1:{}", 4003 + offset),
128        )
129    }
130
131    fn choose_random_unused_port_offset(
132        port_range: RangeInclusive<u16>,
133        max_attempts: usize,
134    ) -> u16 {
135        let mut rng = rand::rng();
136
137        for _ in 0..max_attempts {
138            let http_port = rng.random_range(port_range.clone());
139            let offset = http_port - 4000;
140            let ports = [4000 + offset, 4001 + offset, 4002 + offset, 4003 + offset];
141
142            let listeners = ports
143                .into_iter()
144                .map(|port| TcpListener::bind(("127.0.0.1", port)))
145                .collect::<Result<Vec<_>, _>>();
146
147            if listeners.is_ok() {
148                return offset;
149            }
150        }
151
152        panic!("failed to find unused standalone test ports");
153    }
154
155    #[tokio::test(flavor = "multi_thread")]
156    async fn test_export_create_table_with_quoted_names() -> CmdResult<()> {
157        let output_dir = tempfile::tempdir().unwrap();
158        let (http_addr, rpc_addr, mysql_addr, postgres_addr) = random_standalone_addrs();
159
160        let standalone = standalone::Command::parse_from([
161            "standalone",
162            "start",
163            "--data-home",
164            &*output_dir.path().to_string_lossy(),
165            "--http-addr",
166            &http_addr,
167            "--grpc-bind-addr",
168            &rpc_addr,
169            "--mysql-addr",
170            &mysql_addr,
171            "--postgres-addr",
172            &postgres_addr,
173        ]);
174
175        let standalone_opts = standalone.load_options(&GlobalOptions::default()).unwrap();
176        let mut instance = standalone.build(standalone_opts).await?;
177        instance.start().await?;
178
179        let client = Client::with_query_and_control_managers(
180            ChannelManager::new(),
181            ChannelManager::new(),
182            [rpc_addr.as_str()],
183        );
184        let database = Database::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, client);
185        database
186            .sql(r#"CREATE DATABASE "cli.export.create_table";"#)
187            .await
188            .unwrap();
189        database
190            .sql(
191                r#"CREATE TABLE "cli.export.create_table"."a.b.c"(
192                        ts TIMESTAMP,
193                        TIME INDEX (ts)
194                    ) engine=mito;
195                "#,
196            )
197            .await
198            .unwrap();
199
200        let output_dir = tempfile::tempdir().unwrap();
201        let cli = cli::Command::parse_from([
202            "cli",
203            "data",
204            "export",
205            "--addr",
206            &http_addr,
207            "--output-dir",
208            &*output_dir.path().to_string_lossy(),
209            "--target",
210            "schema",
211        ]);
212        let mut cli_app = cli.build(LoggingOptions::default()).await?;
213        cli_app.start().await?;
214
215        instance.stop().await?;
216
217        let output_file = output_dir
218            .path()
219            .join("greptime")
220            .join("cli.export.create_table")
221            .join("create_tables.sql");
222        let res = std::fs::read_to_string(output_file).unwrap();
223        let expect = r#"CREATE TABLE IF NOT EXISTS "a.b.c" (
224  "ts" TIMESTAMP(3) NOT NULL,
225  TIME INDEX ("ts")
226)
227
228ENGINE=mito
229;
230"#;
231        assert_eq!(res.trim(), expect.trim());
232
233        Ok(())
234    }
235}