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
use error::{Result, Error};
use utils;
use protocol;
use connection::KafkaConnection;
use codecs::{ToByte, FromByte};
use std::collections::HashMap;
use std::io::Cursor;
use std::io::Read;
const CLIENTID: &'static str = "kafka-rust";
const DEFAULT_TIMEOUT: i32 = 120;
#[derive(Default, Debug)]
pub struct KafkaClient {
clientid: String,
timeout: i32,
hosts: Vec<String>,
correlation: i32,
conns: HashMap<String, KafkaConnection>,
pub topic_partitions: HashMap<String, Vec<i32>>,
topic_brokers: HashMap<String, String>
}
impl KafkaClient {
pub fn new(hosts: &Vec<String>) -> KafkaClient {
KafkaClient { hosts: hosts.to_vec(), clientid: CLIENTID.to_string(),
timeout: DEFAULT_TIMEOUT, ..KafkaClient::default()}
}
fn get_conn(& mut self, host: &str) -> Result<KafkaConnection> {
match self.conns.get(host) {
Some (conn) => return conn.clone(),
None => {}
}
self.conns.insert(host.to_string(),
try!(KafkaConnection::new(host, self.timeout)));
self.get_conn(host)
}
fn next_id(&mut self) -> i32{
self.correlation = (self.correlation + 1) % (1i32 << 30);
self.correlation
}
pub fn load_metadata_all(&mut self) -> Result<()>{
self.reset_metadata();
self.load_metadata(&vec!())
}
pub fn load_metadata (&mut self, topics: &Vec<String>) -> Result<()>{
let resp = try!(self.get_metadata(topics));
let mut brokers: HashMap<i32, String> = HashMap::new();
for broker in resp.brokers {
brokers.insert(broker.nodeid, format!("{}:{}", broker.host, broker.port));
}
self.topic_brokers.clear();
for topic in resp.topics {
self.topic_partitions.insert(topic.topic.clone(), vec!());
for partition in topic.partitions {
match brokers.get(&partition.leader) {
Some(broker) => {
self.topic_partitions.get_mut(&topic.topic).unwrap().push(partition.id);
self.topic_brokers.insert(
format!("{}-{}", topic.topic, partition.id),
broker.clone());
},
None => {}
}
}
}
Ok(())
}
pub fn reset_metadata(&mut self) {
self.topic_partitions.clear();
self.topic_brokers.clear();
}
fn get_metadata(&mut self, topics: &Vec<String>) -> Result<protocol::MetadataResponse> {
let correlation = self.next_id();
for host in self.hosts.to_vec() {
let req = protocol::MetadataRequest::new(correlation, &self.clientid, topics);
match self.get_conn(&host) {
Ok(mut conn) => if self.send_request(&mut conn, req).is_ok() {
return self.get_response::<protocol::MetadataResponse>(&mut conn);
},
Err(_) => {}
}
}
Err(Error::NoHostReachable)
}
pub fn fetch_offsets(&mut self, _topics: &Vec<String>) {
}
pub fn fetch_topic_offset(&mut self, topic: &String) -> Result<Vec<(String, Vec<utils::PartitionOffset>)>> {
let partitions = self.topic_partitions
.get(topic)
.unwrap_or(&vec!())
.clone();
let mut brokers: HashMap<String, Vec<i32>> = HashMap:: new();
for p in partitions {
let key = format!("{}-{}", topic, p);
match self.topic_brokers.get(&key) {
Some(broker) => {
if !brokers.contains_key(broker) {brokers.insert(broker.clone(), Vec::new());}
brokers.get_mut(broker).unwrap().push(p);
},
None => {}
}
}
let mut res: Vec<utils::PartitionOffset> = vec!();
for (host, partitions) in brokers.iter() {
let v = vec!(utils::TopicPartitions{
topic: topic.clone(),
partitions: partitions.to_vec()
});
for tpo in try!(self.fetch_offset(&v, host)) {
res.push(utils::PartitionOffset{partition: tpo.partition, offset: tpo.offset});
}
}
Ok(vec!((topic.clone(), res)))
}
fn fetch_offset(&mut self, topic_partitions: &Vec<utils::TopicPartitions>, host: &String)
-> Result<Vec<utils::TopicPartitionOffset>> {
let correlation = self.next_id();
let req = protocol::OffsetRequest::new_latest(topic_partitions, correlation, &self.clientid);
let resp = try!(self.send_receive::<protocol::OffsetRequest, protocol::OffsetResponse>(&host, req));
Ok(resp.get_offsets())
}
fn get_broker(&mut self, topic: &String, partition: i32) -> Option<String> {
let key = format!("{}-{}", topic, partition);
match self.topic_brokers.get(&key) {
Some(broker) => {
Some(broker.clone())
},
None => None
}
}
pub fn fetch_messages(&mut self, topic: &String, partition: i32, offset: i64) -> Result<Vec<utils::OffsetMessage>>{
let host = self.get_broker(topic, partition).unwrap();
let correlation = self.next_id();
let req = protocol::FetchRequest::new_single(topic, partition, offset, correlation, &self.clientid);
let resp = try!(self.send_receive::<protocol::FetchRequest, protocol::FetchResponse>(&host, req));
Ok(resp.get_messages())
}
pub fn send_message(&mut self, topic: &String, partition: i32, required_acks: i16,
timeout: i32, message: &Vec<u8>) -> Result<Vec<utils::TopicPartitionOffset>> {
let host = self.get_broker(topic, partition).unwrap();
let correlation = self.next_id();
let req = protocol::ProduceRequest::new_single(topic, partition, required_acks,
timeout, message, correlation, &self.clientid);
let resp = try!(self.send_receive
::<protocol::ProduceRequest, protocol::ProduceResponse>(&host, req));
Ok(resp.get_response())
}
fn send_receive<T: ToByte, V: FromByte>(&mut self, host: &str, req: T) -> Result<V::R> {
let mut conn = try!(self.get_conn(&host));
try!(self.send_request(&mut conn, req));
self.get_response::<V>(&mut conn)
}
fn send_request<T: ToByte>(&self, conn: &mut KafkaConnection, request: T) -> Result<usize>{
let mut buffer = vec!();
request.encode(&mut buffer);
let mut s = vec!();
(buffer.len() as i32).encode(&mut s);
for byte in buffer.iter() { s.push(*byte); }
conn.send(&s)
}
fn get_response<T: FromByte>(&self, conn:&mut KafkaConnection) -> Result<T::R>{
let mut v: Vec<u8> = vec!();
let _ = conn.read(4, &mut v);
let size = i32::decode_new(&mut Cursor::new(v)).unwrap();
let mut resp: Vec<u8> = vec!();
let _ = try!(conn.read(size as u64, &mut resp));
T::decode_new(&mut Cursor::new(resp))
}
}