-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
msg.rs
230 lines (199 loc) · 6.34 KB
/
msg.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
// Copyright 2016 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Instant;
use std::boxed::FnBox;
use std::fmt;
use kvproto::raft_serverpb::RaftMessage;
use kvproto::raft_cmdpb::{RaftCmdRequest, RaftCmdResponse};
use kvproto::metapb::RegionEpoch;
use raft::SnapshotStatus;
use util::collections::HashMap;
use storage::FlowStatistics;
use util::escape;
pub type Callback = Box<FnBox(RaftCmdResponse) + Send>;
pub type BatchCallback = Box<FnBox(Vec<Option<RaftCmdResponse>>) + Send>;
pub type CopFlowStatistics = HashMap<u64, FlowStatistics>;
#[derive(Debug, Clone, Copy)]
pub enum Tick {
Raft,
RaftLogGc,
SplitRegionCheck,
CompactCheck,
PdHeartbeat,
PdStoreHeartbeat,
SnapGc,
CompactLockCf,
ConsistencyCheck,
}
pub struct SnapshotStatusMsg {
pub region_id: u64,
pub to_peer_id: u64,
pub status: SnapshotStatus,
}
pub enum Msg {
Quit,
// For notify.
RaftMessage(RaftMessage),
RaftCmd {
send_time: Instant,
request: RaftCmdRequest,
callback: Callback,
},
BatchRaftSnapCmds {
send_time: Instant,
batch: Vec<RaftCmdRequest>,
on_finished: BatchCallback,
},
// For split check
SplitCheckResult {
region_id: u64,
epoch: RegionEpoch,
// It's a data key, starts with `DATA_PREFIX_KEY`.
split_key: Vec<u8>,
},
SplitRegion {
region_id: u64,
region_epoch: RegionEpoch,
// It's an encoded key.
split_key: Vec<u8>,
callback: Callback,
},
ReportUnreachable { region_id: u64, to_peer_id: u64 },
// For snapshot stats.
SnapshotStats,
CoprocessorStats { request_stats: CopFlowStatistics },
// For consistency check
ComputeHashResult {
region_id: u64,
index: u64,
hash: Vec<u8>,
},
}
impl fmt::Debug for Msg {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Msg::Quit => write!(fmt, "Quit"),
Msg::RaftMessage(_) => write!(fmt, "Raft Message"),
Msg::RaftCmd { .. } => write!(fmt, "Raft Command"),
Msg::BatchRaftSnapCmds { .. } => write!(fmt, "Batch Raft Commands"),
Msg::SplitCheckResult { .. } => write!(fmt, "Split Check Result"),
Msg::ReportUnreachable {
ref region_id,
ref to_peer_id,
} => write!(
fmt,
"peer {} for region {} is unreachable",
to_peer_id,
region_id
),
Msg::SnapshotStats => write!(fmt, "Snapshot stats"),
Msg::CoprocessorStats { .. } => write!(fmt, "Coperocessor stats"),
Msg::ComputeHashResult {
region_id,
index,
ref hash,
} => write!(
fmt,
"ComputeHashResult [region_id: {}, index: {}, hash: {}]",
region_id,
index,
escape(hash)
),
Msg::SplitRegion {
ref region_id,
ref split_key,
..
} => write!(fmt, "Split region {} at key {:?}", region_id, split_key),
}
}
}
impl Msg {
pub fn new_raft_cmd(request: RaftCmdRequest, callback: Callback) -> Msg {
Msg::RaftCmd {
send_time: Instant::now(),
request: request,
callback: callback,
}
}
pub fn new_batch_raft_snapshot_cmd(
batch: Vec<RaftCmdRequest>,
on_finished: BatchCallback,
) -> Msg {
Msg::BatchRaftSnapCmds {
send_time: Instant::now(),
batch: batch,
on_finished: on_finished,
}
}
}
#[cfg(test)]
mod tests {
use std::thread;
use std::boxed::FnBox;
use std::time::Duration;
use mio::{EventLoop, Handler};
use super::*;
use kvproto::raft_cmdpb::{RaftCmdRequest, RaftCmdResponse};
use raftstore::Error;
use util::transport::SendCh;
fn call_command(
sendch: &SendCh<Msg>,
request: RaftCmdRequest,
timeout: Duration,
) -> Result<RaftCmdResponse, Error> {
wait_op!(
|cb: Box<FnBox(RaftCmdResponse) + 'static + Send>| {
sendch.try_send(Msg::new_raft_cmd(request, cb)).unwrap()
},
timeout
).ok_or_else(|| {
Error::Timeout(format!("request timeout for {:?}", timeout))
})
}
struct TestHandler;
impl Handler for TestHandler {
type Timeout = ();
type Message = Msg;
fn notify(&mut self, event_loop: &mut EventLoop<Self>, msg: Self::Message) {
match msg {
Msg::Quit => event_loop.shutdown(),
Msg::RaftCmd {
callback, request, ..
} => {
// a trick for test timeout.
if request.get_header().get_region_id() == u64::max_value() {
thread::sleep(Duration::from_millis(100));
}
callback.call_box((RaftCmdResponse::new(),));
}
// we only test above message types, others panic.
_ => unreachable!(),
}
}
}
#[test]
fn test_sender() {
let mut event_loop = EventLoop::new().unwrap();
let sendch = &SendCh::new(event_loop.channel(), "test-sender");
let t = thread::spawn(move || { event_loop.run(&mut TestHandler).unwrap(); });
let mut request = RaftCmdRequest::new();
request.mut_header().set_region_id(u64::max_value());
assert!(call_command(sendch, request.clone(), Duration::from_millis(500)).is_ok());
match call_command(sendch, request, Duration::from_millis(10)) {
Err(Error::Timeout(_)) => {}
_ => panic!("should failed with timeout"),
}
sendch.try_send(Msg::Quit).unwrap();
t.join().unwrap();
}
}