Skip to main content

mito2/worker/
handle_copy_region.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::sync::{Arc, Mutex};
17
18use common_telemetry::{debug, error, info};
19use snafu::{OptionExt, ResultExt, ensure};
20use store_api::region_engine::MitoCopyRegionFromResponse;
21use store_api::region_request::PathType;
22use store_api::storage::{FileId, RegionId};
23
24use crate::error::{InvalidRequestSnafu, MissingManifestSnafu, Result};
25use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
26use crate::region::{
27    FileDescriptor, MitoRegionRef, RegionFileCopier, RegionLeaderState, RegionMetadataLoader,
28};
29use crate::request::{
30    BackgroundNotify, CopyRegionFromFinished, CopyRegionFromRequest, WorkerRequest,
31};
32use crate::sst::file::{self, FileMeta};
33use crate::sst::location::region_dir_from_table_dir;
34use crate::worker::{RegionWorkerLoop, WorkerRequestWithTime};
35
36/// COPY locks shared by one region worker and its background tasks.
37#[derive(Clone, Default)]
38pub(super) struct CopyRegionLocks {
39    entries: Arc<Mutex<HashMap<RegionId, CopyRegionLock>>>,
40}
41
42struct CopyRegionLock {
43    mutex: Arc<tokio::sync::Mutex<()>>,
44    users: usize,
45}
46
47/// Registers a COPY before it is spawned, including while it waits for the lock.
48struct CopyRegionGuard {
49    locks: CopyRegionLocks,
50    region_id: RegionId,
51    mutex: Arc<tokio::sync::Mutex<()>>,
52}
53
54impl CopyRegionLocks {
55    fn register(&self, region_id: RegionId) -> CopyRegionGuard {
56        let mut entries = self.entries.lock().unwrap();
57        let entry = entries.entry(region_id).or_insert_with(|| CopyRegionLock {
58            mutex: Arc::new(tokio::sync::Mutex::new(())),
59            users: 0,
60        });
61        entry.users += 1;
62        CopyRegionGuard {
63            locks: self.clone(),
64            region_id,
65            mutex: entry.mutex.clone(),
66        }
67    }
68}
69
70impl Drop for CopyRegionGuard {
71    fn drop(&mut self) {
72        // Registration and removal share the map lock, so a queued COPY cannot
73        // lose its entry and race a new COPY using a different mutex.
74        let mut entries = self.locks.entries.lock().unwrap();
75        let entry = entries.get_mut(&self.region_id).unwrap();
76        entry.users -= 1;
77        if entry.users == 0 {
78            entries.remove(&self.region_id);
79        }
80    }
81}
82
83impl<S> RegionWorkerLoop<S> {
84    pub(crate) fn handle_copy_region_from_request(&mut self, request: CopyRegionFromRequest) {
85        let region_id = request.region_id;
86        let source_region_id = request.source_region_id;
87        let sender = request.sender;
88        let region = match self.regions.writable_non_staging_region(region_id) {
89            Ok(region) => region,
90            Err(e) => {
91                let _ = sender.send(Err(e));
92                return;
93            }
94        };
95
96        let same_table = source_region_id.table_id() == region_id.table_id();
97        if !same_table {
98            let _ = sender.send(
99                InvalidRequestSnafu {
100                    region_id,
101                    reason: format!("Source and target regions must be from the same table, source_region_id: {source_region_id}, target_region_id: {region_id}"),
102                }
103                .fail(),
104            );
105            return;
106        }
107        if source_region_id == region_id {
108            let _ = sender.send(
109                InvalidRequestSnafu {
110                    region_id,
111                    reason: format!("Source and target regions must be different, source_region_id: {source_region_id}, target_region_id: {region_id}"),
112                }
113                .fail(),
114            );
115            return;
116        }
117
118        let region_metadata_loader = RegionMetadataLoader::new(
119            self.config.clone(),
120            self.object_store_manager.clone(),
121            self.node_lease.is_enabled(),
122            self.file_ref_manager.file_metadata_interner.clone(),
123        );
124        let worker_sender = self.sender.clone();
125
126        let copy_guard = self.copy_region_locks.register(region_id);
127        common_runtime::spawn_global(async move {
128            let _copy_lock = copy_guard.mutex.lock().await;
129            let (region_edit, source_file_ids) = match Self::copy_region_from(
130                &region,
131                region_metadata_loader,
132                source_region_id,
133                region_id,
134                request.parallelism.max(1),
135            )
136            .await
137            {
138                Ok(region_files) => region_files,
139                Err(e) => {
140                    let _ = sender.send(Err(e));
141                    return;
142                }
143            };
144
145            match region_edit {
146                Some(region_edit)
147                    if region_edit
148                        .files_to_add
149                        .iter()
150                        .any(|file| file.level == file::LEVEL_SHARED) =>
151                {
152                    // Shared references enter the serialized
153                    // edit lane for destination admission sequences.
154                    // The response lists installed references, including shared SSTs
155                    // whose objects stay in place; it is not a physical COPY count.
156                    let copied_file_ids = region_edit
157                        .files_to_add
158                        .iter()
159                        .map(|file| file.file_id)
160                        .collect();
161                    let (tx, rx) = tokio::sync::oneshot::channel();
162                    if worker_sender
163                        .send(WorkerRequestWithTime::new(WorkerRequest::EditRegion(
164                            crate::request::RegionEditRequest::new(
165                                region_id,
166                                region_edit,
167                                false,
168                                tx,
169                            )
170                            .for_copy_region(),
171                        )))
172                        .await
173                        .is_err()
174                    {
175                        let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail());
176                        return;
177                    }
178                    let result = match rx.await {
179                        Ok(result) => {
180                            result.map(|_| MitoCopyRegionFromResponse { copied_file_ids })
181                        }
182                        Err(error) => Err(error).context(crate::error::RecvSnafu),
183                    };
184                    let _ = sender.send(result);
185                }
186                Some(region_edit) => {
187                    let (tx, rx) = tokio::sync::oneshot::channel();
188                    if let Err(e) = worker_sender
189                        .send(WorkerRequestWithTime::new(WorkerRequest::Background {
190                            region_id,
191                            notify: BackgroundNotify::CopyRegionFromFinished(
192                                CopyRegionFromFinished {
193                                    region_id,
194                                    edit: region_edit,
195                                    sender: tx,
196                                },
197                            ),
198                        }))
199                        .await
200                    {
201                        error!(e; "Failed to send copy region from finished notification, region_id: {}", region_id);
202                        let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail());
203                        return;
204                    }
205                    // Keep ownership until the worker installs the published version.
206                    let result = match rx.await {
207                        Ok(result) => result,
208                        Err(error) => Err(error).context(crate::error::RecvSnafu),
209                    };
210                    let _ = sender.send(result);
211                }
212                None => {
213                    let _ = sender.send(Ok(MitoCopyRegionFromResponse {
214                        copied_file_ids: source_file_ids,
215                    }));
216                }
217            }
218        });
219    }
220
221    pub(crate) async fn handle_copy_region_from_finished(
222        &mut self,
223        request: CopyRegionFromFinished,
224    ) {
225        let region_id = request.region_id;
226        let sender = request.sender;
227        let region = match self.regions.writable_region(region_id) {
228            Ok(region) => region,
229            Err(e) => {
230                let _ = sender.send(Err(e));
231                return;
232            }
233        };
234
235        let copied_file_ids = request
236            .edit
237            .files_to_add
238            .iter()
239            .map(|file_meta| file_meta.file_id)
240            .collect();
241
242        region.apply_published_edit(request.edit, &[]).await;
243
244        let _ = sender.send(Ok(MitoCopyRegionFromResponse { copied_file_ids }));
245    }
246
247    /// Returns the region edit and source file IDs, including shared logical references.
248    ///
249    /// If no need to copy files, returns (None, source_file_ids).
250    async fn copy_region_from(
251        region: &MitoRegionRef,
252        region_metadata_loader: RegionMetadataLoader,
253        source_region_id: RegionId,
254        target_region_id: RegionId,
255        parallelism: usize,
256    ) -> Result<(Option<RegionEdit>, Vec<FileId>)> {
257        let table_dir = region.table_dir();
258        let path_type = region.path_type();
259        let region_dir = region_dir_from_table_dir(table_dir, source_region_id, path_type);
260        info!(
261            "Loading source region manifest from region dir: {region_dir}, target region: {target_region_id}"
262        );
263        let source_region_manifest = region_metadata_loader
264            .load_manifest(&region_dir, &region.version().options)
265            .await?
266            .context(MissingManifestSnafu {
267                region_id: source_region_id,
268            })?;
269        let narthex_format =
270            region.version().options.sst_format == Some(crate::sst::FormatType::Narthex);
271        ensure!(
272            (source_region_manifest.sst_format == crate::sst::FormatType::Narthex)
273                == narthex_format,
274            InvalidRequestSnafu {
275                region_id: target_region_id,
276                reason: "Cannot copy between Parquet and Narthex regions",
277            }
278        );
279        // Metadata sync transforms copied rows and then removes these references.
280        // It cannot retire shared inputs through the ordinary edit API, so reject
281        // them before either physical copying or extending the target manifest.
282        ensure!(
283            path_type != PathType::Metadata
284                || source_region_manifest
285                    .files
286                    .values()
287                    .all(|file| file.level != file::LEVEL_SHARED),
288            InvalidRequestSnafu {
289                region_id: target_region_id,
290                reason: "Shared SST references are not supported in metadata-region copies",
291            }
292        );
293        let mut new_file_metas = vec![];
294        let target_region_manifest = region.manifest_ctx.manifest().await;
295        let source_file_ids = source_region_manifest
296            .files
297            .keys()
298            .cloned()
299            .collect::<Vec<_>>();
300        debug!(
301            "source region files: {:?}, source region id: {}",
302            source_region_manifest.files, source_region_id
303        );
304        let mut file_descriptors = Vec::new();
305        for (file_id, file_meta) in &source_region_manifest.files {
306            if target_region_manifest.files.contains_key(file_id) {
307                continue;
308            }
309            if file_meta.level == file::LEVEL_SHARED {
310                new_file_metas.push(file_meta.as_ref().clone());
311            } else if narthex_format {
312                let (copied, objects) = prepare_narthex_copy(region, file_meta).await?;
313                new_file_metas.push(copied);
314                file_descriptors.extend(objects);
315            } else {
316                let copied = remap_copied_file_meta(file_meta, target_region_id);
317                file_descriptors.extend(file_descriptors_for_meta(&copied));
318                new_file_metas.push(copied);
319            }
320        }
321        // Native series coverage belongs to the source region's sequence domain.
322        if new_file_metas.is_empty() {
323            return Ok((None, source_file_ids));
324        }
325
326        debug!("File descriptors to copy: {:?}", file_descriptors);
327        let copier = RegionFileCopier::new(region.access_layer());
328        // TODO(weny): ensure the target region is empty.
329        copier
330            .copy_files(
331                source_region_id,
332                target_region_id,
333                file_descriptors,
334                parallelism,
335            )
336            .await?;
337        let edit = RegionEdit {
338            files_to_add: new_file_metas,
339            files_to_remove: vec![],
340            timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
341            compaction_time_window: None,
342            flushed_entry_id: None,
343            flushed_sequence: None,
344            committed_sequence: None,
345            ..Default::default()
346        };
347        if edit
348            .files_to_add
349            .iter()
350            .any(|file| file.level == file::LEVEL_SHARED)
351        {
352            return Ok((Some(edit), source_file_ids));
353        }
354        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
355        info!(
356            "Applying {:?} to region {target_region_id}, reason: CopyRegionFrom",
357            edit
358        );
359        let version = region
360            .manifest_ctx
361            .update_manifest(RegionLeaderState::Writable, action_list, false)
362            .await?;
363        info!(
364            "Successfully update manifest version to {version}, region: {target_region_id}, reason: CopyRegionFrom"
365        );
366
367        Ok((Some(edit), source_file_ids))
368    }
369}
370
371fn remap_copied_file_meta(file_meta: &FileMeta, target_region_id: RegionId) -> FileMeta {
372    let mut new_file_meta = file_meta.clone();
373    new_file_meta.region_id = target_region_id;
374    // The target region has an independent sequence domain: the physical
375    // per-row sequences in the copied file belong to the source region, so they
376    // must not be trusted for exact sequence-range reads on the target. Clear
377    // the `preserve_row_sequence` marker and source-domain max sequence to fail
378    // closed until the scan provably cannot intersect the copied rows (see
379    // `files_allow_exact_sequence_range`); otherwise an exact request would
380    // replay source-domain rows as target sequences, and an unmarked file with
381    // a stale source-domain `sequence` hint could be silently skipped as
382    // "proven disjoint".
383    new_file_meta.preserve_row_sequence = false;
384    new_file_meta.sequence = None;
385    new_file_meta
386}
387
388fn file_descriptors_for_meta(file_meta: &FileMeta) -> Vec<FileDescriptor> {
389    let data = FileDescriptor::Data {
390        file_id: file_meta.file_id,
391        size: file_meta.file_size,
392    };
393    if file_meta.exists_index() {
394        let region_index_id = file_meta.index_id();
395        vec![
396            data,
397            FileDescriptor::Index {
398                file_id: region_index_id.file_id.file_id(),
399                version: region_index_id.version,
400                size: file_meta.index_file_size(),
401            },
402        ]
403    } else {
404        vec![data]
405    }
406}
407
408/// Prepares a physical narthex copy without rewriting encoded parts. The artifact
409/// manifest records the physical owner; paths are resolved from FileMeta on read.
410async fn prepare_narthex_copy(
411    region: &MitoRegionRef,
412    source: &FileMeta,
413) -> Result<(FileMeta, Vec<FileDescriptor>)> {
414    use crate::series_index::columnar::{invalid, require};
415    use crate::sst::file::FileFormat;
416
417    let layer = region.access_layer();
418    let source_objects = source
419        .narthex_objects(&layer.build_region_dir(source.region_id))
420        .ok_or_else(|| invalid("expected Narthex copy source"))?;
421    let (source_manifest, parts) = source_objects
422        .split_last()
423        .expect("Narthex inventory includes manifest");
424    let bytes = layer
425        .object_store()
426        .read(&source_manifest.path)
427        .await
428        .context(crate::error::OpenDalSnafu)?
429        .to_bytes();
430    let mut manifest: serde_json::Value =
431        serde_json::from_slice(&bytes).map_err(|error| invalid(error.to_string()))?;
432    require(
433        manifest["region_id"].as_u64() == Some(source.region_id.as_u64())
434            && manifest["generation"].as_str() == Some(source.file_id.to_string().as_str()),
435        "narthex copy manifest identity mismatch",
436    )?;
437    manifest["region_id"] = serde_json::json!(region.region_id.as_u64());
438    let bytes = bytes::Bytes::from(
439        serde_json::to_vec(&manifest).map_err(|error| invalid(error.to_string()))?,
440    );
441    let target_region_dir = layer.build_region_dir(region.region_id);
442    let mut copied = remap_copied_file_meta(source, region.region_id);
443    let manifest_size = bytes.len() as u64;
444    match &mut copied.format {
445        FileFormat::NarthexSamples(meta) => meta.manifest_size = manifest_size,
446        FileFormat::NarthexSeriesIndex(meta) => meta.manifest_size = manifest_size,
447        FileFormat::Parquet => return Err(invalid("expected Narthex copy source")),
448    }
449    let targets = copied
450        .narthex_objects(&target_region_dir)
451        .expect("Narthex copy");
452    let descriptors: Vec<_> = source_objects
453        .iter()
454        .zip(targets)
455        .enumerate()
456        .map(|(i, (object, target))| FileDescriptor::NarthexObject {
457            source: object.path.clone(),
458            target: target.path,
459            size: target.file_size,
460            manifest: (i == parts.len()).then(|| bytes.clone()),
461        })
462        .collect();
463    copied.file_size = descriptors.iter().try_fold(0u64, |size, object| {
464        size.checked_add(object.size())
465            .ok_or_else(|| invalid("narthex copy size overflow"))
466    })?;
467    Ok((copied, descriptors))
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[tokio::test]
475    async fn copy_lock_guard_cleans_up_after_waiter_cancellation() {
476        let locks = CopyRegionLocks::default();
477        let region_id = RegionId::new(1, 1);
478        let first = locks.register(region_id);
479        let held = first.mutex.lock().await;
480        let waiting = locks.register(region_id);
481        assert!(Arc::ptr_eq(&first.mutex, &waiting.mutex));
482        let task = tokio::spawn(async move {
483            let _held = waiting.mutex.lock().await;
484        });
485        task.abort();
486        assert!(task.await.unwrap_err().is_cancelled());
487        assert_eq!(locks.entries.lock().unwrap()[&region_id].users, 1);
488        drop(held);
489        drop(first);
490        assert!(locks.entries.lock().unwrap().is_empty());
491    }
492
493    #[tokio::test]
494    async fn copy_lock_guard_retains_entry_for_waiting_copy() {
495        let locks = CopyRegionLocks::default();
496        let region_id = RegionId::new(1, 1);
497        let first = locks.register(region_id);
498        let held = first.mutex.lock().await;
499        let waiting = locks.register(region_id);
500        assert!(waiting.mutex.try_lock().is_err());
501        drop(held);
502        drop(first);
503        let next = locks.register(region_id);
504        assert!(Arc::ptr_eq(&waiting.mutex, &next.mutex));
505        let held = waiting.mutex.lock().await;
506        assert!(next.mutex.try_lock().is_err());
507        drop(held);
508        drop(waiting);
509        assert_eq!(locks.entries.lock().unwrap()[&region_id].users, 1);
510        drop(next);
511        assert!(locks.entries.lock().unwrap().is_empty());
512    }
513}