mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-29 22:24:02 +00:00
fix(repartition): pause source metadata compaction while syncing targets
Signed-off-by: WenyXu <wenymedia@gmail.com>
(cherry picked from commit 5e83bfeed6)
This commit is contained in:
@@ -1036,6 +1036,24 @@ impl Display for ApplyStagingManifest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies one attempt to sync a physical metric region's metadata.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct MetadataSyncAttempt {
|
||||
pub region_id: RegionId,
|
||||
pub attempt_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum MetadataCompaction {
|
||||
/// Wait for compaction to drain, then hold the pause for the remaining sync budget.
|
||||
Pause {
|
||||
attempt: MetadataSyncAttempt,
|
||||
remaining: Duration,
|
||||
},
|
||||
/// Drop only the pause acquired by this attempt.
|
||||
Release(MetadataSyncAttempt),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Display, PartialEq)]
|
||||
pub enum Instruction {
|
||||
/// Opens regions.
|
||||
@@ -1069,6 +1087,8 @@ pub enum Instruction {
|
||||
Suspend,
|
||||
/// Makes regions enter staging state.
|
||||
EnterStagingRegions(Vec<EnterStagingRegion>),
|
||||
/// Controls source metadata compaction during repartition.
|
||||
MetadataCompaction(MetadataCompaction),
|
||||
/// Syncs regions.
|
||||
SyncRegions(Vec<SyncRegion>),
|
||||
/// Remaps manifests for a region.
|
||||
@@ -1350,6 +1370,7 @@ pub enum InstructionReply {
|
||||
GetPackedFileRefs(GetPackedFileRefsReply),
|
||||
GcRegions(GcRegionsReply),
|
||||
EnterStagingRegions(EnterStagingRegionsReply),
|
||||
MetadataCompaction(SimpleReply),
|
||||
SyncRegions(SyncRegionsReply),
|
||||
RemapManifest(RemapManifestReply),
|
||||
ApplyStagingManifests(ApplyStagingManifestsReply),
|
||||
@@ -1379,6 +1400,9 @@ impl Display for InstructionReply {
|
||||
reply.replies
|
||||
)
|
||||
}
|
||||
Self::MetadataCompaction(reply) => {
|
||||
write!(f, "InstructionReply::MetadataCompaction({reply})")
|
||||
}
|
||||
Self::SyncRegions(reply) => {
|
||||
write!(f, "InstructionReply::SyncRegions({:?})", reply.replies)
|
||||
}
|
||||
@@ -1469,6 +1493,30 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_metadata_compaction_mailbox_wire() {
|
||||
let wire: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../../tests/compatibility/wire/metadata_compaction/instructions.json"
|
||||
))
|
||||
.unwrap();
|
||||
let attempt = MetadataSyncAttempt {
|
||||
region_id: RegionId::new(1, 2),
|
||||
attempt_id: "00112233-4455-6677-8899-aabbccddeeff".parse().unwrap(),
|
||||
};
|
||||
let expected = vec![
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Pause {
|
||||
attempt,
|
||||
remaining: Duration::from_millis(19_500),
|
||||
}),
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release(attempt)),
|
||||
];
|
||||
assert_eq!(
|
||||
expected,
|
||||
serde_json::from_value::<Vec<Instruction>>(wire.clone()).unwrap()
|
||||
);
|
||||
assert_eq!(wire, serde_json::to_value(expected).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_instruction_error_serde() {
|
||||
let error = InstructionError::new(
|
||||
|
||||
@@ -32,6 +32,7 @@ mod enter_staging;
|
||||
mod file_ref;
|
||||
mod flush_region;
|
||||
mod gc_worker;
|
||||
mod metadata_compaction;
|
||||
mod open_region;
|
||||
mod remap_manifest;
|
||||
mod sync_region;
|
||||
@@ -44,6 +45,7 @@ use crate::heartbeat::handler::enter_staging::EnterStagingRegionsHandler;
|
||||
use crate::heartbeat::handler::file_ref::{GetFileRefsHandler, GetPackedFileRefsHandler};
|
||||
use crate::heartbeat::handler::flush_region::FlushRegionsHandler;
|
||||
use crate::heartbeat::handler::gc_worker::{GcRegionsHandler, PackedGcRegionsHandler};
|
||||
use crate::heartbeat::handler::metadata_compaction::MetadataCompactionHandler;
|
||||
use crate::heartbeat::handler::open_region::OpenRegionsHandler;
|
||||
use crate::heartbeat::handler::remap_manifest::RemapManifestHandler;
|
||||
use crate::heartbeat::handler::sync_region::SyncRegionHandler;
|
||||
@@ -57,6 +59,7 @@ pub struct RegionHeartbeatResponseHandler {
|
||||
region_server: RegionServer,
|
||||
downgrade_tasks: TaskTracker<()>,
|
||||
flush_tasks: TaskTracker<()>,
|
||||
metadata_compaction: MetadataCompactionHandler,
|
||||
open_region_parallelism: usize,
|
||||
gc_tasks: TaskTracker<GcReport>,
|
||||
kv_backend: KvBackendRef,
|
||||
@@ -101,6 +104,7 @@ impl RegionHeartbeatResponseHandler {
|
||||
region_server,
|
||||
downgrade_tasks: TaskTracker::new(),
|
||||
flush_tasks: TaskTracker::new(),
|
||||
metadata_compaction: MetadataCompactionHandler::default(),
|
||||
// Default to half of the number of CPUs.
|
||||
open_region_parallelism: (num_cpus::get() / 2).max(1),
|
||||
gc_tasks: TaskTracker::new(),
|
||||
@@ -145,6 +149,9 @@ impl RegionHeartbeatResponseHandler {
|
||||
Instruction::EnterStagingRegions(_) => {
|
||||
Ok(Some(Box::new(EnterStagingRegionsHandler.into())))
|
||||
}
|
||||
Instruction::MetadataCompaction(_) => {
|
||||
Ok(Some(Box::new(self.metadata_compaction.clone().into())))
|
||||
}
|
||||
Instruction::SyncRegions(_) => Ok(Some(Box::new(SyncRegionHandler.into()))),
|
||||
Instruction::RemapManifest(_) => Ok(Some(Box::new(RemapManifestHandler.into()))),
|
||||
Instruction::ApplyStagingManifests(_) => {
|
||||
@@ -167,6 +174,7 @@ pub enum InstructionHandlers {
|
||||
GcRegions(GcRegionsHandler),
|
||||
PackedGcRegions(PackedGcRegionsHandler),
|
||||
EnterStagingRegions(EnterStagingRegionsHandler),
|
||||
MetadataCompaction(MetadataCompactionHandler),
|
||||
SyncRegions(SyncRegionHandler),
|
||||
RemapManifest(RemapManifestHandler),
|
||||
ApplyStagingManifests(ApplyStagingManifestsHandler),
|
||||
@@ -202,6 +210,7 @@ impl_from_handler!(
|
||||
GcRegionsHandler => GcRegions,
|
||||
PackedGcRegionsHandler => PackedGcRegions,
|
||||
EnterStagingRegionsHandler => EnterStagingRegions,
|
||||
MetadataCompactionHandler => MetadataCompaction,
|
||||
SyncRegionHandler => SyncRegions,
|
||||
RemapManifestHandler => RemapManifest,
|
||||
ApplyStagingManifestsHandler => ApplyStagingManifests
|
||||
@@ -252,6 +261,7 @@ dispatch_instr!(
|
||||
GcRegions => GcRegions,
|
||||
PackedGcRegions => PackedGcRegions,
|
||||
EnterStagingRegions => EnterStagingRegions,
|
||||
MetadataCompaction => MetadataCompaction,
|
||||
SyncRegions => SyncRegions,
|
||||
RemapManifest => RemapManifest,
|
||||
ApplyStagingManifests => ApplyStagingManifests,
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_meta::instruction::{
|
||||
InstructionError, InstructionReply, InstructionResult, MetadataCompaction, MetadataSyncAttempt,
|
||||
SimpleReply,
|
||||
};
|
||||
use metric_engine::engine::MetricEngine;
|
||||
use mito2::compaction::CompactionGuard;
|
||||
use tokio::sync::{OnceCell, oneshot};
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::heartbeat::handler::{HandlerContext, InstructionHandler};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MetadataCompactionHandler {
|
||||
leases: Arc<Mutex<HashMap<MetadataSyncAttempt, PauseLease>>>,
|
||||
}
|
||||
|
||||
struct PauseLease {
|
||||
deadline: Instant,
|
||||
guard: Arc<OnceCell<CompactionGuard>>,
|
||||
_cancel_expiry: oneshot::Sender<()>,
|
||||
}
|
||||
|
||||
impl MetadataCompactionHandler {
|
||||
fn lease(
|
||||
&self,
|
||||
attempt: MetadataSyncAttempt,
|
||||
deadline: Instant,
|
||||
) -> (Arc<OnceCell<CompactionGuard>>, Instant) {
|
||||
match self.leases.lock().unwrap().entry(attempt) {
|
||||
Entry::Occupied(entry) => (entry.get().guard.clone(), entry.get().deadline),
|
||||
Entry::Vacant(entry) => {
|
||||
let guard = Arc::new(OnceCell::new());
|
||||
let (cancel, cancelled) = oneshot::channel();
|
||||
entry.insert(PauseLease {
|
||||
deadline,
|
||||
guard: guard.clone(),
|
||||
_cancel_expiry: cancel,
|
||||
});
|
||||
let leases = Arc::downgrade(&self.leases);
|
||||
let expected = Arc::downgrade(&guard);
|
||||
common_runtime::spawn_global(async move {
|
||||
tokio::select! {
|
||||
_ = cancelled => (),
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
if let Some(leases) = leases.upgrade()
|
||||
&& let Entry::Occupied(entry) = leases.lock().unwrap().entry(attempt)
|
||||
&& expected.ptr_eq(&Arc::downgrade(&entry.get().guard))
|
||||
{
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
(guard, deadline)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pause(
|
||||
&self,
|
||||
ctx: &HandlerContext,
|
||||
attempt: MetadataSyncAttempt,
|
||||
remaining: std::time::Duration,
|
||||
) -> InstructionResult<()> {
|
||||
let deadline = Instant::now().checked_add(remaining).ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable("Invalid metadata sync deadline")
|
||||
})?;
|
||||
let region_id = attempt.region_id;
|
||||
let engine = ctx
|
||||
.region_server
|
||||
.find_engine(region_id)
|
||||
.map_err(|e| InstructionError::from_error(&e))?
|
||||
.ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is unavailable"
|
||||
))
|
||||
})?;
|
||||
let metric = engine
|
||||
.as_any()
|
||||
.downcast_ref::<MetricEngine>()
|
||||
.ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is not a metric region"
|
||||
))
|
||||
})?;
|
||||
if ctx.region_server.is_region_leader(region_id) != Some(true) {
|
||||
return Err(InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is not writable"
|
||||
)));
|
||||
}
|
||||
let (lease, deadline) = self.lease(attempt, deadline);
|
||||
tokio::time::timeout_at(
|
||||
deadline,
|
||||
lease.get_or_try_init(|| metric.pause_metadata_compaction(region_id)),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
InstructionError::legacy_internal_retryable(
|
||||
"Timed out pausing source metadata compaction",
|
||||
)
|
||||
})?
|
||||
.map_err(|e| InstructionError::from_error(&e))?;
|
||||
if Instant::now() >= deadline || ctx.region_server.is_region_leader(region_id) != Some(true)
|
||||
{
|
||||
return Err(InstructionError::legacy_internal_retryable(
|
||||
"Source metadata compaction lease expired or leadership changed",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl InstructionHandler for MetadataCompactionHandler {
|
||||
type Instruction = MetadataCompaction;
|
||||
|
||||
async fn handle(
|
||||
&self,
|
||||
ctx: &HandlerContext,
|
||||
instruction: MetadataCompaction,
|
||||
) -> Option<InstructionReply> {
|
||||
match instruction {
|
||||
MetadataCompaction::Pause { attempt, remaining } => {
|
||||
let result = self.pause(ctx, attempt, remaining).await;
|
||||
Some(InstructionReply::MetadataCompaction(SimpleReply {
|
||||
result: result.is_ok(),
|
||||
error: result.err(),
|
||||
}))
|
||||
}
|
||||
MetadataCompaction::Release(attempt) => {
|
||||
self.leases.lock().unwrap().remove(&attempt);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use mito2::test_util::{CreateRequestBuilder, TestEnv};
|
||||
use store_api::metric_engine_consts::{
|
||||
METRIC_ENGINE_NAME, METRIC_METADATA_REGION_GROUP, PHYSICAL_TABLE_METADATA_KEY,
|
||||
};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use super::*;
|
||||
use crate::tests::mock_region_server;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_pause_is_attempt_scoped_and_expires() {
|
||||
let mut env = TestEnv::with_prefix("metadata-compaction-lease").await;
|
||||
let mito = env.create_engine(Default::default()).await;
|
||||
let mut server = mock_region_server();
|
||||
let metric = MetricEngine::try_new(mito.clone(), Default::default()).unwrap();
|
||||
server.register_engine(Arc::new(metric));
|
||||
let region_id = RegionId::new(32, 1);
|
||||
let mut create = CreateRequestBuilder::new()
|
||||
.tag_num(0)
|
||||
.insert_option(PHYSICAL_TABLE_METADATA_KEY, "")
|
||||
.build();
|
||||
create.engine = METRIC_ENGINE_NAME.to_string();
|
||||
create.column_metadatas[0].column_schema.name = "greptime_value".into();
|
||||
create.column_metadatas[1].column_schema.name = "greptime_timestamp".into();
|
||||
server
|
||||
.handle_request(region_id, RegionRequest::Create(create))
|
||||
.await
|
||||
.unwrap();
|
||||
let ctx = HandlerContext::new_for_test(server, Arc::new(MemoryKvBackend::new()));
|
||||
let handler = MetadataCompactionHandler::default();
|
||||
let first = MetadataSyncAttempt {
|
||||
region_id,
|
||||
attempt_id: "00000000-0000-0000-0000-000000000001".parse().unwrap(),
|
||||
};
|
||||
let second = MetadataSyncAttempt {
|
||||
region_id,
|
||||
attempt_id: "00000000-0000-0000-0000-000000000002".parse().unwrap(),
|
||||
};
|
||||
for attempt in [first, first, second] {
|
||||
handler
|
||||
.pause(&ctx, attempt, Duration::from_secs(60))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for _ in 0..2 {
|
||||
handler
|
||||
.handle(&ctx, MetadataCompaction::Release(first))
|
||||
.await;
|
||||
}
|
||||
let meta = RegionId::with_group_and_seq(32, METRIC_METADATA_REGION_GROUP, 1);
|
||||
let compact = || mito.handle_request(meta, RegionRequest::Compact(Default::default()));
|
||||
let err = compact().await.unwrap_err();
|
||||
assert!(matches!(
|
||||
err.into_inner()
|
||||
.as_any()
|
||||
.downcast_ref::<mito2::error::Error>(),
|
||||
Some(mito2::error::Error::CompactionCancelled { .. })
|
||||
));
|
||||
mito.handle_request(region_id, RegionRequest::Compact(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
mito.handle_request(meta, RegionRequest::Flush(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
handler
|
||||
.handle(&ctx, MetadataCompaction::Release(second))
|
||||
.await;
|
||||
compact().await.unwrap();
|
||||
handler
|
||||
.pause(&ctx, first, Duration::from_millis(200))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(compact().await.is_err());
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while handler.leases.lock().unwrap().contains_key(&first) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
compact().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,19 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use api::v1::meta::MailboxMessage;
|
||||
use common_meta::instruction::{Instruction, InstructionReply, SyncRegionReply, SyncRegionsReply};
|
||||
use common_meta::instruction::{
|
||||
Instruction, InstructionReply, MetadataCompaction, MetadataSyncAttempt, SyncRegionReply,
|
||||
SyncRegionsReply,
|
||||
};
|
||||
use common_meta::peer::Peer;
|
||||
use common_meta::rpc::router::RegionRoute;
|
||||
use common_procedure::{Context as ProcedureContext, Status};
|
||||
use common_telemetry::info;
|
||||
use common_telemetry::tracing_context::TracingContext;
|
||||
use common_telemetry::{info, warn};
|
||||
use futures::future::join_all;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
@@ -57,7 +60,7 @@ impl State for SyncRegion {
|
||||
_procedure_ctx: &ProcedureContext,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
Self::flush_central_region(ctx).await?;
|
||||
self.sync_regions(ctx).await?;
|
||||
self.sync_with_paused_source(ctx).await?;
|
||||
|
||||
Ok((
|
||||
Box::new(UpdateMetadata::ApplyStaging),
|
||||
@@ -91,6 +94,75 @@ impl SyncRegion {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn sync_with_paused_source(&self, ctx: &mut Context) -> Result<()> {
|
||||
let prepare = ctx.persistent_ctx.group_prepare_result.as_ref().unwrap();
|
||||
let source = prepare.central_region_datanode.clone();
|
||||
let attempt = MetadataSyncAttempt {
|
||||
region_id: prepare.central_region,
|
||||
attempt_id: uuid::Uuid::new_v4(),
|
||||
};
|
||||
let remaining = ctx
|
||||
.next_operation_timeout()
|
||||
.context(error::ExceededDeadlineSnafu {
|
||||
operation: "Pause source metadata compaction",
|
||||
})?;
|
||||
let pause =
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Pause { attempt, remaining });
|
||||
let reply =
|
||||
Self::request(&ctx.mailbox, &ctx.server_addr, &source, pause, remaining).await?;
|
||||
let InstructionReply::MetadataCompaction(reply) = reply else {
|
||||
return error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: reply.to_string(),
|
||||
reason: "expected source metadata compaction pause acknowledgement",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
if let Some(err) = reply.error {
|
||||
return instruction_error_result(
|
||||
&err,
|
||||
format!(
|
||||
"Failed to pause compaction for {}: {}",
|
||||
attempt.region_id, err.message
|
||||
),
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
reply.result,
|
||||
error::RetryLaterSnafu {
|
||||
reason: format!(
|
||||
"Source {} did not confirm metadata compaction pause",
|
||||
attempt.region_id
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
// A lost reply may leave a target copying. The source releases its guard
|
||||
// at the deadline if we cannot confirm that every target finished.
|
||||
let mut all_replied = true;
|
||||
let result = self.sync_regions(ctx, &mut all_replied).await;
|
||||
if all_replied {
|
||||
let release = Instruction::MetadataCompaction(MetadataCompaction::Release(attempt));
|
||||
if let Err(err) = Self::release_source(ctx, &source, release).await {
|
||||
warn!(err; "Failed to release source metadata compaction for {attempt:?}");
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn release_source(ctx: &Context, source: &Peer, release: Instruction) -> Result<()> {
|
||||
let msg = Self::message(&ctx.server_addr, source, &release)?;
|
||||
let channel = Channel::Datanode(source.id);
|
||||
tokio::time::timeout(
|
||||
ctx.next_operation_timeout().unwrap_or_default(),
|
||||
ctx.mailbox.send_oneway(&channel, msg),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.context(error::ExceededDeadlineSnafu {
|
||||
operation: "Release source metadata compaction",
|
||||
})?
|
||||
}
|
||||
|
||||
/// Builds instructions to sync regions on datanodes.
|
||||
fn build_sync_region_instructions(
|
||||
central_region: RegionId,
|
||||
@@ -117,7 +189,7 @@ impl SyncRegion {
|
||||
}
|
||||
|
||||
/// Syncs regions on datanodes.
|
||||
async fn sync_regions(&self, ctx: &mut Context) -> Result<()> {
|
||||
async fn sync_regions(&self, ctx: &mut Context, all_replied: &mut bool) -> Result<()> {
|
||||
let table_id = ctx.persistent_ctx.table_id;
|
||||
let prepare_result = ctx.persistent_ctx.group_prepare_result.as_ref().unwrap();
|
||||
let instructions = Self::build_sync_region_instructions(
|
||||
@@ -135,11 +207,11 @@ impl SyncRegion {
|
||||
.map(|(peer, sync_regions)| {
|
||||
(
|
||||
peer,
|
||||
Self::sync_region(
|
||||
Self::request(
|
||||
&ctx.mailbox,
|
||||
&ctx.server_addr,
|
||||
peer,
|
||||
sync_regions,
|
||||
Instruction::SyncRegions(sync_regions.clone()),
|
||||
operation_timeout,
|
||||
),
|
||||
)
|
||||
@@ -159,7 +231,33 @@ impl SyncRegion {
|
||||
)
|
||||
};
|
||||
|
||||
let results = join_all(tasks).await;
|
||||
let now = Instant::now();
|
||||
let replies = join_all(tasks).await;
|
||||
let results = replies
|
||||
.into_iter()
|
||||
.zip(&peers)
|
||||
.map(|(reply, peer)| match reply {
|
||||
Ok(InstructionReply::SyncRegions(SyncRegionsReply { replies }))
|
||||
if Self::received_all(&instructions[*peer], &replies) =>
|
||||
{
|
||||
replies
|
||||
.iter()
|
||||
.try_for_each(|reply| Self::handle_sync_region_reply(reply, &now, peer))
|
||||
}
|
||||
Ok(reply) => {
|
||||
*all_replied = false;
|
||||
error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: reply.to_string(),
|
||||
reason: "expected replies from all requested sync regions",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
Err(err) => {
|
||||
*all_replied = false;
|
||||
Err(err)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let result = handle_multiple_results(&results);
|
||||
|
||||
match result {
|
||||
@@ -211,32 +309,33 @@ impl SyncRegion {
|
||||
}
|
||||
}
|
||||
|
||||
/// Syncs regions on a datanode.
|
||||
async fn sync_region(
|
||||
mailbox: &MailboxRef,
|
||||
fn message(
|
||||
server_addr: &str,
|
||||
peer: &Peer,
|
||||
sync_regions: &[common_meta::instruction::SyncRegion],
|
||||
timeout: Duration,
|
||||
) -> Result<()> {
|
||||
let ch = Channel::Datanode(peer.id);
|
||||
let instruction = Instruction::SyncRegions(sync_regions.to_vec());
|
||||
let tracing_ctx = TracingContext::from_current_span();
|
||||
let message = MailboxMessage::json_message(
|
||||
&format!(
|
||||
"Sync regions: {:?}",
|
||||
sync_regions.iter().map(|r| r.region_id).collect::<Vec<_>>()
|
||||
),
|
||||
&format!("Metasrv@{}", server_addr),
|
||||
instruction: &Instruction,
|
||||
) -> Result<MailboxMessage> {
|
||||
MailboxMessage::json_message(
|
||||
&instruction.to_string(),
|
||||
&format!("Metasrv@{server_addr}"),
|
||||
&format!("Datanode-{}@{}", peer.id, peer.addr),
|
||||
common_time::util::current_time_millis(),
|
||||
&instruction,
|
||||
Some(tracing_ctx.to_w3c()),
|
||||
instruction,
|
||||
Some(TracingContext::from_current_span().to_w3c()),
|
||||
)
|
||||
.with_context(|_| error::SerializeToJsonSnafu {
|
||||
input: instruction.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
async fn request(
|
||||
mailbox: &MailboxRef,
|
||||
server_addr: &str,
|
||||
peer: &Peer,
|
||||
instruction: Instruction,
|
||||
timeout: Duration,
|
||||
) -> Result<InstructionReply> {
|
||||
let ch = Channel::Datanode(peer.id);
|
||||
let message = Self::message(server_addr, peer, &instruction)?;
|
||||
let now = std::time::Instant::now();
|
||||
let receiver = mailbox.send(&ch, message, timeout).await;
|
||||
|
||||
@@ -256,25 +355,7 @@ impl SyncRegion {
|
||||
};
|
||||
|
||||
match receiver.await {
|
||||
Ok(msg) => {
|
||||
let reply = HeartbeatMailbox::json_reply(&msg)?;
|
||||
info!(
|
||||
"Received sync regions reply: {:?}, elapsed: {:?}",
|
||||
reply,
|
||||
now.elapsed()
|
||||
);
|
||||
let InstructionReply::SyncRegions(SyncRegionsReply { replies }) = reply else {
|
||||
return error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: msg.to_string(),
|
||||
reason: "expect sync regions reply",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
for reply in replies {
|
||||
Self::handle_sync_region_reply(&reply, &now, peer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(msg) => HeartbeatMailbox::json_reply(&msg),
|
||||
Err(error::Error::MailboxChannelClosed { .. }) => error::RetryLaterSnafu {
|
||||
reason: format!(
|
||||
"Mailbox closed when sending sync region to datanode {:?}, elapsed: {:?}",
|
||||
@@ -295,6 +376,19 @@ impl SyncRegion {
|
||||
}
|
||||
}
|
||||
|
||||
fn received_all(
|
||||
requests: &[common_meta::instruction::SyncRegion],
|
||||
replies: &[SyncRegionReply],
|
||||
) -> bool {
|
||||
if requests.len() != replies.len() {
|
||||
return false;
|
||||
}
|
||||
let ids: HashSet<_> = replies.iter().map(|reply| reply.region_id).collect();
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| ids.contains(&request.region_id))
|
||||
}
|
||||
|
||||
fn handle_sync_region_reply(
|
||||
SyncRegionReply {
|
||||
region_id,
|
||||
@@ -404,6 +498,123 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_source_pause_release_follows_target_reply() {
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::handler::HeartbeatMailbox;
|
||||
use common_meta::instruction::{
|
||||
Instruction, InstructionReply, MetadataCompaction, SimpleReply,
|
||||
};
|
||||
|
||||
for outcome in ["success", "region_error", "lost_reply", "pause_rejected"] {
|
||||
let mut env = TestingEnv::new();
|
||||
let mut persistent = new_persistent_context(1024, vec![], vec![]);
|
||||
persistent.group_prepare_result = Some(test_prepare_result(1024));
|
||||
let budget = persistent.timeout;
|
||||
let (source_tx, mut source_rx) = tokio::sync::mpsc::channel(2);
|
||||
let (target_tx, mut target_rx) = tokio::sync::mpsc::channel(1);
|
||||
env.mailbox_ctx
|
||||
.insert_heartbeat_response_receiver(Channel::Datanode(1), source_tx)
|
||||
.await;
|
||||
env.mailbox_ctx
|
||||
.insert_heartbeat_response_receiver(Channel::Datanode(2), target_tx)
|
||||
.await;
|
||||
let mut ctx = env.create_context(persistent);
|
||||
let mailbox = ctx.mailbox.clone();
|
||||
let target = RegionId::new(1024, 3);
|
||||
let sync = SyncRegion {
|
||||
region_routes: vec![RegionRoute {
|
||||
region: Region {
|
||||
id: target,
|
||||
..Default::default()
|
||||
},
|
||||
leader_peer: Some(Peer::empty(2)),
|
||||
..Default::default()
|
||||
}],
|
||||
};
|
||||
let peers = async {
|
||||
let msg = source_rx
|
||||
.recv()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
let Instruction::MetadataCompaction(MetadataCompaction::Pause {
|
||||
attempt,
|
||||
remaining,
|
||||
}) = HeartbeatMailbox::json_instruction(&msg).unwrap()
|
||||
else {
|
||||
panic!("expected pause")
|
||||
};
|
||||
assert_eq!(attempt.region_id, RegionId::new(1024, 1));
|
||||
assert!(remaining > Duration::ZERO && remaining <= budget);
|
||||
assert!(target_rx.try_recv().is_err());
|
||||
let mut ack = msg.clone();
|
||||
ack.payload = Some(api::v1::meta::mailbox_message::Payload::Json(
|
||||
serde_json::to_string(&InstructionReply::MetadataCompaction(SimpleReply {
|
||||
result: outcome != "pause_rejected",
|
||||
error: None,
|
||||
}))
|
||||
.unwrap(),
|
||||
));
|
||||
mailbox.on_recv(msg.id, Ok(ack)).await.unwrap();
|
||||
if outcome == "pause_rejected" {
|
||||
return attempt;
|
||||
}
|
||||
let msg = target_rx
|
||||
.recv()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
HeartbeatMailbox::json_instruction(&msg).unwrap(),
|
||||
Instruction::SyncRegions(_)
|
||||
));
|
||||
assert!(source_rx.try_recv().is_err());
|
||||
let reply = match outcome {
|
||||
"lost_reply" => crate::error::MailboxTimeoutSnafu { id: msg.id }.fail(),
|
||||
"region_error" => Ok(new_sync_region_reply(
|
||||
msg.id,
|
||||
target,
|
||||
false,
|
||||
true,
|
||||
Some("sync failed".into()),
|
||||
)),
|
||||
_ => Ok(new_sync_region_reply(msg.id, target, true, true, None)),
|
||||
};
|
||||
mailbox.on_recv(msg.id, reply).await.unwrap();
|
||||
attempt
|
||||
};
|
||||
let (attempt, result) = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
tokio::join!(peers, sync.sync_with_paused_source(&mut ctx))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.is_ok(), outcome == "success");
|
||||
if outcome == "pause_rejected" {
|
||||
assert!(target_rx.try_recv().is_err());
|
||||
}
|
||||
if matches!(outcome, "lost_reply" | "pause_rejected") {
|
||||
assert!(source_rx.try_recv().is_err());
|
||||
} else {
|
||||
let msg = source_rx
|
||||
.try_recv()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
HeartbeatMailbox::json_instruction(&msg).unwrap(),
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release(attempt))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sync_regions_all_successful() {
|
||||
let mut env = TestingEnv::new();
|
||||
@@ -436,7 +647,7 @@ mod tests {
|
||||
}];
|
||||
let sync_region = SyncRegion { region_routes };
|
||||
|
||||
sync_region.sync_regions(&mut ctx).await.unwrap();
|
||||
sync_region.sync_regions(&mut ctx, &mut true).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -457,7 +668,10 @@ mod tests {
|
||||
}];
|
||||
let sync_region = SyncRegion { region_routes };
|
||||
|
||||
let err = sync_region.sync_regions(&mut ctx).await.unwrap_err();
|
||||
let err = sync_region
|
||||
.sync_regions(&mut ctx, &mut true)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_matches!(err, Error::RetryLater { .. });
|
||||
}
|
||||
|
||||
@@ -499,7 +713,10 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
|
||||
let err = sync_region.sync_regions(&mut ctx).await.unwrap_err();
|
||||
let err = sync_region
|
||||
.sync_regions(&mut ctx, &mut true)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_matches!(err, Error::RetryLater { .. });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,6 +566,17 @@ pub struct PutGroupResult {
|
||||
}
|
||||
|
||||
impl MetricEngine {
|
||||
/// Pauses compaction on the metadata half of a physical metric region.
|
||||
pub async fn pause_metadata_compaction(
|
||||
&self,
|
||||
physical_region: RegionId,
|
||||
) -> mito2::error::Result<mito2::compaction::CompactionGuard> {
|
||||
self.inner
|
||||
.mito
|
||||
.pause_compaction(crate::utils::to_metadata_region_id(physical_region))
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn try_new(mito: MitoEngine, mut config: EngineConfig) -> Result<Self> {
|
||||
let metadata_region = MetadataRegion::new(mito.clone());
|
||||
let data_region = DataRegion::new(mito.clone());
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
[
|
||||
{"MetadataCompaction":{"Pause":{"attempt":{"region_id":4294967298,"attempt_id":"00112233-4455-6677-8899-aabbccddeeff"},"remaining":{"secs":19,"nanos":500000000}}}},
|
||||
{"MetadataCompaction":{"Release":{"region_id":4294967298,"attempt_id":"00112233-4455-6677-8899-aabbccddeeff"}}}
|
||||
]
|
||||
Reference in New Issue
Block a user