-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathzookeeper.rs
2101 lines (1752 loc) · 83.1 KB
/
zookeeper.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use std::{fs, future};
use assert_matches::assert_matches;
use assertor::*;
use async_io::Timer;
use asyncs::select;
use pretty_assertions::assert_eq;
use rand::distributions::Standard;
use rand::Rng;
use rcgen::{Certificate, CertificateParams};
#[allow(unused_imports)]
use tempfile::{tempdir, TempDir};
use test_case::test_case;
use testcontainers::clients::Cli as DockerCli;
use testcontainers::core::{Container, Healthcheck, LogStream, RunnableImage, WaitFor};
use testcontainers::images::generic::GenericImage;
use zookeeper_client as zk;
static ZK_IMAGE_TAG: &'static str = "3.9.0";
static PERSISTENT_OPEN: &zk::CreateOptions<'static> = &zk::CreateMode::Persistent.with_acls(zk::Acls::anyone_all());
static CONTAINER_OPEN: &zk::CreateOptions<'static> = &zk::CreateMode::Container.with_acls(zk::Acls::anyone_all());
#[allow(dead_code)]
fn env_toggle(name: &str) -> bool {
match std::env::var(name) {
Ok(v) if v == "true" => true,
Ok(v) if v == "false" => false,
_ => rand::random(),
}
}
fn random_data() -> Vec<u8> {
let rng = rand::thread_rng();
rng.sample_iter(Standard).take(32).collect()
}
fn zookeeper_image<'a>(options: ContainerOptions<'a>) -> RunnableImage<GenericImage> {
let mut properties = options.properties;
properties.insert(0, "-Dzookeeper.DigestAuthenticationProvider.superDigest=super:D/InIHSb7yEEbrWz8b9l71RjZJU=");
properties.insert(0, "-Dzookeeper.enableEagerACLCheck=true");
let server_jvmflags = properties.join(" ");
let client_jvmflags = options.healthcheck.join(" ");
let healthcheck = Healthcheck::default()
.with_cmd(["./bin/zkServer.sh", "status"].iter())
.with_interval(Duration::from_secs(2))
.with_retries(60);
let mut image: RunnableImage<_> = GenericImage::new("zookeeper", options.tag)
.with_env_var("SERVER_JVMFLAGS", server_jvmflags)
.with_env_var("CLIENT_JVMFLAGS", client_jvmflags)
.with_healthcheck(healthcheck)
.with_wait_for(WaitFor::Healthcheck)
.into();
for (dest, source) in options.volumes {
image = image.with_volume((source.to_str().unwrap(), dest));
}
if let Some(network) = options.network.as_ref() {
image = image.with_network(*network);
}
image
}
async fn example() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let path = "/abc";
let data = "path_data".as_bytes().to_vec();
let child_path = "/abc/efg";
let child_data = "child_path_data".as_bytes().to_vec();
let (_, stat_watcher) = client.check_and_watch_stat(path).await.unwrap();
let (stat, _) = client.create(path, &data, PERSISTENT_OPEN).await.unwrap();
assert_eq!((data.clone(), stat), client.get_data(path).await.unwrap());
let event = stat_watcher.changed().await;
assert_eq!(event.event_type, zk::EventType::NodeCreated);
assert_eq!(event.path, path);
let mut multi_reader = client.new_multi_reader();
multi_reader.add_get_data(path).unwrap();
multi_reader.add_get_children("/").unwrap();
let mut results = multi_reader.commit().await.unwrap();
assert_eq!(results.len(), 2);
assert_matches!(results.remove(0), zk::MultiReadResult::Data { data: got_data, stat: got_stat } => {
assert_eq!(got_data, data);
assert_eq!(got_stat, stat);
});
assert_matches!(results.remove(0), zk::MultiReadResult::Children { children } => {
assert_that!(children).contains("abc".to_string());
});
let path_client = client.clone().chroot(path).unwrap();
assert_eq!((data.clone(), stat), path_client.get_data("/").await.unwrap());
let (_, _, child_watcher) = client.get_and_watch_children(path).await.unwrap();
let (child_stat, _) = client.create(child_path, &child_data, PERSISTENT_OPEN).await.unwrap();
let child_event = child_watcher.changed().await;
assert_eq!(child_event.event_type, zk::EventType::NodeChildrenChanged);
assert_eq!(child_event.path, path);
let relative_child_path = child_path.strip_prefix(path).unwrap();
assert_eq!((child_data.clone(), child_stat), path_client.get_data(relative_child_path).await.unwrap());
multi_reader.add_get_children(path).unwrap();
multi_reader.add_get_data(child_path).unwrap();
let mut results = multi_reader.commit().await.unwrap();
assert_eq!(results.len(), 2);
assert_matches!(results.remove(0), zk::MultiReadResult::Children { children } => {
assert_eq!(children, vec!["efg"]);
});
assert_matches!(results.remove(0), zk::MultiReadResult::Data { data, stat } => {
assert_eq!(data, child_data);
assert_eq!(stat, child_stat);
});
let (_, _, event_watcher) = client.get_and_watch_data("/").await.unwrap();
drop(client);
drop(path_client);
let session_event = event_watcher.changed().await;
assert_eq!(session_event.event_type, zk::EventType::Session);
assert_eq!(session_event.session_state, zk::SessionState::Closed);
}
#[test_log::test(asyncs::test)]
async fn test_example() {
asyncs::spawn(async move { example().await }).await.unwrap()
}
async fn connect(cluster: &Cluster, chroot: &str) -> zk::Client {
let client = cluster.client(None).await;
if chroot.len() <= 1 {
return client;
}
let mut i = 1;
while i <= chroot.len() {
let j = match chroot[i..].find('/') {
Some(j) => j + i,
None => chroot.len(),
};
let path = &chroot[..j];
match client.create(path, Default::default(), PERSISTENT_OPEN).await {
Ok(_) | Err(zk::Error::NodeExists) => {},
Err(err) => panic!("{err}"),
}
i = j + 1;
}
client.chroot(chroot).unwrap()
}
#[test_log::test(asyncs::test)]
async fn test_connect_nohosts() {
assert_that!(zk::Client::connector()
.session_timeout(Duration::from_secs(24 * 3600))
.fail_eagerly()
.connect("127.0.0.1:100,127.0.0.1:101")
.await
.unwrap_err())
.is_equal_to(zk::Error::NoHosts);
}
#[test_log::test(asyncs::test)]
async fn test_connect_timeout() {
assert_that!(zk::Client::connector()
.session_timeout(Duration::from_secs(1))
.connect("127.0.0.1:100,127.0.0.1:101")
.await
.unwrap_err())
.is_equal_to(zk::Error::Timeout);
}
#[test_log::test(asyncs::test)]
async fn test_connect_session_expired() {
let cluster = Cluster::new().await;
let client = cluster.custom_client(None, |connector| connector.detached()).await.unwrap();
let timeout = client.session_timeout();
let session = client.into_session();
Timer::after(timeout * 2).await;
assert_that!(cluster.custom_client(None, |connector| connector.session(session)).await.unwrap_err())
.is_equal_to(zk::Error::SessionExpired);
}
#[derive(Copy, Clone)]
enum Encryption {
Raw,
#[cfg(feature = "tls")]
Tls,
}
#[allow(dead_code)]
struct Tls {
_dir: Arc<TempDir>,
_ca_cert: Certificate,
ca_cert_pem: String,
ca_cert_file: PathBuf,
server_identity_file: PathBuf,
client_cert_pem: String,
client_cert_key: String,
client_identity_file: PathBuf,
client_x_cert_pem: String,
client_x_cert_key: String,
hostname_verification: bool,
}
#[cfg(feature = "tls")]
impl Tls {
fn new(dir: Arc<TempDir>) -> Self {
let hostname_verification = env_toggle("ZK_TLS_HOSTNAME_VERIFICATION");
let (ca_cert, ca_cert_pem) = generate_ca_cert();
let server_cert = generate_server_cert(hostname_verification);
let signed_server_cert = server_cert.serialize_pem_with_signer(&ca_cert).unwrap();
// ZooKeeper needs a keystore with both key and signed cert.
let server_pem = server_cert.serialize_private_key_pem() + &signed_server_cert;
let ca_cert_file = dir.path().join("ca.cert.pem");
fs::write(&ca_cert_file, &ca_cert_pem).unwrap();
let server_pem_file = dir.path().join("server.pem");
fs::write(&server_pem_file, &server_pem).unwrap();
let client_cert = generate_client_cert("client");
let signed_client_cert = client_cert.serialize_pem_with_signer(&ca_cert).unwrap();
let client_key = client_cert.serialize_private_key_pem();
let client_pem = client_key.clone() + &signed_client_cert;
let client_pem_file = dir.path().join("client.pem");
fs::write(&client_pem_file, &client_pem).unwrap();
let client_cert_x = generate_client_cert("client_x");
let signed_client_cert_x = client_cert_x.serialize_pem_with_signer(&ca_cert).unwrap();
let client_key_x = client_cert_x.serialize_private_key_pem();
Self {
_dir: dir,
_ca_cert: ca_cert,
ca_cert_pem,
ca_cert_file,
server_identity_file: server_pem_file,
client_cert_pem: signed_client_cert,
client_cert_key: client_key,
client_identity_file: client_pem_file,
client_x_cert_pem: signed_client_cert_x,
client_x_cert_key: client_key_x,
hostname_verification,
}
}
fn options(&self) -> zk::TlsOptions {
let mut options = zk::TlsOptions::default()
.with_pem_ca_certs(&self.ca_cert_pem)
.unwrap()
.with_pem_identity(&self.client_cert_pem, &self.client_cert_key)
.unwrap();
if !self.hostname_verification {
options = unsafe { options.with_no_hostname_verification() };
}
options
}
fn options_x(&self) -> zk::TlsOptions {
self.options().with_pem_identity(&self.client_x_cert_pem, &self.client_x_cert_key).unwrap()
}
}
struct Cluster {
#[cfg(feature = "tls")]
tls: Option<Tls>,
containers: Vec<(u32, Container<'static, GenericImage>)>,
docker: Arc<DockerCli>,
dir: LazyTempDir,
}
unsafe impl Send for Cluster {}
unsafe impl Sync for Cluster {}
struct ContainerOptions<'a> {
tag: &'a str,
volumes: HashMap<&'a str, &'a Path>,
properties: Vec<&'a str>,
healthcheck: Vec<&'a str>,
network: Option<&'a str>,
}
impl Default for ContainerOptions<'_> {
fn default() -> Self {
Self { tag: ZK_IMAGE_TAG, volumes: HashMap::new(), properties: vec![], healthcheck: vec![], network: None }
}
}
impl<'a> From<ClusterOptions<'a>> for ContainerOptions<'a> {
fn from(options: ClusterOptions<'a>) -> Self {
Self {
tag: options.tag,
volumes: Default::default(),
properties: options.properties,
healthcheck: Default::default(),
network: None,
}
}
}
struct ClusterOptions<'a> {
tag: &'a str,
network: Option<&'a str>,
volumes: HashMap<&'a str, &'a str>,
properties: Vec<&'a str>,
configs: Vec<&'a str>,
servers: Vec<(u32, &'a [&'a str])>,
}
impl ClusterOptions<'_> {
fn is_standalone(&self) -> bool {
return self.servers.len() <= 1;
}
fn servers(&self) -> Vec<(u32, String)> {
let mut lines = String::new();
for config in self.configs.iter() {
write!(&mut lines, "{}\n", config).unwrap();
}
let mut servers = vec![];
for server in self.servers.iter() {
let mut lines = lines.clone();
lines += "initLimit=5\n";
lines += "syncLimit=2\n";
write!(&mut lines, "{}\n", server.1.join("\n")).unwrap();
servers.push((server.0, lines));
}
if servers.is_empty() {
return vec![(1, lines)];
}
servers
}
}
impl Default for ClusterOptions<'_> {
fn default() -> Self {
Self {
tag: ZK_IMAGE_TAG,
network: None,
volumes: Default::default(),
properties: vec![],
configs: vec![],
servers: vec![],
}
}
}
struct LazyTempDir {
dir: Option<Arc<TempDir>>,
}
impl LazyTempDir {
fn new() -> Self {
Self { dir: None }
}
fn tempdir(&mut self) -> &Arc<TempDir> {
self.dir.get_or_insert_with(|| Arc::new(tempdir().unwrap()))
}
}
impl Cluster {
pub async fn new() -> Self {
Self::with_options(Default::default(), None).await
}
pub async fn with_properties(properties: Vec<&'_ str>) -> Self {
Self::with_options(ClusterOptions { properties, ..Default::default() }, None).await
}
pub async fn with_options(options: ClusterOptions<'_>, encryption: Option<Encryption>) -> Self {
let encryption = encryption.unwrap_or_else(|| {
#[cfg(feature = "tls")]
return if env_toggle("ZK_TEST_TLS") { Encryption::Tls } else { Encryption::Raw };
#[cfg(not(feature = "tls"))]
Encryption::Raw
});
let docker = Arc::new(DockerCli::default());
let mut cluster = match encryption {
#[cfg(not(feature = "tls"))]
Encryption::Raw => {
println!("starting plaintext zookeeper server {} ...", options.tag);
Self { containers: vec![], docker, dir: LazyTempDir::new() }
},
#[cfg(feature = "tls")]
Encryption::Raw => {
println!("starting plaintext zookeeper server {} ...", options.tag);
Self { tls: None, containers: vec![], docker, dir: LazyTempDir::new() }
},
#[cfg(feature = "tls")]
Encryption::Tls => {
let mut dir = LazyTempDir::new();
let tls = Tls::new(dir.tempdir().clone());
println!(
"starting tls zookeeper server {} {} hostname verification ...",
options.tag,
if tls.hostname_verification { "with" } else { "without" }
);
Self { tls: Some(tls), containers: vec![], docker, dir }
},
};
cluster.boot(options).await;
cluster
}
pub async fn boot(&mut self, options: ClusterOptions<'_>) {
let standalone = options.is_standalone();
let mut tasks = vec![];
for (id, mut configs) in options.servers() {
#[allow(unused_mut)]
let mut container_options = ContainerOptions {
tag: options.tag,
properties: options.properties.clone(),
network: options.network,
..Default::default()
};
#[cfg(feature = "tls")]
let tls = self.tls.is_some();
#[cfg(not(feature = "tls"))]
let tls = false;
match tls {
false => {
if standalone && !configs.is_empty() {
configs += "clientPort=2181\n";
configs += "initLimit=5\n";
configs += "syncLimit=2\n";
}
},
#[cfg(not(feature = "tls"))]
true => {},
#[cfg(feature = "tls")]
true => {
let tls = self.tls.as_ref().unwrap();
configs += r"
ssl.clientAuth=need
ssl.keyStore.location=/certs/server.pem
ssl.trustStore.location=/certs/ca.cert.pem
serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
";
if standalone {
configs += "secureClientPort=2181\n";
}
container_options.volumes = HashMap::from([
("/certs/client.pem", tls.client_identity_file.as_path()),
("/certs/server.pem", tls.server_identity_file.as_path()),
("/certs/ca.cert.pem", tls.ca_cert_file.as_path()),
]);
container_options.healthcheck = vec![
"-Dzookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty",
"-Dzookeeper.ssl.trustStore.location=/certs/ca.cert.pem",
"-Dzookeeper.ssl.keyStore.location=/certs/client.pem",
"-Dzookeeper.client.secure=true",
];
},
};
let mut image = zookeeper_image(container_options);
for (path, content) in options.volumes.iter() {
let file_path = self.dir.tempdir().path().join(Path::new(path).strip_prefix("/").unwrap());
let parent_path = file_path.parent().unwrap();
fs::create_dir_all(parent_path).unwrap();
fs::write(&file_path, content).unwrap();
image = image.with_volume((file_path.to_str().unwrap(), *path));
}
if !configs.is_empty() {
configs += "dataDir=/data\n";
let cfg_path = self.dir.tempdir().path().join(format!("zoo{id}.cfg"));
fs::write(&cfg_path, &configs).unwrap();
image = image.with_volume((cfg_path.to_str().unwrap(), "/conf/zoo.cfg"));
}
if standalone {
let container = unsafe { std::mem::transmute(self.docker.run(image)) };
self.containers.push((1, container));
return;
}
let data_dir = self.dir.tempdir().path().join(format!("zoo{id}.data"));
std::fs::create_dir_all(data_dir.as_path()).unwrap();
fs::write(&data_dir.as_path().join("myid"), format!("{id}\n")).unwrap();
image = image.with_volume((data_dir.to_str().unwrap(), "/data"));
// image = image.with_env_var(("ZOO_MY_ID", id.to_string()));
tasks.push((
id,
blocking::unblock({
let docker = self.docker.clone();
move || unsafe { std::mem::transmute::<_, Container<'static, GenericImage>>(docker.run(image)) }
}),
));
}
for task in tasks {
let id = task.0;
let container = task.1.await;
self.containers.push((id, container));
}
}
pub fn stop(&self) {
self.containers.iter().for_each(|c| c.1.stop());
}
pub fn by_id(&self, id: u32) -> &Container<'static, GenericImage> {
self.containers.iter().find_map(|c| if c.0 == id { Some(&c.1) } else { None }).expect("container")
}
#[allow(dead_code)]
pub fn logs(&self, id: u32) -> LogStream {
let container = self.by_id(id);
container.stdout()
}
fn url(&self, chroot: Option<&str>) -> (String, bool) {
#[cfg(feature = "tls")]
let tls = self.tls.is_some();
#[cfg(not(feature = "tls"))]
let tls = false;
#[cfg(feature = "tls")]
let secure = rand::random();
#[cfg(not(feature = "tls"))]
let secure = false;
let endpoints: Vec<_> = self
.containers
.iter()
.map(|c| {
let explicit = rand::random();
let protocol = match (tls, secure, explicit) {
(true, false, _) | (true, _, true) => "tcp+tls://",
(false, true, _) | (false, _, true) => "tcp://",
(_, _, _) => "",
};
format!("{}127.0.0.1:{}", protocol, c.1.get_host_port(2181))
})
.collect();
(endpoints.join(",") + chroot.unwrap_or(""), secure)
}
#[cfg(not(feature = "tls"))]
pub fn connector(&self) -> zk::Connector {
zk::Client::connector()
}
#[cfg(feature = "tls")]
pub fn connector(&self) -> zk::Connector {
let mut connector = zk::Client::connector();
let Some(tls) = self.tls.as_ref() else {
return connector;
};
connector.tls(tls.options());
connector
}
pub async fn client(&self, chroot: Option<&str>) -> zk::Client {
self.custom_client(chroot, |connector| connector).await.unwrap()
}
#[cfg(feature = "tls")]
pub async fn client_x(&self, chroot: Option<&str>) -> zk::Client {
self.custom_client(chroot, |connector| match self.tls.as_ref().map(Tls::options_x) {
None => connector,
Some(options) => connector.tls(options),
})
.await
.unwrap()
}
pub async fn custom_client(
&self,
chroot: Option<&str>,
custom: impl FnOnce(&mut zk::Connector) -> &mut zk::Connector,
) -> Result<zk::Client, zk::Error> {
let mut connector = self.connector();
custom(&mut connector);
let (url, secure) = self.url(chroot);
match secure {
#[cfg(feature = "tls")]
true => connector.secure_connect(&url).await,
#[cfg(not(feature = "tls"))]
true => unreachable!("no tls support"),
false => connector.connect(&url).await,
}
}
}
#[test_case("/"; "no_chroot")]
#[test_case("/x"; "chroot_x")]
#[test_case("/x/y"; "chroot_x_y")]
#[test_log::test(asyncs::test)]
async fn test_multi(chroot: &str) {
let cluster = Cluster::new().await;
let client = connect(&cluster, chroot).await;
let mut writer = client.new_multi_writer();
assert_that!(writer.commit().await.unwrap()).is_empty();
writer.add_set_data("/a", &random_data(), None).unwrap();
writer.abort();
assert_that!(writer.commit().await.unwrap()).is_empty();
writer.add_create("/a", "/a.0".as_bytes(), PERSISTENT_OPEN).unwrap();
let mut results = writer.commit().await.unwrap();
assert_matches!(results.remove(0), zk::MultiWriteResult::Create { path, stat } => {
assert_eq!(path, "/a");
assert_that!(stat.is_invalid()).is_false();
});
assert_that!(results).is_empty();
assert_that!(writer.commit().await.unwrap()).is_empty();
let (data, a_stat) = client.get_data("/a").await.unwrap();
assert_eq!(data, "/a.0".as_bytes());
writer.add_check_version("/a", a_stat.version + 1).unwrap();
writer.add_set_data("/a", &random_data(), None).unwrap();
writer.add_create("/a", &random_data(), PERSISTENT_OPEN).unwrap();
assert_eq!(writer.commit().await.unwrap_err(), zk::MultiWriteError::OperationFailed {
index: 0,
source: zk::Error::BadVersion
});
writer.add_set_data("/a", &random_data(), None).unwrap();
writer.add_check_version("/a", a_stat.version + 1).unwrap();
writer.add_create("/a", &random_data(), PERSISTENT_OPEN).unwrap();
assert_eq!(writer.commit().await.unwrap_err(), zk::MultiWriteError::OperationFailed {
index: 2,
source: zk::Error::NodeExists
});
writer.add_set_data("/a", "/a.1".as_bytes(), None).unwrap();
writer.add_check_version("/a", a_stat.version + 1).unwrap();
writer.add_set_data("/a", "/a.2".as_bytes(), None).unwrap();
writer.add_check_version("/a", a_stat.version + 2).unwrap();
writer.add_create("/a/b", "/a/b.0".as_bytes(), PERSISTENT_OPEN).unwrap();
let mut results = writer.commit().await.unwrap();
assert_matches!(results.remove(0), zk::MultiWriteResult::SetData { stat } => {
assert_that!(stat.czxid).is_equal_to(a_stat.czxid);
assert_that!(stat.mzxid).is_greater_than(a_stat.mzxid);
assert_that!(stat.version).is_equal_to(a_stat.version + 1);
});
assert_matches!(results.remove(0), zk::MultiWriteResult::Check);
assert_matches!(results.remove(0), zk::MultiWriteResult::SetData { stat } => {
assert_that!(stat.czxid).is_equal_to(a_stat.czxid);
assert_that!(stat.mzxid).is_greater_than(a_stat.mzxid);
assert_that!(stat.version).is_equal_to(a_stat.version + 2);
});
assert_matches!(results.remove(0), zk::MultiWriteResult::Check);
assert_matches!(results.remove(0), zk::MultiWriteResult::Create { path, stat } => {
assert_eq!(path, "/a/b");
assert_that!(stat.is_invalid()).is_false();
});
assert_that!(results).is_empty();
let (_, a_stat) = client.get_data("/a").await.unwrap();
let (_, b_stat) = client.get_data("/a/b").await.unwrap();
let mut reader = client.new_multi_reader();
assert_that!(reader.commit().await.unwrap()).is_empty();
reader.add_get_data("/a").unwrap();
reader.abort();
assert_that!(reader.commit().await.unwrap()).is_empty();
reader.add_get_data("/a").unwrap();
reader.add_get_data("/a/b").unwrap();
reader.add_get_data("/a/c").unwrap();
reader.add_get_children("/a").unwrap();
reader.add_get_children("/a/b").unwrap();
reader.add_get_children("/a/c").unwrap();
let mut results = reader.commit().await.unwrap();
assert_that!(reader.commit().await.unwrap()).is_empty();
assert_matches!(results.remove(0), zk::MultiReadResult::Data { data, stat } => {
assert_eq!(data, "/a.2".as_bytes());
assert_eq!(stat, a_stat);
});
assert_matches!(results.remove(0), zk::MultiReadResult::Data { data, stat } => {
assert_eq!(data, "/a/b.0".as_bytes());
assert_eq!(stat, b_stat);
});
assert_matches!(results.remove(0), zk::MultiReadResult::Error { err: zk::Error::NoNode });
assert_matches!(results.remove(0), zk::MultiReadResult::Children { children } => {
assert_eq!(children, vec!["b".to_string()]);
});
assert_matches!(results.remove(0), zk::MultiReadResult::Children { children } => {
assert_that!(children).is_empty();
});
assert_matches!(results.remove(0), zk::MultiReadResult::Error { err: zk::Error::NoNode });
assert_that!(results).is_empty();
}
#[test_log::test(asyncs::test)]
async fn test_multi_async_order() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
client.create("/a", "a0".as_bytes(), PERSISTENT_OPEN).await.unwrap();
let mut writer = client.new_multi_writer();
writer.add_set_data("/a", "a1".as_bytes(), None).unwrap();
let write = writer.commit();
let mut reader = client.new_multi_reader();
reader.add_get_data("/a").unwrap();
let mut results = reader.commit().await.unwrap();
let zk::MultiReadResult::Data { data, stat } = results.remove(0) else { panic!("expect get data result") };
let mut write_results = write.await.unwrap();
let zk::MultiWriteResult::SetData { stat: set_stat } = write_results.remove(0) else {
panic!("expect set data result")
};
assert_that!(data).is_equal_to("a1".as_bytes().to_owned());
assert_that!(stat).is_equal_to(set_stat);
}
#[test_log::test(asyncs::test)]
async fn test_check_writer() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let mut check_writer = client.new_check_writer("/check", None).unwrap();
check_writer.add_create("/a", Default::default(), PERSISTENT_OPEN).unwrap();
assert_that!(check_writer.commit().await.unwrap_err())
.is_equal_to(zk::CheckWriteError::CheckFailed { source: zk::Error::NoNode });
let (stat, _sequence) = client.create("/check", Default::default(), PERSISTENT_OPEN).await.unwrap();
let mut check_writer = client.new_check_writer("/check", Some(stat.version + 1)).unwrap();
check_writer.add_create("/a", Default::default(), PERSISTENT_OPEN).unwrap();
assert_that!(check_writer.commit().await.unwrap_err())
.is_equal_to(zk::CheckWriteError::CheckFailed { source: zk::Error::BadVersion });
let mut check_writer = client.new_check_writer("/check", Some(stat.version)).unwrap();
check_writer.add_create("/a", b"a", PERSISTENT_OPEN).unwrap();
let mut results = check_writer.commit().await.unwrap();
let created_stat = match results.remove(0) {
zk::MultiWriteResult::Create { stat, .. } => stat,
result => panic!("expect create result, got {:?}", result),
};
let (data, stat) = client.get_data("/a").await.unwrap();
assert_that!(created_stat).is_equal_to(stat);
assert_that!(data).is_equal_to(b"a".to_vec());
}
#[test_case("/x"; "chroot_x")]
#[test_case("/x/y"; "chroot_x_y")]
#[test_log::test(asyncs::test)]
async fn test_lock_shared(chroot: &str) {
let cluster = Cluster::new().await;
test_lock_with_path(
&cluster,
chroot,
zk::LockPrefix::new_shared("/locks/shared/n-").unwrap(),
zk::LockPrefix::new_shared("/locks/shared/n-").unwrap(),
)
.await;
}
#[test_case("/x"; "chroot_x")]
#[test_case("/x/y"; "chroot_x_y")]
#[test_log::test(asyncs::test)]
async fn test_lock_custom(chroot: &str) {
let cluster = Cluster::new().await;
let lock1_prefix = zk::LockPrefix::new_custom("/locks/custom/n-abc-".to_string(), "n-").unwrap();
let lock2_prefix = zk::LockPrefix::new_custom("/locks/custom/n-def-".to_string(), "n-").unwrap();
test_lock_with_path(&cluster, chroot, lock1_prefix, lock2_prefix).await;
}
#[test_case("/x"; "chroot_x")]
#[test_case("/x/y"; "chroot_x_y")]
#[test_log::test(asyncs::test)]
async fn test_lock_curator(chroot: &str) {
let cluster = Cluster::new().await;
let lock1_prefix = zk::LockPrefix::new_curator("/locks/curator", "latch-").unwrap();
let lock2_prefix = zk::LockPrefix::new_curator("/locks/curator", "latch-").unwrap();
test_lock_with_path(&cluster, chroot, lock1_prefix, lock2_prefix).await;
}
#[test_log::test(asyncs::test)]
async fn test_lock_no_node() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let prefix = zk::LockPrefix::new_curator("/a/locks", "latch-").unwrap();
assert_eq!(client.lock(prefix, b"", zk::Acls::anyone_all()).await.unwrap_err(), zk::Error::NoNode);
}
#[test_log::test(asyncs::test)]
async fn test_lock_curator_filter() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let options = zk::LockOptions::new(zk::Acls::anyone_all()).with_ancestor_options(CONTAINER_OPEN.clone()).unwrap();
let latch_prefix = zk::LockPrefix::new_curator("/locks/curator", "latch-").unwrap();
let _latch = client.lock(latch_prefix, b"", options.clone()).await.unwrap();
let lock_prefix = zk::LockPrefix::new_curator("/locks/curator", "lock-").unwrap();
let _lock = client.lock(lock_prefix, b"", options).await.unwrap();
}
#[allow(unused_must_use)] // semi-asynchronous future
async fn test_lock_with_path(
cluster: &Cluster,
chroot: &str,
lock1_prefix: zk::LockPrefix<'static>,
lock2_prefix: zk::LockPrefix<'static>,
) {
let client1 = connect(cluster, chroot).await;
let client2 = connect(cluster, chroot).await;
let options = zk::LockOptions::new(zk::Acls::anyone_all()).with_ancestor_options(CONTAINER_OPEN.clone()).unwrap();
let lock1 = client1.lock(lock1_prefix, b"", options.clone()).await.unwrap();
let contender2 = asyncs::spawn(async move {
let lock2 = client2.lock(lock2_prefix, b"", options).await.unwrap();
let (data, stat) = lock2.client().get_data("/lock-path").await.unwrap();
lock2.set_data("/lock-path", lock2.lock_path().as_bytes(), None).await.unwrap();
lock2.delete("/tmp1", None).await.unwrap();
(data, stat)
});
// Let lock2 get chance to chime in.
Timer::after(Duration::from_millis(100)).await;
let lock1_path = lock1.lock_path().to_string();
let (stat, _) = lock1.create("/lock-path", lock1_path.as_bytes(), PERSISTENT_OPEN).await.unwrap();
// Semi-asynchronous data request, no need to await.
lock1.create("/tmp1", b"", PERSISTENT_OPEN);
client1.delete(&lock1_path, None).await.unwrap();
assert_that!(lock1.create("/tmp2", b"", PERSISTENT_OPEN).await.unwrap_err())
.is_equal_to(zk::Error::RuntimeInconsistent);
drop(lock1);
assert_that!(contender2.await.unwrap()).is_equal_to((lock1_path.as_bytes().to_vec(), stat));
assert_that!(client1.check_stat("/tmp1").await.unwrap()).is_equal_to(None);
let (data, _stat) = client1.get_data("/lock-path").await.unwrap();
let lock2_path = String::from_utf8(data).unwrap();
// Let background delete get chance to chime in.
Timer::after(Duration::from_millis(100)).await;
assert_that!(client1.check_stat(&lock1_path).await.unwrap()).is_equal_to(None);
assert_that!(client1.check_stat(&lock2_path).await.unwrap()).is_equal_to(None);
}
#[test_log::test(asyncs::test)]
async fn test_no_node() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
assert_eq!(client.check_stat("/nonexistent").await.unwrap(), None);
assert_eq!(client.get_data("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(client.get_and_watch_data("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(client.get_children("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(client.get_and_watch_children("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(client.list_children("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(client.list_and_watch_children("/nonexistent").await.unwrap_err(), zk::Error::NoNode);
assert_eq!(
client.create("/nonexistent/child", Default::default(), PERSISTENT_OPEN).await.unwrap_err(),
zk::Error::NoNode
);
}
#[test_log::test(asyncs::test)]
async fn test_request_order() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let path = "/abc";
let child_path = "/abc/efg";
let create = client.create(path, Default::default(), PERSISTENT_OPEN);
let get_data = client.get_and_watch_children(path);
let get_child_data = client.get_data(child_path);
let (child_stat, _) = client.create(child_path, Default::default(), PERSISTENT_OPEN).await.unwrap();
let (stat, _) = create.await.unwrap();
assert_that!(child_stat.czxid).is_greater_than(stat.czxid);
let (children, stat1, watcher) = get_data.await.unwrap();
assert_that!(children).is_empty();
assert_that!(stat1).is_equal_to(stat);
let child_event = watcher.changed().await;
assert_that!(child_event.event_type).is_equal_to(zk::EventType::NodeChildrenChanged);
assert_that!(child_event.path).is_equal_to(path.to_owned());
assert_that!(get_child_data.await).is_equal_to(Err(zk::Error::NoNode));
}
#[test_log::test(asyncs::test)]
async fn test_data_node() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let path = "/abc";
let data = random_data();
let (stat, sequence) = client.create(path, &data, PERSISTENT_OPEN).await.unwrap();
assert_eq!(sequence.into_i64(), -1);
assert_eq!(stat, client.check_stat(path).await.unwrap().unwrap());
assert_eq!((data, stat), client.get_data(path).await.unwrap());
assert_eq!((vec![], stat), client.get_children(path).await.unwrap());
assert_eq!(Vec::<String>::new(), client.list_children(path).await.unwrap());
client.delete(path, None).await.unwrap();
assert_eq!(client.check_stat(path).await.unwrap(), None);
}
#[test_log::test(asyncs::test)]
async fn test_create_root() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await.chroot("/a").unwrap();
assert_that!(client.create("/", &vec![], PERSISTENT_OPEN).await.unwrap_err())
.is_equal_to(zk::Error::BadArguments(&"can not create root node"));
assert_that!(client.mkdir("/", PERSISTENT_OPEN).await.unwrap_err())
.is_equal_to(zk::Error::BadArguments(&"can not create root node"));
}
#[test_log::test(asyncs::test)]
async fn test_create_sequential() {
let cluster = Cluster::new().await;
let client = cluster.client(None).await;
let prefix = "/PREFIX-";
let data = random_data();
let (stat1, sequence1) = client
.create(prefix, &data, &zk::CreateMode::PersistentSequential.with_acls(zk::Acls::anyone_all()))
.await
.unwrap();
let (stat2, sequence2) = client
.create(prefix, &data, &zk::CreateMode::EphemeralSequential.with_acls(zk::Acls::anyone_all()))
.await
.unwrap();
assert!(sequence2.into_i64() > sequence1.into_i64());
let path1 = format!("{}{}", prefix, sequence1);
let path2 = format!("{}{}", prefix, sequence2);
assert_eq!((data.clone(), stat1), client.get_data(&path1).await.unwrap());
assert_eq!((data, stat2), client.get_data(&path2).await.unwrap());
}
#[test_log::test(asyncs::test)]
async fn test_create_ttl() {
let cluster = Cluster::with_properties(vec![
"-Dzookeeper.extendedTypesEnabled=true",
"-Dznode.container.checkIntervalMs=1000",
])
.await;
let client = cluster.client(None).await;
let ttl_options = PERSISTENT_OPEN.clone().with_ttl(Duration::from_millis(500));
client.create("/ttl", &vec![], &ttl_options).await.unwrap();
client.create("/ttl/child", &vec![], PERSISTENT_OPEN).await.unwrap();
Timer::after(Duration::from_secs(4)).await;
client.delete("/ttl/child", None).await.unwrap();
Timer::after(Duration::from_secs(4)).await;
assert_that!(client.delete("/ttl", None).await.unwrap_err()).is_equal_to(zk::Error::NoNode);
}
#[test_log::test(asyncs::test)]
async fn test_create_container() {
let cluster = Cluster::with_properties(vec![
"-Dzookeeper.extendedTypesEnabled=true",
"-Dznode.container.checkIntervalMs=1000",
])
.await;
let client = cluster.client(None).await;
client.create("/container", &vec![], &zk::CreateMode::Container.with_acls(zk::Acls::anyone_all())).await.unwrap();
client.create("/container/child", &vec![], PERSISTENT_OPEN).await.unwrap();
Timer::after(Duration::from_secs(4)).await;
client.delete("/container/child", None).await.unwrap();
Timer::after(Duration::from_secs(4)).await;