common_meta/ddl/
create_table.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::HashMap;
16
17use api::v1::region::region_request::Body as PbRegionRequest;
18use api::v1::region::{RegionRequest, RegionRequestHeader};
19use async_trait::async_trait;
20use common_error::ext::BoxedError;
21use common_procedure::error::{
22    ExternalSnafu, FromJsonSnafu, Result as ProcedureResult, ToJsonSnafu,
23};
24use common_procedure::{Context as ProcedureContext, LockKey, Procedure, ProcedureId, Status};
25use common_telemetry::tracing_context::TracingContext;
26use common_telemetry::{info, warn};
27use futures::future::join_all;
28use serde::{Deserialize, Serialize};
29use snafu::{ensure, OptionExt, ResultExt};
30use store_api::metadata::ColumnMetadata;
31use store_api::metric_engine_consts::TABLE_COLUMN_METADATA_EXTENSION_KEY;
32use store_api::storage::{RegionId, RegionNumber};
33use strum::AsRefStr;
34use table::metadata::{RawTableInfo, TableId};
35use table::table_reference::TableReference;
36
37use crate::ddl::create_table_template::{build_template, CreateRequestBuilder};
38use crate::ddl::utils::raw_table_info::update_table_info_column_ids;
39use crate::ddl::utils::{
40    add_peer_context_if_needed, convert_region_routes_to_detecting_regions,
41    extract_column_metadatas, map_to_procedure_error, region_storage_path,
42};
43use crate::ddl::{DdlContext, TableMetadata};
44use crate::error::{self, Result};
45use crate::key::table_name::TableNameKey;
46use crate::key::table_route::{PhysicalTableRouteValue, TableRouteValue};
47use crate::lock_key::{CatalogLock, SchemaLock, TableNameLock};
48use crate::metrics;
49use crate::region_keeper::OperatingRegionGuard;
50use crate::rpc::ddl::CreateTableTask;
51use crate::rpc::router::{
52    find_leader_regions, find_leaders, operating_leader_regions, RegionRoute,
53};
54pub struct CreateTableProcedure {
55    pub context: DdlContext,
56    pub creator: TableCreator,
57}
58
59impl CreateTableProcedure {
60    pub const TYPE_NAME: &'static str = "metasrv-procedure::CreateTable";
61
62    pub fn new(task: CreateTableTask, context: DdlContext) -> Self {
63        Self {
64            context,
65            creator: TableCreator::new(task),
66        }
67    }
68
69    pub fn from_json(json: &str, context: DdlContext) -> ProcedureResult<Self> {
70        let data = serde_json::from_str(json).context(FromJsonSnafu)?;
71
72        Ok(CreateTableProcedure {
73            context,
74            creator: TableCreator {
75                data,
76                opening_regions: vec![],
77            },
78        })
79    }
80
81    fn table_info(&self) -> &RawTableInfo {
82        &self.creator.data.task.table_info
83    }
84
85    pub(crate) fn table_id(&self) -> TableId {
86        self.table_info().ident.table_id
87    }
88
89    fn region_wal_options(&self) -> Result<&HashMap<RegionNumber, String>> {
90        self.creator
91            .data
92            .region_wal_options
93            .as_ref()
94            .context(error::UnexpectedSnafu {
95                err_msg: "region_wal_options is not allocated",
96            })
97    }
98
99    fn table_route(&self) -> Result<&PhysicalTableRouteValue> {
100        self.creator
101            .data
102            .table_route
103            .as_ref()
104            .context(error::UnexpectedSnafu {
105                err_msg: "table_route is not allocated",
106            })
107    }
108
109    #[cfg(any(test, feature = "testing"))]
110    pub fn set_allocated_metadata(
111        &mut self,
112        table_id: TableId,
113        table_route: PhysicalTableRouteValue,
114        region_wal_options: HashMap<RegionNumber, String>,
115    ) {
116        self.creator
117            .set_allocated_metadata(table_id, table_route, region_wal_options)
118    }
119
120    /// On the prepare step, it performs:
121    /// - Checks whether the table exists.
122    /// - Allocates the table id.
123    ///
124    /// Abort(non-retry):
125    /// - TableName exists and `create_if_not_exists` is false.
126    /// - Failed to allocate [TableMetadata].
127    pub(crate) async fn on_prepare(&mut self) -> Result<Status> {
128        let expr = &self.creator.data.task.create_table;
129        let table_name_value = self
130            .context
131            .table_metadata_manager
132            .table_name_manager()
133            .get(TableNameKey::new(
134                &expr.catalog_name,
135                &expr.schema_name,
136                &expr.table_name,
137            ))
138            .await?;
139
140        if let Some(value) = table_name_value {
141            ensure!(
142                expr.create_if_not_exists,
143                error::TableAlreadyExistsSnafu {
144                    table_name: self.creator.data.table_ref().to_string(),
145                }
146            );
147
148            let table_id = value.table_id();
149            return Ok(Status::done_with_output(table_id));
150        }
151
152        self.creator.data.state = CreateTableState::DatanodeCreateRegions;
153        let TableMetadata {
154            table_id,
155            table_route,
156            region_wal_options,
157        } = self
158            .context
159            .table_metadata_allocator
160            .create(&self.creator.data.task)
161            .await?;
162        self.creator
163            .set_allocated_metadata(table_id, table_route, region_wal_options);
164
165        Ok(Status::executing(true))
166    }
167
168    pub fn new_region_request_builder(
169        &self,
170        physical_table_id: Option<TableId>,
171    ) -> Result<CreateRequestBuilder> {
172        let create_table_expr = &self.creator.data.task.create_table;
173        let template = build_template(create_table_expr)?;
174        Ok(CreateRequestBuilder::new(template, physical_table_id))
175    }
176
177    /// Creates regions on datanodes
178    ///
179    /// Abort(non-retry):
180    /// - Failed to create [CreateRequestBuilder].
181    /// - Failed to get the table route of physical table (for logical table).
182    ///
183    /// Retry:
184    /// - If the underlying servers returns one of the following [Code](tonic::status::Code):
185    ///   - [Code::Cancelled](tonic::status::Code::Cancelled)
186    ///   - [Code::DeadlineExceeded](tonic::status::Code::DeadlineExceeded)
187    ///   - [Code::Unavailable](tonic::status::Code::Unavailable)
188    pub async fn on_datanode_create_regions(&mut self) -> Result<Status> {
189        let table_route = self.table_route()?.clone();
190        let request_builder = self.new_region_request_builder(None)?;
191        // Registers opening regions
192        let guards = self
193            .creator
194            .register_opening_regions(&self.context, &table_route.region_routes)?;
195        if !guards.is_empty() {
196            self.creator.opening_regions = guards;
197        }
198        self.create_regions(&table_route.region_routes, request_builder)
199            .await
200    }
201
202    async fn create_regions(
203        &mut self,
204        region_routes: &[RegionRoute],
205        request_builder: CreateRequestBuilder,
206    ) -> Result<Status> {
207        let create_table_data = &self.creator.data;
208        // Safety: the region_wal_options must be allocated
209        let region_wal_options = self.region_wal_options()?;
210        let create_table_expr = &create_table_data.task.create_table;
211        let catalog = &create_table_expr.catalog_name;
212        let schema = &create_table_expr.schema_name;
213        let storage_path = region_storage_path(catalog, schema);
214        let leaders = find_leaders(region_routes);
215        let mut create_region_tasks = Vec::with_capacity(leaders.len());
216
217        for datanode in leaders {
218            let requester = self.context.node_manager.datanode(&datanode).await;
219
220            let regions = find_leader_regions(region_routes, &datanode);
221            let mut requests = Vec::with_capacity(regions.len());
222            for region_number in regions {
223                let region_id = RegionId::new(self.table_id(), region_number);
224                let create_region_request =
225                    request_builder.build_one(region_id, storage_path.clone(), region_wal_options);
226                requests.push(PbRegionRequest::Create(create_region_request));
227            }
228
229            for request in requests {
230                let request = RegionRequest {
231                    header: Some(RegionRequestHeader {
232                        tracing_context: TracingContext::from_current_span().to_w3c(),
233                        ..Default::default()
234                    }),
235                    body: Some(request),
236                };
237
238                let datanode = datanode.clone();
239                let requester = requester.clone();
240                create_region_tasks.push(async move {
241                    requester
242                        .handle(request)
243                        .await
244                        .map_err(add_peer_context_if_needed(datanode))
245                });
246            }
247        }
248
249        let mut results = join_all(create_region_tasks)
250            .await
251            .into_iter()
252            .collect::<Result<Vec<_>>>()?;
253
254        if let Some(column_metadatas) =
255            extract_column_metadatas(&mut results, TABLE_COLUMN_METADATA_EXTENSION_KEY)?
256        {
257            self.creator.data.column_metadatas = column_metadatas;
258        } else {
259            warn!("creating table result doesn't contains extension key `{TABLE_COLUMN_METADATA_EXTENSION_KEY}`,leaving the table's column metadata unchanged");
260        }
261
262        self.creator.data.state = CreateTableState::CreateMetadata;
263        Ok(Status::executing(true))
264    }
265
266    /// Creates table metadata
267    ///
268    /// Abort(not-retry):
269    /// - Failed to create table metadata.
270    async fn on_create_metadata(&mut self, pid: ProcedureId) -> Result<Status> {
271        let table_id = self.table_id();
272        let table_ref = self.creator.data.table_ref();
273        let manager = &self.context.table_metadata_manager;
274
275        let mut raw_table_info = self.table_info().clone();
276        if !self.creator.data.column_metadatas.is_empty() {
277            update_table_info_column_ids(&mut raw_table_info, &self.creator.data.column_metadatas);
278        }
279        // Safety: the region_wal_options must be allocated.
280        let region_wal_options = self.region_wal_options()?.clone();
281        // Safety: the table_route must be allocated.
282        let physical_table_route = self.table_route()?.clone();
283        let detecting_regions =
284            convert_region_routes_to_detecting_regions(&physical_table_route.region_routes);
285        let table_route = TableRouteValue::Physical(physical_table_route);
286        manager
287            .create_table_metadata(raw_table_info, table_route, region_wal_options)
288            .await?;
289        self.context
290            .register_failure_detectors(detecting_regions)
291            .await;
292        info!(
293            "Successfully created table: {}, table_id: {}, procedure_id: {}",
294            table_ref, table_id, pid
295        );
296
297        self.creator.opening_regions.clear();
298        Ok(Status::done_with_output(table_id))
299    }
300}
301
302#[async_trait]
303impl Procedure for CreateTableProcedure {
304    fn type_name(&self) -> &str {
305        Self::TYPE_NAME
306    }
307
308    fn recover(&mut self) -> ProcedureResult<()> {
309        // Only registers regions if the table route is allocated.
310        if let Some(x) = &self.creator.data.table_route {
311            self.creator.opening_regions = self
312                .creator
313                .register_opening_regions(&self.context, &x.region_routes)
314                .map_err(BoxedError::new)
315                .context(ExternalSnafu {
316                    clean_poisons: false,
317                })?;
318        }
319
320        Ok(())
321    }
322
323    async fn execute(&mut self, ctx: &ProcedureContext) -> ProcedureResult<Status> {
324        let state = &self.creator.data.state;
325
326        let _timer = metrics::METRIC_META_PROCEDURE_CREATE_TABLE
327            .with_label_values(&[state.as_ref()])
328            .start_timer();
329
330        match state {
331            CreateTableState::Prepare => self.on_prepare().await,
332            CreateTableState::DatanodeCreateRegions => self.on_datanode_create_regions().await,
333            CreateTableState::CreateMetadata => self.on_create_metadata(ctx.procedure_id).await,
334        }
335        .map_err(map_to_procedure_error)
336    }
337
338    fn dump(&self) -> ProcedureResult<String> {
339        serde_json::to_string(&self.creator.data).context(ToJsonSnafu)
340    }
341
342    fn lock_key(&self) -> LockKey {
343        let table_ref = &self.creator.data.table_ref();
344
345        LockKey::new(vec![
346            CatalogLock::Read(table_ref.catalog).into(),
347            SchemaLock::read(table_ref.catalog, table_ref.schema).into(),
348            TableNameLock::new(table_ref.catalog, table_ref.schema, table_ref.table).into(),
349        ])
350    }
351}
352
353pub struct TableCreator {
354    /// The serializable data.
355    pub data: CreateTableData,
356    /// The guards of opening.
357    pub opening_regions: Vec<OperatingRegionGuard>,
358}
359
360impl TableCreator {
361    pub fn new(task: CreateTableTask) -> Self {
362        Self {
363            data: CreateTableData {
364                state: CreateTableState::Prepare,
365                column_metadatas: vec![],
366                task,
367                table_route: None,
368                region_wal_options: None,
369            },
370            opening_regions: vec![],
371        }
372    }
373
374    /// Registers and returns the guards of the opening region if they don't exist.
375    fn register_opening_regions(
376        &self,
377        context: &DdlContext,
378        region_routes: &[RegionRoute],
379    ) -> Result<Vec<OperatingRegionGuard>> {
380        let opening_regions = operating_leader_regions(region_routes);
381
382        if self.opening_regions.len() == opening_regions.len() {
383            return Ok(vec![]);
384        }
385
386        let mut opening_region_guards = Vec::with_capacity(opening_regions.len());
387
388        for (region_id, datanode_id) in opening_regions {
389            let guard = context
390                .memory_region_keeper
391                .register(datanode_id, region_id)
392                .context(error::RegionOperatingRaceSnafu {
393                    region_id,
394                    peer_id: datanode_id,
395                })?;
396            opening_region_guards.push(guard);
397        }
398        Ok(opening_region_guards)
399    }
400
401    fn set_allocated_metadata(
402        &mut self,
403        table_id: TableId,
404        table_route: PhysicalTableRouteValue,
405        region_wal_options: HashMap<RegionNumber, String>,
406    ) {
407        self.data.task.table_info.ident.table_id = table_id;
408        self.data.table_route = Some(table_route);
409        self.data.region_wal_options = Some(region_wal_options);
410    }
411}
412
413#[derive(Debug, Clone, Serialize, Deserialize, AsRefStr, PartialEq)]
414pub enum CreateTableState {
415    /// Prepares to create the table
416    Prepare,
417    /// Creates regions on the Datanode
418    DatanodeCreateRegions,
419    /// Creates metadata
420    CreateMetadata,
421}
422
423#[derive(Debug, Serialize, Deserialize)]
424pub struct CreateTableData {
425    pub state: CreateTableState,
426    pub task: CreateTableTask,
427    #[serde(default)]
428    pub column_metadatas: Vec<ColumnMetadata>,
429    /// None stands for not allocated yet.
430    table_route: Option<PhysicalTableRouteValue>,
431    /// None stands for not allocated yet.
432    pub region_wal_options: Option<HashMap<RegionNumber, String>>,
433}
434
435impl CreateTableData {
436    fn table_ref(&self) -> TableReference<'_> {
437        self.task.table_ref()
438    }
439}