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        let partition_exprs = region_routes
218            .iter()
219            .map(|r| (r.region.id.region_number(), r.region.partition_expr()))
220            .collect();
221
222        for datanode in leaders {
223            let requester = self.context.node_manager.datanode(&datanode).await;
224
225            let regions = find_leader_regions(region_routes, &datanode);
226            let mut requests = Vec::with_capacity(regions.len());
227            for region_number in regions {
228                let region_id = RegionId::new(self.table_id(), region_number);
229                let create_region_request = request_builder.build_one(
230                    region_id,
231                    storage_path.clone(),
232                    region_wal_options,
233                    &partition_exprs,
234                );
235                requests.push(PbRegionRequest::Create(create_region_request));
236            }
237
238            for request in requests {
239                let request = RegionRequest {
240                    header: Some(RegionRequestHeader {
241                        tracing_context: TracingContext::from_current_span().to_w3c(),
242                        ..Default::default()
243                    }),
244                    body: Some(request),
245                };
246
247                let datanode = datanode.clone();
248                let requester = requester.clone();
249                create_region_tasks.push(async move {
250                    requester
251                        .handle(request)
252                        .await
253                        .map_err(add_peer_context_if_needed(datanode))
254                });
255            }
256        }
257
258        let mut results = join_all(create_region_tasks)
259            .await
260            .into_iter()
261            .collect::<Result<Vec<_>>>()?;
262
263        if let Some(column_metadatas) =
264            extract_column_metadatas(&mut results, TABLE_COLUMN_METADATA_EXTENSION_KEY)?
265        {
266            self.creator.data.column_metadatas = column_metadatas;
267        } else {
268            warn!("creating table result doesn't contains extension key `{TABLE_COLUMN_METADATA_EXTENSION_KEY}`,leaving the table's column metadata unchanged");
269        }
270
271        self.creator.data.state = CreateTableState::CreateMetadata;
272        Ok(Status::executing(true))
273    }
274
275    /// Creates table metadata
276    ///
277    /// Abort(not-retry):
278    /// - Failed to create table metadata.
279    async fn on_create_metadata(&mut self, pid: ProcedureId) -> Result<Status> {
280        let table_id = self.table_id();
281        let table_ref = self.creator.data.table_ref();
282        let manager = &self.context.table_metadata_manager;
283
284        let mut raw_table_info = self.table_info().clone();
285        if !self.creator.data.column_metadatas.is_empty() {
286            update_table_info_column_ids(&mut raw_table_info, &self.creator.data.column_metadatas);
287        }
288        // Safety: the region_wal_options must be allocated.
289        let region_wal_options = self.region_wal_options()?.clone();
290        // Safety: the table_route must be allocated.
291        let physical_table_route = self.table_route()?.clone();
292        let detecting_regions =
293            convert_region_routes_to_detecting_regions(&physical_table_route.region_routes);
294        let table_route = TableRouteValue::Physical(physical_table_route);
295        manager
296            .create_table_metadata(raw_table_info, table_route, region_wal_options)
297            .await?;
298        self.context
299            .register_failure_detectors(detecting_regions)
300            .await;
301        info!(
302            "Successfully created table: {}, table_id: {}, procedure_id: {}",
303            table_ref, table_id, pid
304        );
305
306        self.creator.opening_regions.clear();
307        Ok(Status::done_with_output(table_id))
308    }
309}
310
311#[async_trait]
312impl Procedure for CreateTableProcedure {
313    fn type_name(&self) -> &str {
314        Self::TYPE_NAME
315    }
316
317    fn recover(&mut self) -> ProcedureResult<()> {
318        // Only registers regions if the table route is allocated.
319        if let Some(x) = &self.creator.data.table_route {
320            self.creator.opening_regions = self
321                .creator
322                .register_opening_regions(&self.context, &x.region_routes)
323                .map_err(BoxedError::new)
324                .context(ExternalSnafu {
325                    clean_poisons: false,
326                })?;
327        }
328
329        Ok(())
330    }
331
332    async fn execute(&mut self, ctx: &ProcedureContext) -> ProcedureResult<Status> {
333        let state = &self.creator.data.state;
334
335        let _timer = metrics::METRIC_META_PROCEDURE_CREATE_TABLE
336            .with_label_values(&[state.as_ref()])
337            .start_timer();
338
339        match state {
340            CreateTableState::Prepare => self.on_prepare().await,
341            CreateTableState::DatanodeCreateRegions => self.on_datanode_create_regions().await,
342            CreateTableState::CreateMetadata => self.on_create_metadata(ctx.procedure_id).await,
343        }
344        .map_err(map_to_procedure_error)
345    }
346
347    fn dump(&self) -> ProcedureResult<String> {
348        serde_json::to_string(&self.creator.data).context(ToJsonSnafu)
349    }
350
351    fn lock_key(&self) -> LockKey {
352        let table_ref = &self.creator.data.table_ref();
353
354        LockKey::new(vec![
355            CatalogLock::Read(table_ref.catalog).into(),
356            SchemaLock::read(table_ref.catalog, table_ref.schema).into(),
357            TableNameLock::new(table_ref.catalog, table_ref.schema, table_ref.table).into(),
358        ])
359    }
360}
361
362pub struct TableCreator {
363    /// The serializable data.
364    pub data: CreateTableData,
365    /// The guards of opening.
366    pub opening_regions: Vec<OperatingRegionGuard>,
367}
368
369impl TableCreator {
370    pub fn new(task: CreateTableTask) -> Self {
371        Self {
372            data: CreateTableData {
373                state: CreateTableState::Prepare,
374                column_metadatas: vec![],
375                task,
376                table_route: None,
377                region_wal_options: None,
378            },
379            opening_regions: vec![],
380        }
381    }
382
383    /// Registers and returns the guards of the opening region if they don't exist.
384    fn register_opening_regions(
385        &self,
386        context: &DdlContext,
387        region_routes: &[RegionRoute],
388    ) -> Result<Vec<OperatingRegionGuard>> {
389        let opening_regions = operating_leader_regions(region_routes);
390
391        if self.opening_regions.len() == opening_regions.len() {
392            return Ok(vec![]);
393        }
394
395        let mut opening_region_guards = Vec::with_capacity(opening_regions.len());
396
397        for (region_id, datanode_id) in opening_regions {
398            let guard = context
399                .memory_region_keeper
400                .register(datanode_id, region_id)
401                .context(error::RegionOperatingRaceSnafu {
402                    region_id,
403                    peer_id: datanode_id,
404                })?;
405            opening_region_guards.push(guard);
406        }
407        Ok(opening_region_guards)
408    }
409
410    fn set_allocated_metadata(
411        &mut self,
412        table_id: TableId,
413        table_route: PhysicalTableRouteValue,
414        region_wal_options: HashMap<RegionNumber, String>,
415    ) {
416        self.data.task.table_info.ident.table_id = table_id;
417        self.data.table_route = Some(table_route);
418        self.data.region_wal_options = Some(region_wal_options);
419    }
420}
421
422#[derive(Debug, Clone, Serialize, Deserialize, AsRefStr, PartialEq)]
423pub enum CreateTableState {
424    /// Prepares to create the table
425    Prepare,
426    /// Creates regions on the Datanode
427    DatanodeCreateRegions,
428    /// Creates metadata
429    CreateMetadata,
430}
431
432#[derive(Debug, Serialize, Deserialize)]
433pub struct CreateTableData {
434    pub state: CreateTableState,
435    pub task: CreateTableTask,
436    #[serde(default)]
437    pub column_metadatas: Vec<ColumnMetadata>,
438    /// None stands for not allocated yet.
439    table_route: Option<PhysicalTableRouteValue>,
440    /// None stands for not allocated yet.
441    pub region_wal_options: Option<HashMap<RegionNumber, String>>,
442}
443
444impl CreateTableData {
445    fn table_ref(&self) -> TableReference<'_> {
446        self.task.table_ref()
447    }
448}