Skip to main content

cli/
bench.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 std::collections::{BTreeMap, HashMap};
16use std::future::Future;
17use std::sync::Arc;
18use std::time::Duration;
19
20use async_trait::async_trait;
21use clap::Parser;
22use common_error::ext::BoxedError;
23use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
24#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
25use common_meta::kv_backend::KvBackendRef;
26use common_meta::kv_backend::etcd::EtcdStore;
27use common_meta::kv_backend::memory::MemoryKvBackend;
28#[cfg(feature = "mysql_kvbackend")]
29use common_meta::kv_backend::rds::MySqlStore;
30#[cfg(feature = "pg_kvbackend")]
31use common_meta::kv_backend::rds::PgStore;
32use common_meta::peer::Peer;
33use common_meta::rpc::router::{Region, RegionRoute};
34use common_telemetry::info;
35use common_wal::options::WalOptions;
36use datatypes::data_type::ConcreteDataType;
37use datatypes::schema::{ColumnSchema, Schema};
38use rand::Rng;
39use store_api::storage::RegionNumber;
40use table::metadata::{TableId, TableIdent, TableInfo, TableMeta, TableType};
41use table::table_name::TableName;
42
43use self::metadata::TableMetadataBencher;
44use crate::Tool;
45
46mod metadata;
47
48async fn bench_self_recorded<F, Fut>(desc: &str, f: F, count: u32)
49where
50    F: Fn(u32) -> Fut,
51    Fut: Future<Output = Duration>,
52{
53    let mut total = Duration::default();
54
55    for i in 1..=count {
56        total += f(i).await;
57    }
58
59    let cost = total.as_millis() as f64 / count as f64;
60    info!("{desc}, average operation cost: {cost:.2} ms");
61}
62
63/// Command to benchmark table metadata operations.
64#[derive(Debug, Default, Parser)]
65pub struct BenchTableMetadataCommand {
66    #[clap(long)]
67    etcd_addr: Option<String>,
68    #[cfg(feature = "pg_kvbackend")]
69    #[clap(long)]
70    postgres_addr: Option<String>,
71    #[cfg(feature = "pg_kvbackend")]
72    #[clap(long)]
73    postgres_schema: Option<String>,
74    #[cfg(feature = "mysql_kvbackend")]
75    #[clap(long)]
76    mysql_addr: Option<String>,
77    #[clap(long)]
78    count: u32,
79}
80
81impl BenchTableMetadataCommand {
82    pub async fn build(&self) -> std::result::Result<Box<dyn Tool>, BoxedError> {
83        let kv_backend = if let Some(etcd_addr) = &self.etcd_addr {
84            info!("Using etcd as kv backend");
85            EtcdStore::with_endpoints([etcd_addr], 128).await.unwrap()
86        } else {
87            Arc::new(MemoryKvBackend::new())
88        };
89
90        #[cfg(feature = "pg_kvbackend")]
91        let kv_backend: KvBackendRef = if let Some(postgres_addr) = &self.postgres_addr {
92            info!("Using postgres as kv backend");
93            PgStore::with_url(postgres_addr, "greptime_metakv", 128)
94                .await
95                .unwrap()
96        } else {
97            kv_backend
98        };
99
100        #[cfg(feature = "mysql_kvbackend")]
101        let kv_backend: KvBackendRef = if let Some(mysql_addr) = &self.mysql_addr {
102            info!("Using mysql as kv backend");
103            MySqlStore::with_url(mysql_addr, "greptime_metakv", 128)
104                .await
105                .unwrap()
106        } else {
107            kv_backend
108        };
109
110        let table_metadata_manager = Arc::new(TableMetadataManager::new(kv_backend));
111
112        let tool = BenchTableMetadata {
113            table_metadata_manager,
114            count: self.count,
115        };
116        Ok(Box::new(tool))
117    }
118}
119
120struct BenchTableMetadata {
121    table_metadata_manager: TableMetadataManagerRef,
122    count: u32,
123}
124
125#[async_trait]
126impl Tool for BenchTableMetadata {
127    async fn do_work(&self) -> std::result::Result<(), BoxedError> {
128        let bencher = TableMetadataBencher::new(self.table_metadata_manager.clone(), self.count);
129        bencher.bench_create().await;
130        bencher.bench_get().await;
131        bencher.bench_rename().await;
132        bencher.bench_delete().await;
133        Ok(())
134    }
135}
136
137fn create_table_info(table_id: TableId, table_name: TableName) -> TableInfo {
138    let columns = 100;
139    let mut column_schemas = Vec::with_capacity(columns);
140    column_schemas.push(
141        ColumnSchema::new(
142            "ts",
143            ConcreteDataType::timestamp_millisecond_datatype(),
144            true,
145        )
146        .with_time_index(true),
147    );
148
149    for i in 1..columns {
150        let column_name = format!("my_column_{i}");
151        column_schemas.push(ColumnSchema::new(
152            column_name,
153            ConcreteDataType::string_datatype(),
154            true,
155        ));
156    }
157
158    let meta = TableMeta {
159        schema: Arc::new(Schema::new(column_schemas)),
160        engine: "mito".to_string(),
161        created_on: chrono::DateTime::default(),
162        updated_on: chrono::DateTime::default(),
163        primary_key_indices: vec![],
164        next_column_id: columns as u32 + 1,
165        value_indices: vec![],
166        options: Default::default(),
167        partition_key_indices: vec![],
168        column_ids: vec![],
169    };
170
171    TableInfo {
172        ident: TableIdent {
173            table_id,
174            version: 1,
175        },
176        name: table_name.table_name,
177        desc: Some("blah".to_string()),
178        catalog_name: table_name.catalog_name,
179        schema_name: table_name.schema_name,
180        meta,
181        table_type: TableType::Base,
182    }
183}
184
185fn create_region_routes(regions: Vec<RegionNumber>) -> Vec<RegionRoute> {
186    let mut region_routes = Vec::with_capacity(100);
187    let mut rng = rand::rng();
188
189    for region_id in regions.into_iter().map(u64::from) {
190        region_routes.push(RegionRoute {
191            region: Region {
192                id: region_id.into(),
193                name: String::new(),
194                attrs: BTreeMap::new(),
195                partition_expr: Default::default(),
196            },
197            leader_peer: Some(Peer {
198                id: rng.random_range(0..10),
199                addr: String::new(),
200            }),
201            follower_peers: vec![],
202            leader_state: None,
203            leader_down_since: None,
204            write_route_policy: None,
205        });
206    }
207
208    region_routes
209}
210
211fn create_region_wal_options(regions: Vec<RegionNumber>) -> HashMap<RegionNumber, WalOptions> {
212    // TODO(niebayes): construct region wal options for benchmark.
213    let _ = regions;
214    HashMap::default()
215}