-
Notifications
You must be signed in to change notification settings - Fork 132
/
cluster.rs
437 lines (384 loc) · 13 KB
/
cluster.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use async_trait::async_trait;
use log::error;
use log::info;
use log::warn;
use tonic::transport::Channel;
use tonic::IntoRequest;
use tonic::Request;
use super::timestamp::TimestampOracle;
use crate::internal_err;
use crate::proto::keyspacepb;
use crate::proto::pdpb;
use crate::Error;
use crate::Result;
use crate::SecurityManager;
use crate::Timestamp;
/// A PD cluster.
pub struct Cluster {
id: u64,
client: pdpb::pd_client::PdClient<Channel>,
keyspace_client: keyspacepb::keyspace_client::KeyspaceClient<Channel>,
members: pdpb::GetMembersResponse,
tso: TimestampOracle,
}
macro_rules! pd_request {
($cluster_id:expr, $type:ty) => {{
let mut request = <$type>::default();
let mut header = pdpb::RequestHeader::default();
header.cluster_id = $cluster_id;
request.header = Some(header);
request
}};
}
// These methods make a single attempt to make a request.
impl Cluster {
pub async fn get_region(
&mut self,
key: Vec<u8>,
timeout: Duration,
) -> Result<pdpb::GetRegionResponse> {
let mut req = pd_request!(self.id, pdpb::GetRegionRequest);
req.region_key = key.clone();
req.send(&mut self.client, timeout).await
}
pub async fn get_region_by_id(
&mut self,
id: u64,
timeout: Duration,
) -> Result<pdpb::GetRegionResponse> {
let mut req = pd_request!(self.id, pdpb::GetRegionByIdRequest);
req.region_id = id;
req.send(&mut self.client, timeout).await
}
pub async fn get_store(
&mut self,
id: u64,
timeout: Duration,
) -> Result<pdpb::GetStoreResponse> {
let mut req = pd_request!(self.id, pdpb::GetStoreRequest);
req.store_id = id;
req.send(&mut self.client, timeout).await
}
pub async fn get_all_stores(
&mut self,
timeout: Duration,
) -> Result<pdpb::GetAllStoresResponse> {
let req = pd_request!(self.id, pdpb::GetAllStoresRequest);
req.send(&mut self.client, timeout).await
}
pub async fn get_timestamp(&self) -> Result<Timestamp> {
self.tso.clone().get_timestamp().await
}
pub async fn update_safepoint(
&mut self,
safepoint: u64,
timeout: Duration,
) -> Result<pdpb::UpdateGcSafePointResponse> {
let mut req = pd_request!(self.id, pdpb::UpdateGcSafePointRequest);
req.safe_point = safepoint;
req.send(&mut self.client, timeout).await
}
pub async fn load_keyspace(
&mut self,
keyspace: &str,
timeout: Duration,
) -> Result<keyspacepb::KeyspaceMeta> {
let mut req = pd_request!(self.id, keyspacepb::LoadKeyspaceRequest);
req.name = keyspace.to_owned();
let resp = req.send(&mut self.keyspace_client, timeout).await?;
let keyspace = resp
.keyspace
.ok_or_else(|| Error::KeyspaceNotFound(keyspace.to_owned()))?;
Ok(keyspace)
}
}
/// An object for connecting and reconnecting to a PD cluster.
pub struct Connection {
security_mgr: Arc<SecurityManager>,
}
impl Connection {
pub fn new(security_mgr: Arc<SecurityManager>) -> Connection {
Connection { security_mgr }
}
pub async fn connect_cluster(
&self,
endpoints: &[String],
timeout: Duration,
) -> Result<Cluster> {
let members = self.validate_endpoints(endpoints, timeout).await?;
let (client, keyspace_client, members) = self.try_connect_leader(&members, timeout).await?;
let id = members.header.as_ref().unwrap().cluster_id;
let tso = TimestampOracle::new(id, &client)?;
let cluster = Cluster {
id,
client,
keyspace_client,
members,
tso,
};
Ok(cluster)
}
// Re-establish connection with PD leader in asynchronous fashion.
pub async fn reconnect(&self, cluster: &mut Cluster, timeout: Duration) -> Result<()> {
warn!("updating pd client");
let start = Instant::now();
let (client, keyspace_client, members) =
self.try_connect_leader(&cluster.members, timeout).await?;
let tso = TimestampOracle::new(cluster.id, &client)?;
*cluster = Cluster {
id: cluster.id,
client,
keyspace_client,
members,
tso,
};
info!("updating PD client done, spent {:?}", start.elapsed());
Ok(())
}
async fn validate_endpoints(
&self,
endpoints: &[String],
timeout: Duration,
) -> Result<pdpb::GetMembersResponse> {
let mut endpoints_set = HashSet::with_capacity(endpoints.len());
let mut members = None;
let mut cluster_id = None;
for ep in endpoints {
if !endpoints_set.insert(ep) {
return Err(internal_err!("duplicated PD endpoint {}", ep));
}
let (_, _, resp) = match self.connect(ep, timeout).await {
Ok(resp) => resp,
// Ignore failed PD node.
Err(e) => {
warn!("PD endpoint {} failed to respond: {:?}", ep, e);
continue;
}
};
// Check cluster ID.
let cid = resp.header.as_ref().unwrap().cluster_id;
if let Some(sample) = cluster_id {
if sample != cid {
return Err(internal_err!(
"PD response cluster_id mismatch, want {}, got {}",
sample,
cid
));
}
} else {
cluster_id = Some(cid);
}
// TODO: check all fields later?
if members.is_none() {
members = Some(resp);
}
}
match members {
Some(members) => {
info!("All PD endpoints are consistent: {:?}", endpoints);
Ok(members)
}
_ => Err(internal_err!("PD cluster failed to respond")),
}
}
async fn connect(
&self,
addr: &str,
_timeout: Duration,
) -> Result<(
pdpb::pd_client::PdClient<Channel>,
keyspacepb::keyspace_client::KeyspaceClient<Channel>,
pdpb::GetMembersResponse,
)> {
let mut client = self
.security_mgr
.connect(addr, pdpb::pd_client::PdClient::<Channel>::new)
.await?;
let keyspace_client = self
.security_mgr
.connect(
addr,
keyspacepb::keyspace_client::KeyspaceClient::<Channel>::new,
)
.await?;
let resp: pdpb::GetMembersResponse = client
.get_members(pdpb::GetMembersRequest::default())
.await?
.into_inner();
Ok((client, keyspace_client, resp))
}
async fn try_connect(
&self,
addr: &str,
cluster_id: u64,
timeout: Duration,
) -> Result<(
pdpb::pd_client::PdClient<Channel>,
keyspacepb::keyspace_client::KeyspaceClient<Channel>,
pdpb::GetMembersResponse,
)> {
let (client, keyspace_client, r) = self.connect(addr, timeout).await?;
Connection::validate_cluster_id(addr, &r, cluster_id)?;
Ok((client, keyspace_client, r))
}
fn validate_cluster_id(
addr: &str,
members: &pdpb::GetMembersResponse,
cluster_id: u64,
) -> Result<()> {
let new_cluster_id = members.header.as_ref().unwrap().cluster_id;
if new_cluster_id != cluster_id {
Err(internal_err!(
"{} no longer belongs to cluster {}, it is in {}",
addr,
cluster_id,
new_cluster_id
))
} else {
Ok(())
}
}
async fn try_connect_leader(
&self,
previous: &pdpb::GetMembersResponse,
timeout: Duration,
) -> Result<(
pdpb::pd_client::PdClient<Channel>,
keyspacepb::keyspace_client::KeyspaceClient<Channel>,
pdpb::GetMembersResponse,
)> {
let previous_leader = previous.leader.as_ref().unwrap();
let members = &previous.members;
let cluster_id = previous.header.as_ref().unwrap().cluster_id;
let mut resp = None;
// Try to connect to other members, then the previous leader.
'outer: for m in members
.iter()
.filter(|m| *m != previous_leader)
.chain(Some(previous_leader))
{
for ep in &m.client_urls {
match self.try_connect(ep.as_str(), cluster_id, timeout).await {
Ok((_, _, r)) => {
resp = Some(r);
break 'outer;
}
Err(e) => {
error!("failed to connect to {}, {:?}", ep, e);
continue;
}
}
}
}
// Then try to connect the PD cluster leader.
if let Some(resp) = resp {
let leader = resp.leader.as_ref().unwrap();
for ep in &leader.client_urls {
if let Ok((client, keyspace_client, members)) =
self.try_connect(ep.as_str(), cluster_id, timeout).await
{
return Ok((client, keyspace_client, members));
}
}
}
Err(internal_err!("failed to connect to {:?}", members))
}
}
type GrpcResult<T> = std::result::Result<T, tonic::Status>;
#[async_trait]
trait PdMessage: Sized {
type Client: Send;
type Response: PdResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response>;
async fn send(self, client: &mut Self::Client, timeout: Duration) -> Result<Self::Response> {
let mut req = self.into_request();
req.set_timeout(timeout);
let response = Self::rpc(req, client).await?;
if let Some(err) = &response.header().error {
Err(internal_err!(err.message))
} else {
Ok(response)
}
}
}
#[async_trait]
impl PdMessage for pdpb::GetRegionRequest {
type Client = pdpb::pd_client::PdClient<Channel>;
type Response = pdpb::GetRegionResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.get_region(req).await?.into_inner())
}
}
#[async_trait]
impl PdMessage for pdpb::GetRegionByIdRequest {
type Client = pdpb::pd_client::PdClient<Channel>;
type Response = pdpb::GetRegionResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.get_region_by_id(req).await?.into_inner())
}
}
#[async_trait]
impl PdMessage for pdpb::GetStoreRequest {
type Client = pdpb::pd_client::PdClient<Channel>;
type Response = pdpb::GetStoreResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.get_store(req).await?.into_inner())
}
}
#[async_trait]
impl PdMessage for pdpb::GetAllStoresRequest {
type Client = pdpb::pd_client::PdClient<Channel>;
type Response = pdpb::GetAllStoresResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.get_all_stores(req).await?.into_inner())
}
}
#[async_trait]
impl PdMessage for pdpb::UpdateGcSafePointRequest {
type Client = pdpb::pd_client::PdClient<Channel>;
type Response = pdpb::UpdateGcSafePointResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.update_gc_safe_point(req).await?.into_inner())
}
}
#[async_trait]
impl PdMessage for keyspacepb::LoadKeyspaceRequest {
type Client = keyspacepb::keyspace_client::KeyspaceClient<Channel>;
type Response = keyspacepb::LoadKeyspaceResponse;
async fn rpc(req: Request<Self>, client: &mut Self::Client) -> GrpcResult<Self::Response> {
Ok(client.load_keyspace(req).await?.into_inner())
}
}
trait PdResponse {
fn header(&self) -> &pdpb::ResponseHeader;
}
impl PdResponse for pdpb::GetStoreResponse {
fn header(&self) -> &pdpb::ResponseHeader {
self.header.as_ref().unwrap()
}
}
impl PdResponse for pdpb::GetRegionResponse {
fn header(&self) -> &pdpb::ResponseHeader {
self.header.as_ref().unwrap()
}
}
impl PdResponse for pdpb::GetAllStoresResponse {
fn header(&self) -> &pdpb::ResponseHeader {
self.header.as_ref().unwrap()
}
}
impl PdResponse for pdpb::UpdateGcSafePointResponse {
fn header(&self) -> &pdpb::ResponseHeader {
self.header.as_ref().unwrap()
}
}
impl PdResponse for keyspacepb::LoadKeyspaceResponse {
fn header(&self) -> &pdpb::ResponseHeader {
self.header.as_ref().unwrap()
}
}