-
Notifications
You must be signed in to change notification settings - Fork 478
feat: datanode stats is stored in the mem_kv of meta leader #943
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
78ddfd8
store heartbeat data in memory, instead of etcd
fengys1996 d411fb4
fix: typo
fengys1996 ec2de1c
fix: license header
fengys1996 e1f3c9e
cr
fengys1996 540a055
cr
fengys1996 8e273f8
rename "expect" -> "expected"
fengys1996 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| syntax = "proto3"; | ||
|
|
||
| package greptime.v1.meta; | ||
|
|
||
| import "greptime/v1/meta/common.proto"; | ||
| import "greptime/v1/meta/store.proto"; | ||
|
|
||
| // Cluster service is used for communication between meta nodes. | ||
| service Cluster { | ||
| // Batch get kvs by input keys from leader's in_memory kv store. | ||
| rpc BatchGet(GetKvRequest) returns (GetKvResponse); | ||
|
|
||
| // Range get the kvs from leader's in_memory kv store. | ||
| rpc Range(RangeRequest) returns (RangeResponse); | ||
| } | ||
|
|
||
| message GetKvRequest { | ||
| RequestHeader header = 1; | ||
|
|
||
| repeated bytes keys = 2; | ||
| } | ||
|
|
||
| message GetKvResponse { | ||
|
fengys1996 marked this conversation as resolved.
Outdated
|
||
| ResponseHeader header = 1; | ||
|
|
||
| repeated KeyValue kvs = 2; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| // 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 api::v1::meta::cluster_client::ClusterClient; | ||
| use api::v1::meta::{ | ||
| GetKvRequest, GetKvResponse, KeyValue, RangeRequest, RangeResponse, ResponseHeader, | ||
| }; | ||
| use common_grpc::channel_manager::ChannelManager; | ||
| use snafu::{ensure, OptionExt, ResultExt}; | ||
|
|
||
| use crate::error::Result; | ||
| use crate::keys::{StatKey, StatValue, DN_STAT_PREFIX}; | ||
| use crate::metasrv::ElectionRef; | ||
| use crate::service::store::ext::KvStoreExt; | ||
| use crate::service::store::kv::ResetableKvStoreRef; | ||
| use crate::{error, util}; | ||
|
|
||
| #[derive(Clone)] | ||
| pub struct MetaPeerClient { | ||
| election: Option<ElectionRef>, | ||
| in_memory: ResetableKvStoreRef, | ||
| channel_manager: ChannelManager, | ||
| } | ||
|
|
||
| impl MetaPeerClient { | ||
| pub fn new(in_mem: ResetableKvStoreRef, election: Option<ElectionRef>) -> Self { | ||
| Self { | ||
| election, | ||
| in_memory: in_mem, | ||
| channel_manager: ChannelManager::default(), | ||
| } | ||
| } | ||
|
|
||
| // Get all datanode stat kvs from leader meta. | ||
| pub async fn get_all_dn_stat_kvs(&self) -> Result<HashMap<StatKey, StatValue>> { | ||
| let stat_prefix = format!("{DN_STAT_PREFIX}-").into_bytes(); | ||
| let range_end = util::get_prefix_end_key(&stat_prefix); | ||
| let req = RangeRequest { | ||
| key: stat_prefix.clone(), | ||
| range_end, | ||
| ..Default::default() | ||
| }; | ||
|
|
||
| if self.is_leader() { | ||
| let kvs = self.in_memory.range(req).await?.kvs; | ||
| return to_stat_kv_map(kvs); | ||
| } | ||
|
|
||
| // Safety: when self.is_leader() == false, election must not empty. | ||
| let election = self.election.as_ref().unwrap(); | ||
|
|
||
| let leader_addr = election.leader().await?.0; | ||
|
|
||
| let channel = self | ||
| .channel_manager | ||
| .get(leader_addr) | ||
| .context(error::CreateChannelSnafu)?; | ||
|
|
||
| let request = tonic::Request::new(req); | ||
|
|
||
| let response: RangeResponse = ClusterClient::new(channel) | ||
| .range(request) | ||
| .await | ||
| .context(error::BatchGetSnafu)? | ||
| .into_inner(); | ||
|
|
||
| check_resp_header(&response.header)?; | ||
|
|
||
| to_stat_kv_map(response.kvs) | ||
| } | ||
|
|
||
| // Get datanode stat kvs from leader meta by input keys. | ||
| pub async fn get_dn_stat_kvs(&self, keys: Vec<StatKey>) -> Result<HashMap<StatKey, StatValue>> { | ||
| let stat_keys = keys.into_iter().map(|key| key.into()).collect(); | ||
| let stat_kvs = self.batch_get(stat_keys).await?; | ||
|
|
||
| let mut result = HashMap::with_capacity(stat_kvs.len()); | ||
| for stat_kv in stat_kvs { | ||
| let stat_key = stat_kv.key.try_into()?; | ||
| let stat_val = stat_kv.value.try_into()?; | ||
| result.insert(stat_key, stat_val); | ||
| } | ||
| Ok(result) | ||
| } | ||
|
|
||
| // Get kv information from the leader's in_mem kv store | ||
| async fn batch_get(&self, keys: Vec<Vec<u8>>) -> Result<Vec<KeyValue>> { | ||
| if self.is_leader() { | ||
| return self.in_memory.batch_get(keys).await; | ||
| } | ||
|
|
||
| // Safety: when self.is_leader() == false, election must not empty. | ||
| let election = self.election.as_ref().unwrap(); | ||
|
|
||
| let leader_addr = election.leader().await?.0; | ||
|
|
||
| let channel = self | ||
| .channel_manager | ||
| .get(leader_addr) | ||
| .context(error::CreateChannelSnafu)?; | ||
|
|
||
| let request = tonic::Request::new(GetKvRequest { | ||
| keys: keys.clone(), | ||
| ..Default::default() | ||
| }); | ||
|
|
||
| let response: GetKvResponse = ClusterClient::new(channel.clone()) | ||
| .batch_get(request) | ||
| .await | ||
| .context(error::BatchGetSnafu)? | ||
| .into_inner(); | ||
|
|
||
| check_resp_header(&response.header)?; | ||
|
|
||
| Ok(response.kvs) | ||
| } | ||
|
|
||
| // Check if the meta node is a leader node. | ||
| // Note: when self.election is None, we also consider the meta node is leader | ||
| fn is_leader(&self) -> bool { | ||
| self.election | ||
| .as_ref() | ||
| .map(|election| election.is_leader()) | ||
| .unwrap_or(true) | ||
| } | ||
| } | ||
|
|
||
| fn to_stat_kv_map(kvs: Vec<KeyValue>) -> Result<HashMap<StatKey, StatValue>> { | ||
| let mut map = HashMap::with_capacity(kvs.len()); | ||
| for kv in kvs { | ||
| map.insert(kv.key.try_into()?, kv.value.try_into()?); | ||
| } | ||
| Ok(map) | ||
| } | ||
|
|
||
| fn check_resp_header(header: &Option<ResponseHeader>) -> Result<()> { | ||
| let header = header | ||
| .as_ref() | ||
| .context(error::ResponseHeaderNotFoundSnafu)?; | ||
|
|
||
| ensure!(!header.is_not_leader(), error::IsNotLeaderSnafu); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use api::v1::meta::{Error, ErrorCode, KeyValue, ResponseHeader}; | ||
|
|
||
| use super::{check_resp_header, to_stat_kv_map}; | ||
| use crate::error; | ||
| use crate::handler::node_stat::Stat; | ||
| use crate::keys::{StatKey, StatValue}; | ||
|
|
||
| #[test] | ||
| fn test_to_stat_kv_map() { | ||
| let stat_key = StatKey { | ||
| cluster_id: 0, | ||
| node_id: 100, | ||
| }; | ||
|
|
||
| let stat = Stat { | ||
| cluster_id: 0, | ||
| id: 100, | ||
| addr: "127.0.0.1:3001".to_string(), | ||
| is_leader: true, | ||
| ..Default::default() | ||
| }; | ||
| let stat_val = StatValue { stats: vec![stat] }.try_into().unwrap(); | ||
|
|
||
| let kv = KeyValue { | ||
| key: stat_key.clone().into(), | ||
| value: stat_val, | ||
| }; | ||
|
|
||
| let kv_map = to_stat_kv_map(vec![kv]).unwrap(); | ||
| assert_eq!(1, kv_map.len()); | ||
| assert!(kv_map.get(&stat_key).is_some()); | ||
|
|
||
| let stat_val = kv_map.get(&stat_key).unwrap(); | ||
| let stat = stat_val.stats.get(0).unwrap(); | ||
|
|
||
| assert_eq!(0, stat.cluster_id); | ||
| assert_eq!(100, stat.id); | ||
| assert_eq!("127.0.0.1:3001", stat.addr); | ||
| assert!(stat.is_leader); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_check_resp_header() { | ||
| let header = Some(ResponseHeader { | ||
| error: None, | ||
| ..Default::default() | ||
| }); | ||
| let result = check_resp_header(&header); | ||
| assert!(result.is_ok()); | ||
|
|
||
| let result = check_resp_header(&None); | ||
| assert!(result.is_err()); | ||
| assert!(matches!( | ||
| result.err().unwrap(), | ||
| error::Error::ResponseHeaderNotFound { .. } | ||
| )); | ||
|
|
||
| let header = Some(ResponseHeader { | ||
| error: Some(Error { | ||
| code: ErrorCode::NotLeader as i32, | ||
| err_msg: "The current meta is not leader".to_string(), | ||
| }), | ||
| ..Default::default() | ||
| }); | ||
| let result = check_resp_header(&header); | ||
| assert!(result.is_err()); | ||
| assert!(matches!( | ||
| result.err().unwrap(), | ||
| error::Error::IsNotLeader { .. } | ||
| )); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.