Skip to main content

mito2/worker/
handle_reload.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
15//! Reloading a region fenced by a manifest version conflict, or by a failed tail replay round
16//! that found a newer manifest.
17
18use std::sync::Arc;
19
20use common_telemetry::{error, info, warn};
21use store_api::logstore::LogStore;
22use store_api::storage::RegionId;
23use tokio::sync::mpsc::Sender;
24
25use crate::error::Result;
26use crate::region::{MitoRegion, MitoRegionRef};
27use crate::request::{BackgroundNotify, WorkerRequest, WorkerRequestWithTime};
28use crate::worker::RegionWorkerLoop;
29
30impl<S: LogStore> RegionWorkerLoop<S> {
31    /// Starts reloading the region from its manifest and this node's WAL if a manifest version
32    /// conflict or a failed tail replay round that found a newer manifest fenced it, and no
33    /// catchup or reload of it runs.
34    pub(crate) fn maybe_reload_region(&mut self, region_id: RegionId) {
35        let Some(region) = self.regions.get_region(region_id) else {
36            return;
37        };
38        // A flush of the old instance would report to the replacement, so the reload waits until
39        // the flush reports here, which checks again.
40        if !region.manifest_ctx.is_reload_pending()
41            || self.catchup_regions.is_region_exists(region_id)
42            || self.flush_scheduler.is_flush_requested(region_id)
43        {
44            return;
45        }
46        // The worker writes a region inline and a Follower takes no writes, so every
47        // acknowledged write has an entry id at or below the one read below.
48        if !region.is_follower() {
49            warn!(
50                "Region {region_id} waits for a reload but is {:?}, not reloading it",
51                region.state()
52            );
53            return;
54        }
55        let opener = match self.region_reopener(&region) {
56            Ok(opener) => opener.skip_wal_replay(false),
57            Err(e) => {
58                error!(e; "Failed to build the reload of region {region_id}");
59                return;
60            }
61        };
62        let last_entry_id = region.version_control.current().last_entry_id;
63        info!("Reloading region {region_id}, last entry id: {last_entry_id}");
64        self.catchup_regions.insert_region(region_id);
65        let durability_barrier = self.wal.durability_barrier(region_id, &region.provider);
66        let wal = self.wal.clone();
67        let config = self.config.clone();
68        let sender = self.sender.clone();
69        common_runtime::spawn_global(async move {
70            let result = async {
71                // The fenced instance is stopped, but its last checkpoint may still be writing
72                // the manifest that the reload reads.
73                region.manifest_ctx.wait_for_checkpoint_after_stop().await;
74                // The replay reads only what the log store has made durable.
75                durability_barrier.wait(last_entry_id).await?;
76                opener.open(&config, &wal).await
77            }
78            .await;
79            let notify = BackgroundNotify::RegionReloaded {
80                old: region,
81                result,
82            };
83            let _ = sender
84                .send(WorkerRequestWithTime::new(WorkerRequest::Background {
85                    region_id,
86                    notify,
87                }))
88                .await;
89        });
90    }
91
92    /// Replaces the fenced instance with the reloaded one, unless the region was closed or
93    /// reopened during the reload. A failed reload leaves the fenced instance in place.
94    pub(crate) async fn handle_region_reloaded(
95        &mut self,
96        region_id: RegionId,
97        old: MitoRegionRef,
98        result: Result<MitoRegionRef>,
99    ) {
100        self.listener.on_region_reload_swap(region_id).await;
101        self.catchup_regions.remove_region(region_id);
102        let region = match result {
103            Ok(region) => region,
104            Err(e) => {
105                error!(e; "Failed to reload region {region_id}");
106                return;
107            }
108        };
109        let registered = self.regions.get_region(region_id);
110        if !registered.is_some_and(|registered| Arc::ptr_eq(&registered, &old)) {
111            info!("Region {region_id} changed during its reload, dropping the reloaded instance");
112            return;
113        }
114        // Preserve allocated sequences without publishing the old memtables.
115        region
116            .version_control
117            .update_last_sequence(old.version_control.current().last_sequence);
118        // Leases apply through the shared region map, so only those from heartbeats sent after
119        // the replacement may promote the new instance.
120        region.manifest_ctx.ignore_earlier_promotions();
121        // Requests waiting for the old instance are rejected as a close rejects them.
122        self.fail_region_stalled_requests_as_not_found(&region_id);
123        self.reject_region_requests_as_not_found(region_id);
124        self.register_region(region);
125        if let Some(state) = &self.series_index_task_state {
126            state.wake();
127        }
128        info!("Region {region_id} is reloaded");
129    }
130}
131
132/// Asks the worker to reload the region if a commit outside the worker fenced it. The caller
133/// must not hold the region's manifest lock, which the worker may wait for.
134pub(crate) async fn notify_if_fenced(sender: &Sender<WorkerRequestWithTime>, region: &MitoRegion) {
135    if region.manifest_ctx.is_reload_pending() {
136        let _ = sender
137            .send(WorkerRequestWithTime::new(WorkerRequest::Background {
138                region_id: region.region_id,
139                notify: BackgroundNotify::RegionFenced,
140            }))
141            .await;
142    }
143}