Skip to main content

datanode/
utils.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 common_meta::DatanodeId;
18use common_meta::key::datanode_table::{DatanodeTableManager, RegionInfo};
19use common_meta::key::topic_name::{TopicNameKey, TopicNameManager, TopicNameValue};
20use common_meta::key::topic_region::{
21    ReplayCheckpoint as MetadataReplayCheckpoint, TopicRegionKey, TopicRegionManager,
22    TopicRegionValue,
23};
24use common_meta::kv_backend::KvBackendRef;
25use common_meta::wal_provider::{
26    RegionWalOptions, extract_topic_from_wal_options, serialize_wal_options,
27};
28use futures::TryStreamExt;
29use snafu::ResultExt;
30use store_api::metric_engine_consts::METRIC_ENGINE_NAME;
31use store_api::path_utils::table_dir;
32use store_api::region_request::{PathType, RegionOpenRequest, ReplayCheckpoint};
33use store_api::storage::RegionId;
34use tracing::info;
35
36use crate::error::{GetMetadataSnafu, Result, SerializeWalOptionsSnafu};
37
38/// The requests to open regions.
39pub struct RegionOpenRequests {
40    pub(crate) leader_regions: Vec<(RegionId, RegionOpenRequest)>,
41    #[cfg(feature = "enterprise")]
42    pub(crate) follower_regions: Vec<(RegionId, RegionOpenRequest)>,
43}
44
45impl RegionOpenRequests {
46    /// Splits the request set into leader and follower regions.
47    #[allow(clippy::type_complexity)]
48    pub fn into_parts(
49        self,
50    ) -> (
51        Vec<(RegionId, RegionOpenRequest)>,
52        Vec<(RegionId, RegionOpenRequest)>,
53    ) {
54        let leader_regions = self.leader_regions;
55        #[cfg(feature = "enterprise")]
56        let follower_regions = self.follower_regions;
57        #[cfg(not(feature = "enterprise"))]
58        let follower_regions = Vec::new();
59        (leader_regions, follower_regions)
60    }
61}
62
63fn group_region_by_topic(
64    region_id: RegionId,
65    region_options: &RegionWalOptions,
66    topic_regions: &mut HashMap<String, Vec<RegionId>>,
67) {
68    if let Some(topic) = extract_topic_from_wal_options(region_id, region_options) {
69        topic_regions.entry(topic).or_default().push(region_id);
70    }
71}
72
73fn region_pruned_entry_ids(
74    topic_regions: &HashMap<String, Vec<RegionId>>,
75    topic_name_values: &HashMap<String, TopicNameValue>,
76) -> HashMap<RegionId, u64> {
77    topic_regions
78        .iter()
79        .flat_map(|(topic, region_ids)| {
80            topic_name_values
81                .get(topic)
82                .into_iter()
83                .flat_map(move |value| {
84                    region_ids
85                        .iter()
86                        .map(move |region_id| (*region_id, value.pruned_entry_id))
87                })
88        })
89        .collect()
90}
91
92fn get_replay_checkpoint(
93    region_id: RegionId,
94    topic_region_values: &Option<HashMap<RegionId, TopicRegionValue>>,
95    pruned_entry_id: Option<u64>,
96    is_metric_engine: bool,
97) -> Option<ReplayCheckpoint> {
98    let checkpoint = topic_region_values
99        .as_ref()
100        .and_then(|values| values.get(&region_id))
101        .and_then(|value| value.checkpoint)
102        .map(|checkpoint| {
103            MetadataReplayCheckpoint::new(checkpoint.entry_id, checkpoint.metadata_entry_id)
104        });
105
106    MetadataReplayCheckpoint::merge_with_topic_pruned_entry_id(
107        checkpoint,
108        pruned_entry_id,
109        is_metric_engine,
110    )
111    .map(|checkpoint| ReplayCheckpoint {
112        entry_id: checkpoint.entry_id,
113        metadata_entry_id: checkpoint.metadata_entry_id,
114    })
115}
116
117/// Builds the request that opens `region_id` of a table with `region_info`, with the WAL
118/// options of the region if `region_info` has them. The request does not skip the WAL replay
119/// and has no replay checkpoint.
120pub(crate) fn build_region_open_request(
121    region_id: RegionId,
122    region_info: &RegionInfo,
123) -> Result<RegionOpenRequest> {
124    let mut options = region_info.region_options.clone();
125    serialize_wal_options(&mut options, region_id, &region_info.region_wal_options)
126        .context(SerializeWalOptionsSnafu { region_id })?;
127    Ok(RegionOpenRequest {
128        engine: region_info.engine.clone(),
129        table_dir: table_dir(&region_info.region_storage_path, region_id.table_id()),
130        path_type: PathType::Bare,
131        options,
132        skip_wal_replay: false,
133        checkpoint: None,
134        requirements: Default::default(),
135    })
136}
137
138/// Builds region-open requests from persisted metadata.
139pub async fn build_region_open_requests(
140    node_id: DatanodeId,
141    kv_backend: KvBackendRef,
142) -> Result<RegionOpenRequests> {
143    let datanode_table_manager = DatanodeTableManager::new(kv_backend.clone());
144    let table_values = datanode_table_manager
145        .tables(node_id)
146        .try_collect::<Vec<_>>()
147        .await
148        .context(GetMetadataSnafu)?;
149
150    let topic_region_manager = TopicRegionManager::new(kv_backend.clone());
151    let topic_name_manager = TopicNameManager::new(kv_backend);
152    let mut topic_regions = HashMap::<String, Vec<RegionId>>::new();
153    let mut regions = vec![];
154    #[cfg(feature = "enterprise")]
155    let mut follower_regions = vec![];
156
157    for table_value in table_values {
158        for region_number in table_value.regions {
159            let region_id = RegionId::new(table_value.table_id, region_number);
160            group_region_by_topic(
161                region_id,
162                &table_value.region_info.region_wal_options,
163                &mut topic_regions,
164            );
165            regions.push((
166                region_id,
167                build_region_open_request(region_id, &table_value.region_info)?,
168            ));
169        }
170
171        #[cfg(feature = "enterprise")]
172        for region_number in table_value.follower_regions {
173            let region_id = RegionId::new(table_value.table_id, region_number);
174            group_region_by_topic(
175                region_id,
176                &table_value.region_info.region_wal_options,
177                &mut topic_regions,
178            );
179            follower_regions.push((
180                region_id,
181                build_region_open_request(region_id, &table_value.region_info)?,
182            ));
183        }
184    }
185
186    let topic_region_values = if !topic_regions.is_empty() {
187        let keys = topic_regions
188            .iter()
189            .flat_map(|(topic, regions)| {
190                regions
191                    .iter()
192                    .map(|region_id| TopicRegionKey::new(*region_id, topic))
193            })
194            .collect::<Vec<_>>();
195        let topic_region_manager = topic_region_manager
196            .batch_get(keys)
197            .await
198            .context(GetMetadataSnafu)?;
199        Some(topic_region_manager)
200    } else {
201        None
202    };
203
204    let topic_name_values = if !topic_regions.is_empty() {
205        let topics = topic_regions
206            .keys()
207            .map(|topic| TopicNameKey::new(topic))
208            .collect::<Vec<_>>();
209        Some(
210            topic_name_manager
211                .batch_get(topics)
212                .await
213                .context(GetMetadataSnafu)?,
214        )
215    } else {
216        None
217    };
218    let region_pruned_entry_ids = topic_name_values
219        .as_ref()
220        .map(|values| region_pruned_entry_ids(&topic_regions, values));
221
222    for (region_id, request) in &mut regions {
223        let pruned_entry_id = region_pruned_entry_ids
224            .as_ref()
225            .and_then(|values| values.get(region_id).copied());
226        let checkpoint = get_replay_checkpoint(
227            *region_id,
228            &topic_region_values,
229            pruned_entry_id,
230            request.engine == METRIC_ENGINE_NAME,
231        );
232        info!("region_id: {}, checkpoint: {:?}", region_id, checkpoint);
233        request.checkpoint = checkpoint;
234    }
235
236    #[cfg(feature = "enterprise")]
237    for (_, request) in &mut follower_regions {
238        request.skip_wal_replay = true;
239    }
240
241    Ok(RegionOpenRequests {
242        leader_regions: regions,
243        #[cfg(feature = "enterprise")]
244        follower_regions,
245    })
246}