cli/metadata/
repair.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
15mod alter_table;
16mod create_table;
17
18use std::sync::Arc;
19use std::time::Duration;
20
21use async_trait::async_trait;
22use clap::Parser;
23use client::api::v1::CreateTableExpr;
24use client::client_manager::NodeClients;
25use client::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
26use common_error::ext::{BoxedError, ErrorExt};
27use common_error::status_code::StatusCode;
28use common_grpc::channel_manager::ChannelConfig;
29use common_meta::error::Error as CommonMetaError;
30use common_meta::key::TableMetadataManager;
31use common_meta::kv_backend::KvBackendRef;
32use common_meta::node_manager::NodeManagerRef;
33use common_meta::peer::Peer;
34use common_meta::rpc::router::{RegionRoute, find_leaders};
35use common_telemetry::{error, info, warn};
36use futures::TryStreamExt;
37use snafu::{ResultExt, ensure};
38use store_api::storage::TableId;
39
40use crate::Tool;
41use crate::common::StoreConfig;
42use crate::error::{
43    InvalidArgumentsSnafu, Result, SendRequestToDatanodeSnafu, TableMetadataSnafu, UnexpectedSnafu,
44};
45use crate::metadata::utils::{FullTableMetadata, IteratorInput, TableMetadataIterator};
46
47/// Repair metadata of logical tables.
48#[derive(Debug, Default, Parser)]
49pub struct RepairLogicalTablesCommand {
50    /// The names of the tables to repair.
51    #[clap(long, value_delimiter = ',', alias = "table-name")]
52    table_names: Vec<String>,
53
54    /// The id of the table to repair.
55    #[clap(long, value_delimiter = ',', alias = "table-id")]
56    table_ids: Vec<TableId>,
57
58    /// The schema of the tables to repair.
59    #[clap(long, default_value = DEFAULT_SCHEMA_NAME)]
60    schema_name: String,
61
62    /// The catalog of the tables to repair.
63    #[clap(long, default_value = DEFAULT_CATALOG_NAME)]
64    catalog_name: String,
65
66    /// Whether to fail fast if any repair operation fails.
67    #[clap(long)]
68    fail_fast: bool,
69
70    #[clap(flatten)]
71    store: StoreConfig,
72
73    /// The timeout for the client to operate the datanode.
74    #[clap(long, default_value_t = 30)]
75    client_timeout_secs: u64,
76
77    /// The timeout for the client to connect to the datanode.
78    #[clap(long, default_value_t = 3)]
79    client_connect_timeout_secs: u64,
80}
81
82impl RepairLogicalTablesCommand {
83    fn validate(&self) -> Result<()> {
84        ensure!(
85            !self.table_names.is_empty() || !self.table_ids.is_empty(),
86            InvalidArgumentsSnafu {
87                msg: "You must specify --table-names or --table-ids.",
88            }
89        );
90        Ok(())
91    }
92}
93
94impl RepairLogicalTablesCommand {
95    pub async fn build(&self) -> std::result::Result<Box<dyn Tool>, BoxedError> {
96        self.validate().map_err(BoxedError::new)?;
97        let kv_backend = self.store.build().await?;
98        let node_client_channel_config = ChannelConfig::new()
99            .timeout(Duration::from_secs(self.client_timeout_secs))
100            .connect_timeout(Duration::from_secs(self.client_connect_timeout_secs));
101        let node_manager = Arc::new(NodeClients::new(node_client_channel_config));
102
103        Ok(Box::new(RepairTool {
104            table_names: self.table_names.clone(),
105            table_ids: self.table_ids.clone(),
106            schema_name: self.schema_name.clone(),
107            catalog_name: self.catalog_name.clone(),
108            fail_fast: self.fail_fast,
109            kv_backend,
110            node_manager,
111        }))
112    }
113}
114
115struct RepairTool {
116    table_names: Vec<String>,
117    table_ids: Vec<TableId>,
118    schema_name: String,
119    catalog_name: String,
120    fail_fast: bool,
121    kv_backend: KvBackendRef,
122    node_manager: NodeManagerRef,
123}
124
125#[async_trait]
126impl Tool for RepairTool {
127    async fn do_work(&self) -> std::result::Result<(), BoxedError> {
128        self.repair_tables().await.map_err(BoxedError::new)
129    }
130}
131
132impl RepairTool {
133    fn generate_iterator_input(&self) -> Result<IteratorInput> {
134        if !self.table_names.is_empty() {
135            let table_names = &self.table_names;
136            let catalog = &self.catalog_name;
137            let schema_name = &self.schema_name;
138
139            let table_names = table_names
140                .iter()
141                .map(|table_name| (catalog.clone(), schema_name.clone(), table_name.clone()))
142                .collect::<Vec<_>>();
143            return Ok(IteratorInput::new_table_names(table_names));
144        } else if !self.table_ids.is_empty() {
145            return Ok(IteratorInput::new_table_ids(self.table_ids.clone()));
146        };
147
148        InvalidArgumentsSnafu {
149            msg: "You must specify --table-names or --table-id.",
150        }
151        .fail()
152    }
153
154    async fn repair_tables(&self) -> Result<()> {
155        let input = self.generate_iterator_input()?;
156        let mut table_metadata_iterator =
157            Box::pin(TableMetadataIterator::new(self.kv_backend.clone(), input).into_stream());
158        let table_metadata_manager = TableMetadataManager::new(self.kv_backend.clone());
159
160        let mut skipped_table = 0;
161        let mut success_table = 0;
162        while let Some(full_table_metadata) = table_metadata_iterator.try_next().await? {
163            let full_table_name = full_table_metadata.full_table_name();
164            if !full_table_metadata.is_metric_engine() {
165                warn!(
166                    "Skipping repair for non-metric engine table: {}",
167                    full_table_name
168                );
169                skipped_table += 1;
170                continue;
171            }
172
173            if full_table_metadata.is_physical_table() {
174                warn!("Skipping repair for physical table: {}", full_table_name);
175                skipped_table += 1;
176                continue;
177            }
178
179            let (physical_table_id, physical_table_route) = table_metadata_manager
180                .table_route_manager()
181                .get_physical_table_route(full_table_metadata.table_id)
182                .await
183                .context(TableMetadataSnafu)?;
184
185            if let Err(err) = self
186                .repair_table(
187                    &full_table_metadata,
188                    physical_table_id,
189                    &physical_table_route.region_routes,
190                )
191                .await
192            {
193                error!(
194                    err;
195                    "Failed to repair table: {}, skipped table: {}",
196                    full_table_name,
197                    skipped_table,
198                );
199
200                if self.fail_fast {
201                    return Err(err);
202                }
203            } else {
204                success_table += 1;
205            }
206        }
207
208        info!(
209            "Repair logical tables result: {} tables repaired, {} tables skipped",
210            success_table, skipped_table
211        );
212
213        Ok(())
214    }
215
216    async fn alter_table_on_datanodes(
217        &self,
218        full_table_metadata: &FullTableMetadata,
219        physical_region_routes: &[RegionRoute],
220    ) -> Result<Vec<(Peer, CommonMetaError)>> {
221        let logical_table_id = full_table_metadata.table_id;
222        let alter_table_expr = alter_table::generate_alter_table_expr_for_all_columns(
223            &full_table_metadata.table_info,
224        )?;
225        let node_manager = self.node_manager.clone();
226
227        let mut failed_peers = Vec::new();
228        info!(
229            "Sending alter table requests to all datanodes for table: {}, number of regions:{}.",
230            full_table_metadata.full_table_name(),
231            physical_region_routes.len()
232        );
233        let leaders = find_leaders(physical_region_routes);
234        for peer in &leaders {
235            let alter_table_request = alter_table::make_alter_region_request_for_peer(
236                logical_table_id,
237                &alter_table_expr,
238                peer,
239                physical_region_routes,
240            )?;
241            let datanode = node_manager.datanode(peer).await;
242            if let Err(err) = datanode.handle(alter_table_request).await {
243                failed_peers.push((peer.clone(), err));
244            }
245        }
246
247        Ok(failed_peers)
248    }
249
250    async fn create_table_on_datanode(
251        &self,
252        create_table_expr: &CreateTableExpr,
253        logical_table_id: TableId,
254        physical_table_id: TableId,
255        peer: &Peer,
256        physical_region_routes: &[RegionRoute],
257    ) -> Result<()> {
258        let node_manager = self.node_manager.clone();
259        let datanode = node_manager.datanode(peer).await;
260        let create_table_request = create_table::make_create_region_request_for_peer(
261            logical_table_id,
262            physical_table_id,
263            create_table_expr,
264            peer,
265            physical_region_routes,
266        )?;
267
268        datanode
269            .handle(create_table_request)
270            .await
271            .with_context(|_| SendRequestToDatanodeSnafu { peer: peer.clone() })?;
272
273        Ok(())
274    }
275
276    async fn repair_table(
277        &self,
278        full_table_metadata: &FullTableMetadata,
279        physical_table_id: TableId,
280        physical_region_routes: &[RegionRoute],
281    ) -> Result<()> {
282        let full_table_name = full_table_metadata.full_table_name();
283        // First we sends alter table requests to all datanodes with all columns.
284        let failed_peers = self
285            .alter_table_on_datanodes(full_table_metadata, physical_region_routes)
286            .await?;
287
288        if failed_peers.is_empty() {
289            info!(
290                "All alter table requests sent successfully for table: {}",
291                full_table_name
292            );
293            return Ok(());
294        }
295        warn!(
296            "Sending alter table requests to datanodes for table: {} failed for the datanodes: {:?}",
297            full_table_name,
298            failed_peers
299                .iter()
300                .map(|(peer, _)| peer.id)
301                .collect::<Vec<_>>()
302        );
303
304        let create_table_expr =
305            create_table::generate_create_table_expr(&full_table_metadata.table_info)?;
306
307        let mut errors = Vec::new();
308        for (peer, err) in failed_peers {
309            if err.status_code() != StatusCode::RegionNotFound {
310                error!(
311                    err;
312                    "Sending alter table requests to datanode: {} for table: {} failed",
313                    peer.id,
314                    full_table_name,
315                );
316                continue;
317            }
318            info!(
319                "Region not found for table: {}, datanode: {}, trying to create the logical table on that datanode",
320                full_table_name, peer.id
321            );
322
323            // If the alter table request fails for any datanode, we attempt to create the table on that datanode
324            // as a fallback mechanism to ensure table consistency across the cluster.
325            if let Err(err) = self
326                .create_table_on_datanode(
327                    &create_table_expr,
328                    full_table_metadata.table_id,
329                    physical_table_id,
330                    &peer,
331                    physical_region_routes,
332                )
333                .await
334            {
335                error!(
336                    err;
337                    "Failed to create table on datanode: {} for table: {}",
338                    peer.id, full_table_name
339                );
340                errors.push(err);
341                if self.fail_fast {
342                    break;
343                }
344            } else {
345                info!(
346                    "Created table on datanode: {} for table: {}",
347                    peer.id, full_table_name
348                );
349            }
350        }
351
352        if !errors.is_empty() {
353            return UnexpectedSnafu {
354                msg: format!(
355                    "Failed to create table on datanodes for table: {}",
356                    full_table_name,
357                ),
358            }
359            .fail();
360        }
361
362        Ok(())
363    }
364}