mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
fix(meta): invalidate all datanode tables on address change (#9986)
When a datanode restarts with a new address, metasrv invalidated cached
table routes only for the tables in that heartbeat's region stats. The
first heartbeat after a restart often reports few or no regions (e.g.
with init_regions_in_background), so frontends kept dialing the old
address until metadata_cache_ttl expired.
Read the previous address via prev_kv when saving it, and when it
changed (or a failed save of the same epoch is retried) invalidate
every table registered for the datanode in __dn_table.
Signed-off-by: Floris Smit <florissmit10@gmail.com>
Co-authored-by: Weny Xu <wenymedia@gmail.com>
(cherry picked from commit 351f4207b4)
Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
@@ -43,6 +43,8 @@ abstraction, election, key encoding, and the DDL manager live in `common-meta`;
|
||||
`handler/utils.rs` for per-node address persistence. Datanode address
|
||||
updates retain the statistics handler's per-node ordering. Address epochs are
|
||||
confirmed only after a successful save; cache invalidation remains best effort.
|
||||
A changed datanode address invalidates every table on that node (`__dn_table`),
|
||||
not only the tables in the current heartbeat.
|
||||
- **Datanode process fence**: before the handler chain, the leader's heartbeat
|
||||
session checks a datanode request's non-zero `node_epoch` against the highest
|
||||
one recorded under `__datanode_epoch`, read and raised through the leader
|
||||
|
||||
@@ -16,14 +16,17 @@ use std::cmp::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::meta::{HeartbeatRequest, Peer, Role};
|
||||
use common_meta::DatanodeId;
|
||||
use common_meta::datanode::{DatanodeStatKey, DatanodeStatValue, Stat};
|
||||
use common_meta::instruction::CacheIdent;
|
||||
use common_meta::key::MetadataKey;
|
||||
use common_meta::key::node_address::NodeAddressKey;
|
||||
use common_meta::key::node_address::{NodeAddressKey, NodeAddressValue};
|
||||
use common_meta::rpc::store::PutRequest;
|
||||
use common_telemetry::{error, warn};
|
||||
use dashmap::DashMap;
|
||||
use futures::TryStreamExt;
|
||||
use snafu::ResultExt;
|
||||
use store_api::storage::TableId;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::error::{self, Result};
|
||||
@@ -196,14 +199,43 @@ async fn update_datanode_address(updater: &NodeAddressUpdater, ctx: &Context, st
|
||||
.inspect_err(|e| {
|
||||
error!(e; "Failed to update datanode address, node: {}, address: {}", stat.id, stat.addr);
|
||||
});
|
||||
if let Ok(true) = updated {
|
||||
let cache_idents = stat
|
||||
.table_ids()
|
||||
.into_iter()
|
||||
.map(CacheIdent::TableId)
|
||||
.collect::<Vec<_>>();
|
||||
utils::invalidate_address_caches(ctx, stat.id, &cache_idents).await;
|
||||
let Ok(Some(saved)) = updated else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut table_ids = stat.table_ids();
|
||||
// Cached table routes embed the address, and a restarted datanode's first
|
||||
// heartbeat may report few regions, so invalidate every table on the node.
|
||||
// A failed earlier attempt may already have stored the new address, which
|
||||
// hides the change from this save.
|
||||
if saved.retried || address_changed(saved.output.as_ref(), &stat.addr) {
|
||||
match datanode_table_ids(ctx, stat.id).await {
|
||||
Ok(ids) => table_ids.extend(ids),
|
||||
Err(e) => {
|
||||
error!(e; "Failed to list tables of datanode {} for address invalidation", stat.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
let cache_idents = table_ids
|
||||
.into_iter()
|
||||
.map(CacheIdent::TableId)
|
||||
.collect::<Vec<_>>();
|
||||
utils::invalidate_address_caches(ctx, stat.id, &cache_idents).await;
|
||||
}
|
||||
|
||||
/// A missing or undecodable previous address counts as changed.
|
||||
fn address_changed(previous: Option<&NodeAddressValue>, addr: &str) -> bool {
|
||||
previous.is_none_or(|previous| previous.peer.addr != addr)
|
||||
}
|
||||
|
||||
async fn datanode_table_ids(ctx: &Context, datanode_id: DatanodeId) -> Result<Vec<TableId>> {
|
||||
ctx.table_metadata_manager
|
||||
.datanode_table_manager()
|
||||
.tables(datanode_id)
|
||||
.map_ok(|value| value.table_id)
|
||||
.try_collect()
|
||||
.await
|
||||
.context(error::TableMetadataManagerSnafu)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -214,8 +246,11 @@ mod tests {
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use common_meta::cache_invalidator::{CacheInvalidator, Context as InvalidationContext};
|
||||
use common_meta::datanode::DatanodeStatKey;
|
||||
use common_meta::error::{Error as MetaError, Result as MetaResult};
|
||||
use common_meta::key::datanode_table::{DatanodeTableKey, DatanodeTableValue, RegionInfo};
|
||||
use common_meta::key::{MetadataValue, RegionRoleSet};
|
||||
use common_meta::kv_backend::{KvBackend, KvBackendRef, ResettableKvBackend, TxnService};
|
||||
use common_meta::rpc::store::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse,
|
||||
@@ -537,6 +572,168 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingCacheInvalidator {
|
||||
calls: StdMutex<Vec<Vec<CacheIdent>>>,
|
||||
}
|
||||
|
||||
impl RecordingCacheInvalidator {
|
||||
fn table_ids_per_call(&self) -> Vec<Vec<TableId>> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|idents| {
|
||||
let mut ids = idents
|
||||
.iter()
|
||||
.map(|ident| match ident {
|
||||
CacheIdent::TableId(id) => *id,
|
||||
other => panic!("unexpected cache ident: {other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl CacheInvalidator for RecordingCacheInvalidator {
|
||||
async fn invalidate(
|
||||
&self,
|
||||
_: &InvalidationContext,
|
||||
idents: &[CacheIdent],
|
||||
) -> MetaResult<()> {
|
||||
self.calls.lock().unwrap().push(idents.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalidate_all(&self) -> MetaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn register_datanode_tables(ctx: &Context, datanode_id: u64, table_ids: &[TableId]) {
|
||||
for table_id in table_ids {
|
||||
let value = DatanodeTableValue::new(
|
||||
*table_id,
|
||||
RegionRoleSet::new(vec![0], vec![]),
|
||||
RegionInfo::default(),
|
||||
);
|
||||
ctx.kv_backend
|
||||
.put(PutRequest {
|
||||
key: DatanodeTableKey::new(datanode_id, *table_id).to_bytes(),
|
||||
value: value.try_as_raw_value().unwrap(),
|
||||
prev_kv: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn use_recording_invalidator(ctx: &mut Context) -> Arc<RecordingCacheInvalidator> {
|
||||
let invalidator = Arc::new(RecordingCacheInvalidator::default());
|
||||
ctx.cache_invalidator = invalidator.clone();
|
||||
invalidator
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_address_change_invalidates_all_tables_on_datanode() {
|
||||
let mut ctx = TestEnv::new().ctx();
|
||||
let invalidator = use_recording_invalidator(&mut ctx);
|
||||
register_datanode_tables(&ctx, 101, &[1024, 1025]).await;
|
||||
register_datanode_tables(&ctx, 102, &[2048]).await;
|
||||
let handler = Arc::new(CollectStatsHandler::default());
|
||||
|
||||
handle_stat(handler.clone(), ctx.clone(), stat(101, 1, 0, "dn-101-v1"))
|
||||
.await
|
||||
.unwrap();
|
||||
// Restarted on a new address, reporting no regions yet.
|
||||
handle_stat(handler.clone(), ctx.clone(), stat(101, 2, 0, "dn-101-v2"))
|
||||
.await
|
||||
.unwrap();
|
||||
handle_stat(handler, ctx, stat(101, 2, 0, "dn-101-v2"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
vec![vec![1024, 1025], vec![1024, 1025]],
|
||||
invalidator.table_ids_per_call()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_unchanged_address_only_invalidates_reported_tables() {
|
||||
let mut ctx = TestEnv::new().ctx();
|
||||
register_datanode_tables(&ctx, 101, &[1024, 1025]).await;
|
||||
let handler = Arc::new(CollectStatsHandler::default());
|
||||
handle_stat(handler, ctx.clone(), stat(101, 1, 0, "dn-101"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A fresh handler sees the node as after a metasrv leader change.
|
||||
let invalidator = use_recording_invalidator(&mut ctx);
|
||||
let handler = Arc::new(CollectStatsHandler::default());
|
||||
handle_stat(handler.clone(), ctx.clone(), stat(101, 1, 0, "dn-101"))
|
||||
.await
|
||||
.unwrap();
|
||||
handle_stat(handler, ctx, stat(101, 2, 0, "dn-101"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
vec![Vec::<TableId>::new(), vec![]],
|
||||
invalidator.table_ids_per_call()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_retry_after_landed_write_invalidates_all_tables_on_datanode() {
|
||||
use common_meta::kv_backend::test_util::MockKvBackendBuilder;
|
||||
use common_meta::rpc::KeyValue;
|
||||
|
||||
let mut ctx = TestEnv::new().ctx();
|
||||
let invalidator = use_recording_invalidator(&mut ctx);
|
||||
register_datanode_tables(&ctx, 101, &[1024, 1025]).await;
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let backend = MockKvBackendBuilder::default()
|
||||
.put_fn(Arc::new({
|
||||
let attempts = attempts.clone();
|
||||
move |req: PutRequest| {
|
||||
// The first write lands but reports an error, so the retry
|
||||
// reads back its own address as the previous one.
|
||||
if attempts.fetch_add(1, AtomicOrdering::Relaxed) == 0 {
|
||||
return common_meta::error::UnexpectedSnafu {
|
||||
err_msg: "injected lost response",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
Ok(PutResponse {
|
||||
prev_kv: Some(KeyValue {
|
||||
key: req.key,
|
||||
value: req.value,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}) as _)
|
||||
.build()
|
||||
.unwrap();
|
||||
ctx.leader_cached_kv_backend =
|
||||
Arc::new(LeaderCachedKvBackend::with_always_leader(Arc::new(backend)));
|
||||
let handler = Arc::new(CollectStatsHandler::default());
|
||||
|
||||
handle_stat(handler.clone(), ctx.clone(), stat(101, 2, 0, "dn-101-v2"))
|
||||
.await
|
||||
.unwrap();
|
||||
handle_stat(handler, ctx, stat(101, 2, 0, "dn-101-v2"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(2, attempts.load(AtomicOrdering::Relaxed));
|
||||
assert_eq!(vec![vec![1024, 1025]], invalidator.table_ids_per_call());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_persistence_failure_retries_but_notification_failure_does_not() {
|
||||
use crate::handler::collect_stats_handler::CollectStatsHandler;
|
||||
|
||||
@@ -54,7 +54,7 @@ impl HeartbeatHandler for RemapFlowPeerHandler {
|
||||
// Address errors must not prevent later heartbeat handlers from running.
|
||||
error!(e; "Failed to update flownode address, peer: {:?}", peer);
|
||||
});
|
||||
if let Ok(true) = updated {
|
||||
if let Ok(Some(_)) = updated {
|
||||
let cache_idents = [CacheIdent::FlowNodeAddressChange(peer.id)];
|
||||
utils::invalidate_address_caches(ctx, peer.id, &cache_idents).await;
|
||||
}
|
||||
|
||||
@@ -44,19 +44,27 @@ struct NodeAddressEpochs {
|
||||
saved_epoch: Option<u64>,
|
||||
}
|
||||
|
||||
/// The outcome of a successful address save.
|
||||
pub(crate) struct SavedAddress<T> {
|
||||
pub(crate) output: T,
|
||||
/// An earlier save of this epoch failed or was cancelled, but its write
|
||||
/// may still have reached the store.
|
||||
pub(crate) retried: bool,
|
||||
}
|
||||
|
||||
impl NodeAddressUpdater {
|
||||
/// Saves a new or previously failed epoch. Returns true only when this call
|
||||
/// saved the address, or false when the heartbeat is stale or already saved.
|
||||
/// Saves a new or previously failed epoch. Returns `None` when the
|
||||
/// heartbeat is stale or already saved.
|
||||
/// Cache invalidation is separate and does not affect acknowledgement.
|
||||
pub(crate) async fn update_if_needed<F, Fut>(
|
||||
pub(crate) async fn update_if_needed<T, F, Fut>(
|
||||
&self,
|
||||
node: (Role, u64),
|
||||
epoch: u64,
|
||||
save: F,
|
||||
) -> Result<bool>
|
||||
) -> Result<Option<SavedAddress<T>>>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<()>>,
|
||||
Fut: Future<Output = Result<T>>,
|
||||
{
|
||||
// Never retain a DashMap guard across await, even while waiting for a
|
||||
// different node: its entry may live in the same shard.
|
||||
@@ -66,34 +74,43 @@ impl NodeAddressUpdater {
|
||||
};
|
||||
let mut state = state.lock().await;
|
||||
if state.seen_epoch.is_some_and(|seen| epoch < seen) || state.saved_epoch == Some(epoch) {
|
||||
return Ok(false);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Seeing an epoch rejects stale heartbeats, but only a successful save
|
||||
// suppresses retries of that same epoch. Cancellation also leaves it retryable.
|
||||
let retried = state.seen_epoch == Some(epoch);
|
||||
state.seen_epoch = Some(epoch);
|
||||
save().await?;
|
||||
let output = save().await?;
|
||||
state.saved_epoch = Some(epoch);
|
||||
Ok(true)
|
||||
Ok(Some(SavedAddress { output, retried }))
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists an address through the leader cache.
|
||||
pub(crate) async fn save_node_address(ctx: &Context, key: Vec<u8>, peer: Peer) -> Result<()> {
|
||||
/// Persists an address through the leader cache and returns the one it
|
||||
/// replaced, treating an undecodable value as absent.
|
||||
pub(crate) async fn save_node_address(
|
||||
ctx: &Context,
|
||||
key: Vec<u8>,
|
||||
peer: Peer,
|
||||
) -> Result<Option<NodeAddressValue>> {
|
||||
let address = NodeAddressValue::new(peer);
|
||||
let value = address
|
||||
.try_as_raw_value()
|
||||
.context(InvalidNodeInfoFormatSnafu)?;
|
||||
ctx.leader_cached_kv_backend
|
||||
let resp = ctx
|
||||
.leader_cached_kv_backend
|
||||
.put(PutRequest {
|
||||
key,
|
||||
value,
|
||||
prev_kv: false,
|
||||
prev_kv: true,
|
||||
})
|
||||
.await
|
||||
.context(KvBackendSnafu)?;
|
||||
info!("Successfully updated node address: {:?}", address.peer);
|
||||
Ok(())
|
||||
Ok(resp
|
||||
.prev_kv
|
||||
.and_then(|kv| NodeAddressValue::try_from_raw_value(&kv.value).ok()))
|
||||
}
|
||||
|
||||
/// Preserves the existing best-effort notification behavior. Notification
|
||||
@@ -127,7 +144,7 @@ mod tests {
|
||||
let key = (Role::Datanode, 1);
|
||||
assert!(
|
||||
updater
|
||||
.update_if_needed(key, 2, || async {
|
||||
.update_if_needed::<(), _, _>(key, 2, || async {
|
||||
crate::error::UnexpectedSnafu {
|
||||
violated: "injected save failure",
|
||||
}
|
||||
@@ -137,32 +154,36 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
!updater
|
||||
.update_if_needed(key, 1, || async {
|
||||
updater
|
||||
.update_if_needed::<(), _, _>(key, 1, || async {
|
||||
panic!("stale heartbeat must not save");
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
updater
|
||||
.update_if_needed(key, 2, || async { Ok(()) })
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some_and(|saved| saved.retried)
|
||||
);
|
||||
assert!(
|
||||
!updater
|
||||
.update_if_needed(key, 2, || async {
|
||||
updater
|
||||
.update_if_needed::<(), _, _>(key, 2, || async {
|
||||
panic!("successful epoch must not save again");
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
updater
|
||||
.update_if_needed(key, 3, || async { Ok(()) })
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some_and(|saved| !saved.retried)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -190,6 +211,7 @@ mod tests {
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -248,6 +270,7 @@ mod tests {
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
})
|
||||
@@ -256,18 +279,19 @@ mod tests {
|
||||
progress_tx.send(()).unwrap();
|
||||
finish.notified().await;
|
||||
timeout(Duration::from_secs(2), async {
|
||||
assert!(first.await.unwrap().unwrap());
|
||||
assert!(second.await.unwrap().unwrap());
|
||||
assert!(first.await.unwrap().unwrap().is_some());
|
||||
assert!(second.await.unwrap().unwrap().is_some());
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!updater
|
||||
.update_if_needed((Role::Datanode, 1), 1, || async {
|
||||
updater
|
||||
.update_if_needed::<(), _, _>((Role::Datanode, 1), 1, || async {
|
||||
panic!("old epoch must not overwrite a newer one");
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user