Skip to main content

common_meta/ddl/
alter_logical_tables.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 executor;
16mod update_metadata;
17mod validator;
18
19use api::region::RegionResponse;
20use async_trait::async_trait;
21use common_catalog::format_full_table_name;
22use common_procedure::error::{FromJsonSnafu, Result as ProcedureResult, ToJsonSnafu};
23use common_procedure::{Context, EventContext, EventTrigger, LockKey, Procedure, Status};
24use common_telemetry::{debug, error, info, warn};
25pub use executor::make_alter_region_request;
26use serde::{Deserialize, Serialize};
27use snafu::ResultExt;
28use store_api::metadata::ColumnMetadata;
29use store_api::metric_engine_consts::ALTER_PHYSICAL_EXTENSION_KEY;
30use strum::AsRefStr;
31use table::metadata::TableId;
32
33use crate::cache_invalidator::Context as CacheContext;
34use crate::ddl::DdlContext;
35use crate::ddl::alter_logical_tables::executor::AlterLogicalTablesExecutor;
36use crate::ddl::alter_logical_tables::validator::{
37    AlterLogicalTableValidator, ValidatorResult, retain_unskipped,
38};
39use crate::ddl::event::table::{
40    TableDdlEvent, TableDdlEventType, TableDdlLocator, alter_table_kind_name,
41};
42use crate::ddl::utils::{extract_column_metadatas, map_to_procedure_error, sync_follower_regions};
43use crate::error::Result;
44use crate::instruction::CacheIdent;
45use crate::key::DeserializedValueWithBytes;
46use crate::key::table_info::TableInfoValue;
47use crate::key::table_route::PhysicalTableRouteValue;
48use crate::lock_key::{CatalogLock, SchemaLock, TableLock};
49use crate::metrics;
50use crate::rpc::ddl::AlterTableTask;
51use crate::rpc::router::RegionRoute;
52
53pub struct AlterLogicalTablesProcedure {
54    pub context: DdlContext,
55    pub data: AlterTablesData,
56    /// Physical table route cache.
57    pub physical_table_route: Option<PhysicalTableRouteValue>,
58}
59
60/// Builds the validator from the [`AlterTablesData`].
61fn build_validator_from_alter_table_data<'a>(
62    data: &'a AlterTablesData,
63) -> AlterLogicalTableValidator<'a> {
64    let physical_table_id = data.physical_table_id;
65    let alters = data
66        .tasks
67        .iter()
68        .map(|task| &task.alter_table)
69        .collect::<Vec<_>>();
70    AlterLogicalTableValidator::new(physical_table_id, alters, &data.logical_table_ids)
71}
72
73/// Builds the executor from the [`AlterTablesData`].
74fn build_executor_from_alter_expr<'a>(data: &'a AlterTablesData) -> AlterLogicalTablesExecutor<'a> {
75    debug_assert_eq!(data.tasks.len(), data.table_info_values.len());
76    let alters = data
77        .tasks
78        .iter()
79        .zip(data.table_info_values.iter())
80        .map(|(task, table_info)| (table_info.table_info.ident.table_id, &task.alter_table))
81        .collect::<Vec<_>>();
82    AlterLogicalTablesExecutor::new(alters)
83}
84
85impl AlterLogicalTablesProcedure {
86    pub const TYPE_NAME: &'static str = "metasrv-procedure::AlterLogicalTables";
87
88    pub fn new(
89        tasks: Vec<AlterTableTask>,
90        physical_table_id: TableId,
91        logical_table_ids: Vec<TableId>,
92        context: DdlContext,
93    ) -> Self {
94        Self {
95            context,
96            data: AlterTablesData {
97                state: AlterTablesState::Prepare,
98                tasks,
99                table_info_values: vec![],
100                physical_table_id,
101                logical_table_ids,
102                physical_table_info: None,
103                physical_columns: vec![],
104                table_cache_keys_to_invalidate: vec![],
105            },
106            physical_table_route: None,
107        }
108    }
109
110    pub fn from_json(json: &str, context: DdlContext) -> ProcedureResult<Self> {
111        let data = serde_json::from_str(json).context(FromJsonSnafu)?;
112        Ok(Self {
113            context,
114            data,
115            physical_table_route: None,
116        })
117    }
118
119    pub(crate) async fn on_prepare(&mut self) -> Result<Status> {
120        let validator = build_validator_from_alter_table_data(&self.data);
121        let ValidatorResult {
122            num_skipped,
123            skip_alter,
124            table_info_values,
125            physical_table_info,
126            physical_table_route,
127        } = validator
128            .validate(&self.context.table_metadata_manager)
129            .await?;
130
131        let num_tasks = self.data.tasks.len();
132        if num_skipped == num_tasks {
133            info!("All the alter tasks are finished, will skip the procedure.");
134            let cache_ident_keys = AlterLogicalTablesExecutor::build_cache_ident_keys(
135                &physical_table_info,
136                &table_info_values
137                    .iter()
138                    .map(|v| v.get_inner_ref())
139                    .collect::<Vec<_>>(),
140            );
141            self.data.table_cache_keys_to_invalidate = cache_ident_keys;
142            // Re-invalidate the table cache
143            self.data.state = AlterTablesState::InvalidateTableCache;
144            return Ok(Status::executing(true));
145        } else if num_skipped > 0 {
146            info!(
147                "There are {} alter tasks, {} of them were already finished.",
148                num_tasks, num_skipped
149            );
150        }
151
152        // Updates the procedure state.
153        retain_unskipped(&mut self.data.tasks, &skip_alter);
154        self.data.physical_table_info = Some(physical_table_info);
155        self.data.table_info_values = table_info_values;
156        debug_assert_eq!(self.data.tasks.len(), self.data.table_info_values.len());
157        self.physical_table_route = Some(physical_table_route);
158        self.data.state = AlterTablesState::SubmitAlterRegionRequests;
159        Ok(Status::executing(true))
160    }
161
162    pub(crate) async fn on_submit_alter_region_requests(&mut self) -> Result<Status> {
163        self.fetch_physical_table_route_if_non_exist().await?;
164        // Safety: fetched in `fetch_physical_table_route_if_non_exist`.
165        let region_routes = &self.physical_table_route.as_ref().unwrap().region_routes;
166
167        let executor = build_executor_from_alter_expr(&self.data);
168        let mut results = executor
169            .on_alter_regions(
170                &self.context.node_manager,
171                // Avoid double-borrowing self by extracting the region_routes first
172                region_routes,
173            )
174            .await?;
175
176        if let Some(column_metadatas) =
177            extract_column_metadatas(&mut results, ALTER_PHYSICAL_EXTENSION_KEY)?
178        {
179            self.data.physical_columns = column_metadatas;
180        } else {
181            warn!(
182                "altering logical table result doesn't contains extension key `{ALTER_PHYSICAL_EXTENSION_KEY}`,leaving the physical table's schema unchanged"
183            );
184        }
185        self.submit_sync_region_requests(results, region_routes)
186            .await;
187        self.data.state = AlterTablesState::UpdateMetadata;
188        Ok(Status::executing(true))
189    }
190
191    async fn submit_sync_region_requests(
192        &self,
193        results: Vec<RegionResponse>,
194        region_routes: &[RegionRoute],
195    ) {
196        let table_info = &self.data.physical_table_info.as_ref().unwrap().table_info;
197        if let Err(err) = sync_follower_regions(
198            &self.context,
199            self.data.physical_table_id,
200            &results,
201            region_routes,
202            table_info.meta.engine.as_str(),
203        )
204        .await
205        {
206            error!(err; "Failed to sync regions for table {}, table_id: {}",
207                        format_full_table_name(&table_info.catalog_name, &table_info.schema_name, &table_info.name),
208                        self.data.physical_table_id
209            );
210        }
211    }
212
213    pub(crate) async fn on_update_metadata(&mut self) -> Result<Status> {
214        self.update_physical_table_metadata().await?;
215        self.update_logical_tables_metadata().await?;
216
217        let logical_table_info_values = self
218            .data
219            .table_info_values
220            .iter()
221            .map(|v| v.get_inner_ref())
222            .collect::<Vec<_>>();
223
224        let cache_ident_keys = AlterLogicalTablesExecutor::build_cache_ident_keys(
225            self.data.physical_table_info.as_ref().unwrap(),
226            &logical_table_info_values,
227        );
228        self.data.table_cache_keys_to_invalidate = cache_ident_keys;
229        self.data.clear_metadata_fields();
230
231        self.data.state = AlterTablesState::InvalidateTableCache;
232        Ok(Status::executing(true))
233    }
234
235    pub(crate) async fn on_invalidate_table_cache(&mut self) -> Result<Status> {
236        let to_invalidate = &self.data.table_cache_keys_to_invalidate;
237
238        let ctx = CacheContext {
239            subject: Some(format!(
240                "Invalidate table cache by altering logical tables, physical_table_id: {}",
241                self.data.physical_table_id,
242            )),
243        };
244
245        self.context
246            .cache_invalidator
247            .invalidate(&ctx, to_invalidate)
248            .await?;
249        Ok(Status::done())
250    }
251
252    /// Fetches the physical table route if it is not already fetched.
253    async fn fetch_physical_table_route_if_non_exist(&mut self) -> Result<()> {
254        if self.physical_table_route.is_none() {
255            let (_, physical_table_route) = self
256                .context
257                .table_metadata_manager
258                .table_route_manager()
259                .get_physical_table_route(self.data.physical_table_id)
260                .await?;
261            self.physical_table_route = Some(physical_table_route);
262        }
263
264        Ok(())
265    }
266}
267
268#[async_trait]
269impl Procedure for AlterLogicalTablesProcedure {
270    fn type_name(&self) -> &str {
271        Self::TYPE_NAME
272    }
273
274    async fn execute(&mut self, _ctx: &Context) -> ProcedureResult<Status> {
275        let state = &self.data.state;
276
277        let step = state.as_ref();
278
279        let _timer = metrics::METRIC_META_PROCEDURE_ALTER_TABLE
280            .with_label_values(&[step])
281            .start_timer();
282        debug!(
283            "Executing alter logical tables procedure, state: {:?}",
284            state
285        );
286
287        match state {
288            AlterTablesState::Prepare => self.on_prepare().await,
289            AlterTablesState::SubmitAlterRegionRequests => {
290                self.on_submit_alter_region_requests().await
291            }
292            AlterTablesState::UpdateMetadata => self.on_update_metadata().await,
293            AlterTablesState::InvalidateTableCache => self.on_invalidate_table_cache().await,
294        }
295        .inspect_err(|_| {
296            // Reset the physical table route cache.
297            self.physical_table_route = None;
298        })
299        .map_err(map_to_procedure_error)
300    }
301
302    fn dump(&self) -> ProcedureResult<String> {
303        serde_json::to_string(&self.data).context(ToJsonSnafu)
304    }
305
306    fn lock_key(&self) -> LockKey {
307        // CatalogLock, SchemaLock,
308        // TableLock
309        // TableNameLock(s)
310        let mut lock_key = Vec::with_capacity(2 + 1 + self.data.logical_table_ids.len());
311        let table_ref = self.data.tasks[0].table_ref();
312        lock_key.push(CatalogLock::Read(table_ref.catalog).into());
313        lock_key.push(SchemaLock::read(table_ref.catalog, table_ref.schema).into());
314        lock_key.push(TableLock::Write(self.data.physical_table_id).into());
315        if self.data.logical_table_ids.is_empty() {
316            // Pre-upgrade procedure state has no `logical_table_ids`, but a
317            // dump taken after `Prepare` still carries the resolved table
318            // snapshots — recover the logical locks from them.
319            lock_key.extend(
320                self.data
321                    .table_info_values
322                    .iter()
323                    .map(|table| TableLock::Write(table.table_info.ident.table_id).into()),
324            );
325        } else {
326            lock_key.extend(
327                self.data
328                    .logical_table_ids
329                    .iter()
330                    .map(|table_id| TableLock::Write(*table_id).into()),
331            );
332        }
333
334        LockKey::new(lock_key)
335    }
336
337    fn event(&self, ctx: &EventContext<'_>) -> Option<Box<dyn common_event_recorder::Event>> {
338        if !ctx
339            .event_type_filter
340            .allows(TableDdlEventType::AlterLogicalTables.as_str())
341        {
342            return None;
343        }
344        if ctx.trigger != EventTrigger::Submitted {
345            return Some(Box::new(TableDdlEvent::lifecycle(
346                TableDdlEventType::AlterLogicalTables,
347                self.data.tasks.iter().map(|task| {
348                    let table_ref = task.table_ref();
349                    TableDdlLocator::new(table_ref.catalog, table_ref.schema, table_ref.table)
350                        .with_physical_table_id(self.data.physical_table_id)
351                }),
352            )));
353        }
354
355        let locators = self.data.tasks.iter().map(|task| {
356            let table_ref = task.table_ref();
357            TableDdlLocator::new(table_ref.catalog, table_ref.schema, table_ref.table)
358                .with_physical_table_id(self.data.physical_table_id)
359        });
360        let kinds = self
361            .data
362            .tasks
363            .iter()
364            .filter_map(|task| task.alter_table.kind.as_ref())
365            .filter_map(alter_table_kind_name);
366        Some(Box::new(TableDdlEvent::alter_logical_tables_submitted(
367            locators,
368            self.data.tasks.len(),
369            kinds,
370        )))
371    }
372}
373
374#[derive(Debug, Serialize, Deserialize)]
375pub struct AlterTablesData {
376    state: AlterTablesState,
377    tasks: Vec<AlterTableTask>,
378    /// Table info values before the alter operation.
379    /// Corresponding one-to-one with the AlterTableTask in tasks.
380    table_info_values: Vec<DeserializedValueWithBytes<TableInfoValue>>,
381    /// Physical table info
382    physical_table_id: TableId,
383    /// Logical table ids resolved at submission time, so `lock_key` can name
384    /// them before `Prepare` runs (procedure locks are fixed at submission).
385    /// Empty when restored from pre-upgrade procedure state.
386    #[serde(default)]
387    logical_table_ids: Vec<TableId>,
388    physical_table_info: Option<DeserializedValueWithBytes<TableInfoValue>>,
389    physical_columns: Vec<ColumnMetadata>,
390    table_cache_keys_to_invalidate: Vec<CacheIdent>,
391}
392
393impl AlterTablesData {
394    /// Clears metadata snapshots after the update metadata step.
395    ///
396    /// Keep the tasks and physical table ID until the procedure finishes: lifecycle
397    /// events use them to retain the logical table locator.
398    fn clear_metadata_fields(&mut self) {
399        self.table_info_values.clear();
400        self.physical_table_info = None;
401        self.physical_columns.clear();
402    }
403}
404
405#[derive(Debug, Serialize, Deserialize, AsRefStr)]
406enum AlterTablesState {
407    /// Prepares to alter the table
408    Prepare,
409    SubmitAlterRegionRequests,
410    /// Updates table metadata.
411    UpdateMetadata,
412    /// Broadcasts the invalidating table cache instruction.
413    InvalidateTableCache,
414}