Skip to main content

mito2/worker/
handle_remap.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;
16use std::time::Instant;
17
18use common_error::ext::BoxedError;
19use common_telemetry::{debug, info};
20use futures::future::try_join_all;
21use partition::expr::PartitionExpr;
22use snafu::{OptionExt, ResultExt};
23use store_api::storage::RegionId;
24
25use crate::error::{self, FetchManifestsSnafu, InvalidRequestSnafu, MissingManifestSnafu, Result};
26use crate::region::{MitoRegionRef, RegionMetadataLoader};
27use crate::remap_manifest::RemapManifest;
28use crate::request::RemapManifestsRequest;
29use crate::sst::location::region_dir_from_table_dir;
30use crate::worker::RegionWorkerLoop;
31
32impl<S> RegionWorkerLoop<S> {
33    pub(crate) fn handle_remap_manifests_request(&mut self, request: RemapManifestsRequest) {
34        let region_id = request.region_id;
35        let sender = request.sender;
36        if request.validate_only {
37            // The pre-publication check of the repartition procedure: nothing is staged yet, so
38            // this reads the region's ordinary manifest and reports whether it holds a file it
39            // did not create itself. It writes nothing and returns no manifest paths.
40            let Some(region) = self.regions.get_region(region_id) else {
41                let _ = sender.send(error::RegionNotFoundSnafu { region_id }.fail());
42                return;
43            };
44            common_runtime::spawn_global(async move {
45                let manifest = region.manifest_ctx.manifest().await;
46                let result =
47                    crate::remap_manifest::ensure_region_owns_its_files(region_id, &manifest)
48                        .map(|()| HashMap::new());
49                let _ = sender.send(result);
50            });
51            return;
52        }
53
54        let region = match self.regions.staging_region(region_id) {
55            Ok(region) => region,
56            Err(e) => {
57                let _ = sender.send(Err(e));
58                return;
59            }
60        };
61
62        let same_table = request
63            .input_regions
64            .iter()
65            .map(|r| r.table_id())
66            .all(|t| t == region_id.table_id());
67
68        if !same_table {
69            let _ = sender.send(
70                InvalidRequestSnafu {
71                    region_id,
72                    reason: "Input regions must be from the same table",
73                }
74                .fail(),
75            );
76            return;
77        }
78
79        let region_metadata_loader = RegionMetadataLoader::new(
80            self.config.clone(),
81            self.object_store_manager.clone(),
82            self.node_lease.is_enabled(),
83            self.file_ref_manager.file_metadata_interner.clone(),
84        );
85        common_runtime::spawn_global(async move {
86            let result = Self::fetch_and_remap_manifests(
87                region,
88                region_metadata_loader,
89                request.input_regions,
90                request.new_partition_exprs,
91                request.region_mapping,
92            )
93            .await;
94
95            let _ = sender.send(result);
96        });
97    }
98
99    // Fetches manifests for input regions, remaps them according to the provided
100    // mapping and partition expressions.
101    //
102    // Returns a map from each new region to its relative staging manifest path.
103    async fn fetch_and_remap_manifests(
104        region: MitoRegionRef,
105        region_metadata_loader: RegionMetadataLoader,
106        input_regions: Vec<RegionId>,
107        new_partition_exprs: HashMap<RegionId, PartitionExpr>,
108        region_mapping: HashMap<RegionId, Vec<RegionId>>,
109    ) -> Result<HashMap<RegionId, String>> {
110        let mut tasks = Vec::with_capacity(input_regions.len());
111        let region_options = region.version().options.clone();
112        let table_dir = region.table_dir();
113        let path_type = region.path_type();
114        let now = Instant::now();
115        for input_region in &input_regions {
116            let region_dir = region_dir_from_table_dir(table_dir, *input_region, path_type);
117            let region_options = region_options.clone();
118            let moved_region_metadata_loader = region_metadata_loader.clone();
119            tasks.push(async move {
120                moved_region_metadata_loader
121                    .load_manifest(&region_dir, &region_options)
122                    .await
123            });
124        }
125        let results = try_join_all(tasks)
126            .await
127            .map_err(BoxedError::new)
128            .context(FetchManifestsSnafu)?;
129        let manifests = results
130            .into_iter()
131            .zip(input_regions)
132            .map(|(manifest_res, region_id)| {
133                let manifest = manifest_res.context(MissingManifestSnafu { region_id })?;
134                Ok((region_id, (*manifest).clone()))
135            })
136            .collect::<Result<HashMap<_, _>>>()?;
137        let mut mapper = RemapManifest::new(manifests, new_partition_exprs, region_mapping);
138        let remap_result = mapper.remap_manifests()?;
139
140        // Write new manifests to staging blob storage.
141        let manifest_manager = region.manifest_ctx.manifest_manager.write().await;
142        let manifest_storage = manifest_manager.store();
143        let staging_blob_storage = manifest_storage.staging_storage().blob_storage().clone();
144        let mut tasks = Vec::with_capacity(remap_result.new_manifests.len());
145
146        for (remap_region_id, manifest) in &remap_result.new_manifests {
147            let bytes = serde_json::to_vec(&manifest).context(error::SerializeManifestSnafu {
148                region_id: *remap_region_id,
149            })?;
150            let key = remap_manifest_key(remap_region_id);
151            tasks.push(async {
152                debug!(
153                    "Putting manifest to staging blob storage, region_id: {}, key: {}",
154                    *remap_region_id, key
155                );
156                staging_blob_storage.put(&key, bytes).await?;
157                Ok((*remap_region_id, key))
158            });
159        }
160        let r = try_join_all(tasks).await?;
161        info!(
162            "Remap manifests cost: {:?}, region: {}",
163            now.elapsed(),
164            region.region_id
165        );
166
167        Ok(r.into_iter().collect::<HashMap<_, _>>())
168    }
169}
170
171fn remap_manifest_key(region_id: &RegionId) -> String {
172    format!("remap_manifest_{}", region_id.as_u64())
173}