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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use std::collections::BTreeMap;
use std::convert::{self, TryInto};
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex};
use anyhow::bail;
use kafka_util::client::MzClientContext;
use ore::task;
use rdkafka::client::ClientContext;
use rdkafka::consumer::{BaseConsumer, Consumer, ConsumerContext};
use rdkafka::{Offset, TopicPartitionList};
use reqwest::Url;
use tokio::time::Duration;
use ccsr::tls::{Certificate, Identity};
use sql_parser::ast::Value;
enum ValType {
Path,
String,
Number(i32, i32),
Boolean,
EnvVar,
}
impl ValType {
fn process_val(&self, val: &Value) -> Result<String, anyhow::Error> {
Ok(match (&self, val) {
(ValType::String, Value::String(v)) => v.to_string(),
(ValType::Boolean, Value::Boolean(b)) => b.to_string(),
(ValType::Path, Value::String(v)) => {
if std::fs::metadata(&v).is_err() {
bail!("file does not exist")
}
v.to_string()
}
(ValType::Number(lower, upper), Value::Number(n)) => match n.parse::<i32>() {
Ok(parsed_n) if *lower <= parsed_n && parsed_n <= *upper => n.to_string(),
_ => bail!("must be a number between {} and {}", lower, upper),
},
(ValType::EnvVar, Value::String(v)) => std::env::var(v)?,
_ => bail!("unexpected value type"),
})
}
}
struct Config {
name: &'static str,
val_type: ValType,
transform: fn(String) -> String,
default: Option<String>,
include_env_var: bool,
}
impl Config {
fn new(name: &'static str, val_type: ValType) -> Self {
Config {
name,
val_type,
transform: convert::identity,
default: None,
include_env_var: false,
}
}
fn string(name: &'static str) -> Self {
Config::new(name, ValType::String)
}
fn path(name: &'static str) -> Self {
Config::new(name, ValType::Path)
}
fn set_transform(mut self, f: fn(String) -> String) -> Self {
self.transform = f;
self
}
fn do_transform(&self, v: String) -> String {
(self.transform)(v)
}
fn set_default(mut self, d: Option<String>) -> Self {
assert!(
!self.include_env_var,
"cannot currently both set default values and include environment variables on the same config"
);
self.default = d;
self
}
fn include_env_var(mut self) -> Self {
assert!(
self.default.is_none(),
"cannot currently both set default values and include environment variables on the same config"
);
self.include_env_var = true;
self
}
fn get_kafka_config_key(&self) -> String {
self.name.replace("_", ".")
}
fn get_env_var_key(&self) -> String {
format!("{}_env", self.name)
}
}
fn extract(
input: &mut BTreeMap<String, Value>,
configs: &[Config],
) -> Result<BTreeMap<String, String>, anyhow::Error> {
let mut out = BTreeMap::new();
for config in configs {
let value = match input.remove(config.name) {
Some(v) => match config.val_type.process_val(&v) {
Ok(v) => {
if config.include_env_var && input.get(&config.get_env_var_key()).is_some() {
bail!(
"Invalid WITH options: cannot specify both {} and {} options at the same time",
config.name,
config.get_env_var_key()
)
}
v
}
Err(e) => bail!("Invalid WITH option {}={}: {}", config.name, v, e),
},
None if config.include_env_var => match input.remove(&config.get_env_var_key()) {
Some(v) => match ValType::EnvVar.process_val(&v) {
Ok(v) => v,
Err(e) => bail!(
"Invalid WITH option {}={}: {}",
config.get_env_var_key(),
v,
e
),
},
None => continue,
},
None => match &config.default {
Some(v) => v.to_string(),
None => continue,
},
};
let value = config.do_transform(value);
out.insert(config.get_kafka_config_key(), value);
}
Ok(out)
}
pub fn extract_config(
with_options: &mut BTreeMap<String, Value>,
) -> Result<BTreeMap<String, String>, anyhow::Error> {
extract(
with_options,
&[
Config::string("acks"),
Config::string("client_id"),
Config::new(
"statistics_interval_ms",
ValType::Number(0, 86_400_000),
)
.set_default(Some(
chrono::Duration::seconds(1).num_milliseconds().to_string(),
)),
Config::new(
"topic_metadata_refresh_interval_ms",
ValType::Number(0, 3_600_000),
),
Config::new("enable_auto_commit", ValType::Boolean),
Config::string("isolation_level").set_default(Some(String::from("read_committed"))),
Config::string("security_protocol"),
Config::path("sasl_kerberos_keytab"),
Config::string("sasl_username"),
Config::string("sasl_password").include_env_var(),
Config::string("sasl_kerberos_kinit_cmd"),
Config::string("sasl_kerberos_min_time_before_relogin"),
Config::string("sasl_kerberos_principal"),
Config::string("sasl_kerberos_service_name"),
Config::string("sasl_mechanisms").set_transform(|s| s.to_uppercase()),
Config::path("ssl_ca_location"),
Config::path("ssl_certificate_location"),
Config::path("ssl_key_location"),
Config::string("ssl_key_password").include_env_var(),
Config::new("transaction_timeout_ms", ValType::Number(0, i32::MAX)),
Config::new("enable_idempotence", ValType::Boolean),
Config::new(
"fetch_message_max_bytes",
ValType::Number(0, 1_000_000_000),
),
],
)
}
pub async fn create_consumer(
broker: &str,
topic: &str,
options: &BTreeMap<String, String>,
) -> Result<Arc<BaseConsumer<KafkaErrCheckContext>>, anyhow::Error> {
let mut config = rdkafka::ClientConfig::new();
config.set("bootstrap.servers", broker);
for (k, v) in options {
config.set(k, v);
}
match config.create_with_context(KafkaErrCheckContext::default()) {
Ok(consumer) => {
let consumer: Arc<BaseConsumer<KafkaErrCheckContext>> = Arc::new(consumer);
let context = Arc::clone(&consumer.context());
let owned_topic = String::from(topic);
task::spawn_blocking(move || format!("kafka_set_metadata:{broker}:{topic}"), {
let consumer = Arc::clone(&consumer);
move || {
let _ = consumer.fetch_metadata(Some(&owned_topic), Duration::from_secs(1));
}
})
.await?;
let error = context.error.lock().expect("lock poisoned");
if let Some(error) = &*error {
bail!("librdkafka: {}", error)
}
Ok(consumer)
}
Err(e) => {
match e {
rdkafka::error::KafkaError::ClientCreation(s) => {
if s == "Invalid sasl.kerberos.kinit.cmd value: Property \
not available: \"sasl.kerberos.keytab\""
{
bail!(
"Can't seem to find local keytab cache. With \
sasl_mechanisms='GSSAPI', you must provide an \
explicit sasl_kerberos_keytab or \
sasl_kerberos_kinit_cmd option."
)
} else {
bail!(rdkafka::error::KafkaError::ClientCreation(s))
}
}
_ => bail!(e),
}
}
}
}
pub async fn lookup_start_offsets(
consumer: Arc<BaseConsumer<KafkaErrCheckContext>>,
topic: &str,
with_options: &BTreeMap<String, Value>,
now: u64,
) -> Result<Option<Vec<i64>>, anyhow::Error> {
let time_offset = with_options.get("kafka_time_offset");
if time_offset.is_none() {
return Ok(None);
} else if with_options.contains_key("start_offset") {
bail!("`start_offset` and `kafka_time_offset` cannot be set at the same time.")
}
let time_offset = match time_offset.unwrap() {
Value::Number(s) => match s.parse::<i64>() {
Ok(ts) if ts < 0 => {
let now: i64 = now.try_into()?;
let ts = now - ts.abs();
if ts <= 0 {
bail!("Relative `kafka_time_offset` must be smaller than current system timestamp")
}
ts
}
Ok(ts) => ts,
_ => bail!("`kafka_time_offset` must be a number"),
},
_ => bail!("`kafka_time_offset` must be a number"),
};
task::spawn_blocking(|| format!("kafka_lookup_start_offets:{topic}"), {
let topic = topic.to_string();
move || {
let num_partitions = kafka_util::client::get_partitions(
consumer.as_ref().client(),
&topic,
Duration::from_secs(10),
)?
.len();
let mut tpl = TopicPartitionList::with_capacity(1);
tpl.add_partition_range(&topic, 0, num_partitions as i32 - 1);
tpl.set_all_offsets(Offset::Offset(time_offset))?;
let offsets_for_times = consumer.offsets_for_times(tpl, Duration::from_secs(10))?;
let start_offsets = offsets_for_times
.elements()
.iter()
.map(|elem| match elem.offset() {
Offset::Offset(offset) => Ok(offset),
Offset::End => fetch_end_offset(&consumer, &topic, elem.partition()),
_ => bail!(
"Unexpected offset {:?} for partition {}",
elem.offset(),
elem.partition()
),
})
.collect::<Result<Vec<_>, _>>()?;
if start_offsets.len() != num_partitions {
bail!(
"Expected offsets for {} partitions, but recevied {}",
num_partitions,
start_offsets.len(),
);
}
Ok(Some(start_offsets))
}
})
.await?
}
fn fetch_end_offset(
consumer: &BaseConsumer<KafkaErrCheckContext>,
topic: &str,
pid: i32,
) -> Result<i64, anyhow::Error> {
let (_low, high) = consumer.fetch_watermarks(topic, pid, Duration::from_secs(10))?;
Ok(high)
}
#[derive(Default, Debug)]
pub struct KafkaErrCheckContext {
pub error: Mutex<Option<String>>,
}
impl ConsumerContext for KafkaErrCheckContext {}
impl ClientContext for KafkaErrCheckContext {
fn log(&self, level: rdkafka::config::RDKafkaLogLevel, fac: &str, log_message: &str) {
use rdkafka::config::RDKafkaLogLevel::*;
match level {
Emerg | Alert | Critical | Error => {
let mut error = self.error.lock().expect("lock poisoned");
if error.is_none() {
*error = Some(log_message.to_string());
}
}
_ => {}
}
MzClientContext.log(level, fac, log_message)
}
fn error(&self, error: rdkafka::error::KafkaError, reason: &str) {
*self.error.lock().expect("lock poisoned") = Some(reason.to_string());
MzClientContext.error(error, reason)
}
}
pub fn generate_ccsr_client_config(
csr_url: Url,
_kafka_options: &BTreeMap<String, String>,
ccsr_options: &mut BTreeMap<String, Value>,
) -> Result<ccsr::ClientConfig, anyhow::Error> {
let mut client_config = ccsr::ClientConfig::new(csr_url);
if let Some(ca_path) = match ccsr_options.remove("ssl_ca_location").as_ref() {
Some(Value::String(path)) => Some(path),
Some(_) => {
bail!("ssl_ca_location must be a string");
}
None => None,
} {
let mut ca_buf = Vec::new();
File::open(ca_path)?.read_to_end(&mut ca_buf)?;
let cert = Certificate::from_pem(&ca_buf)?;
client_config = client_config.add_root_certificate(cert);
}
let ssl_key_location = ccsr_options.remove("ssl_key_location");
let key_path = match &&ssl_key_location {
Some(Value::String(path)) => Some(path),
Some(_) => {
bail!("ssl_key_location must be a string");
}
None => None,
};
let ssl_certificate_location = ccsr_options.remove("ssl_certificate_location");
let cert_path = match &ssl_certificate_location {
Some(Value::String(path)) => Some(path),
Some(_) => {
bail!("ssl_certificate_location must be a string");
}
None => None,
};
match (key_path, cert_path) {
(Some(key_path), Some(cert_path)) => {
let mut ident_buf = Vec::new();
File::open(key_path)?.read_to_end(&mut ident_buf)?;
File::open(cert_path)?.read_to_end(&mut ident_buf)?;
let ident = Identity::from_pem(&ident_buf)?;
client_config = client_config.identity(ident);
}
(None, None) => {}
(_, _) => bail!(
"Reading from SSL-auth Confluent Schema Registry \
requires both ssl.key.location and ssl.certificate.location"
),
}
let mut ccsr_options = extract(
ccsr_options,
&[Config::string("username"), Config::string("password")],
)?;
if let Some(username) = ccsr_options.remove("username") {
client_config = client_config.auth(username, ccsr_options.remove("password"));
}
Ok(client_config)
}