-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
V1_AdminApiTest.java
2072 lines (1724 loc) · 90.8 KB
/
V1_AdminApiTest.java
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.admin.v1;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import com.google.common.collect.BoundType;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.hash.Hashing;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.WebTarget;
import lombok.Builder;
import lombok.Cleanup;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
import org.apache.pulsar.broker.namespace.NamespaceEphemeralData;
import org.apache.pulsar.broker.namespace.NamespaceService;
import org.apache.pulsar.client.admin.LongRunningProcessStatus;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.admin.PulsarAdminException.ConflictException;
import org.apache.pulsar.client.admin.PulsarAdminException.NotAuthorizedException;
import org.apache.pulsar.client.admin.PulsarAdminException.NotFoundException;
import org.apache.pulsar.client.admin.PulsarAdminException.PreconditionFailedException;
import org.apache.pulsar.client.admin.internal.LookupImpl;
import org.apache.pulsar.client.admin.internal.TenantsImpl;
import org.apache.pulsar.client.admin.internal.TopicsImpl;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageRoutingMode;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.SubscriptionType;
import org.apache.pulsar.common.lookup.data.LookupData;
import org.apache.pulsar.common.naming.NamespaceBundle;
import org.apache.pulsar.common.naming.NamespaceBundleFactory;
import org.apache.pulsar.common.naming.NamespaceBundles;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.policies.data.AuthAction;
import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData;
import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType;
import org.apache.pulsar.common.policies.data.BacklogQuota;
import org.apache.pulsar.common.policies.data.BacklogQuota.BacklogQuotaType;
import org.apache.pulsar.common.policies.data.BacklogQuota.RetentionPolicy;
import org.apache.pulsar.common.policies.data.BrokerAssignment;
import org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationData;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.NamespaceIsolationData;
import org.apache.pulsar.common.policies.data.NamespaceIsolationDataImpl;
import org.apache.pulsar.common.policies.data.NamespaceOwnershipStatus;
import org.apache.pulsar.common.policies.data.PartitionedTopicStats;
import org.apache.pulsar.common.policies.data.PersistencePolicies;
import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats;
import org.apache.pulsar.common.policies.data.Policies;
import org.apache.pulsar.common.policies.data.PoliciesUtil;
import org.apache.pulsar.common.policies.data.RetentionPolicies;
import org.apache.pulsar.common.policies.data.TenantInfo;
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
import org.apache.pulsar.common.policies.data.TopicStats;
import org.apache.pulsar.common.util.Codec;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.pulsar.compaction.Compactor;
import org.apache.pulsar.metadata.cache.impl.MetadataCacheImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Slf4j
@Test(groups = "broker-admin")
public class V1_AdminApiTest extends MockedPulsarServiceBaseTest {
private static final Logger LOG = LoggerFactory.getLogger(V1_AdminApiTest.class);
private final String TLS_SERVER_CERT_FILE_PATH = "./src/test/resources/certificate/server.crt";
private final String TLS_SERVER_KEY_FILE_PATH = "./src/test/resources/certificate/server.key";
private MockedPulsarService mockPulsarSetup;
private PulsarService otherPulsar;
private PulsarAdmin adminTls;
private PulsarAdmin otheradmin;
private NamespaceBundleFactory bundleFactory;
@BeforeMethod
@Override
public void setup() throws Exception {
conf.setLoadBalancerEnabled(true);
conf.setBrokerServicePortTls(Optional.of(0));
conf.setWebServicePortTls(Optional.of(0));
conf.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
conf.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
conf.setNumExecutorThreadPoolSize(5);
super.internalSetup();
bundleFactory = new NamespaceBundleFactory(pulsar, Hashing.crc32());
adminTls = spy(PulsarAdmin.builder().tlsTrustCertsFilePath(TLS_SERVER_CERT_FILE_PATH)
.serviceHttpUrl(brokerUrlTls.toString()).build());
// create otherbroker to test redirect on calls that need
// namespace ownership
mockPulsarSetup = new MockedPulsarService(this.conf);
mockPulsarSetup.setup();
otherPulsar = mockPulsarSetup.getPulsar();
otheradmin = mockPulsarSetup.getAdmin();
// Setup namespaces
admin.clusters().createCluster("use", ClusterData.builder().serviceUrl(pulsar.getWebServiceAddress()).build());
TenantInfoImpl tenantInfo = new TenantInfoImpl(Sets.newHashSet("role1", "role2"), Sets.newHashSet("use"));
admin.tenants().createTenant("prop-xyz", tenantInfo);
admin.namespaces().createNamespace("prop-xyz/use/ns1");
}
@AfterMethod(alwaysRun = true)
@Override
public void cleanup() throws Exception {
adminTls.close();
super.internalCleanup();
mockPulsarSetup.cleanup();
}
@DataProvider(name = "numBundles")
public static Object[][] numBundles() {
return new Object[][] { { 1 }, { 4 } };
}
@DataProvider(name = "bundling")
public static Object[][] bundling() {
return new Object[][] { { 0 }, { 4 } };
}
@DataProvider(name = "topicName")
public Object[][] topicNamesProvider() {
return new Object[][] { { "topic_+&*%{}() \\/$@#^%" }, { "simple-topicName" } };
}
@DataProvider(name = "topicType")
public Object[][] topicTypeProvider() {
return new Object[][] { { TopicDomain.persistent.value() }, { TopicDomain.non_persistent.value() } };
}
@Test
public void clusters() throws Exception {
admin.clusters().createCluster("usw",
ClusterData.builder().serviceUrl("http://broker.messaging.use.example.com:8080").build());
// "test" cluster is part of config-default cluster and it's znode gets created when PulsarService creates
// failure-domain znode of this default cluster
assertEquals(admin.clusters().getClusters(), Lists.newArrayList("use", "usw"));
assertEquals(admin.clusters().getCluster("use"),
ClusterData.builder().serviceUrl(pulsar.getWebServiceAddress()).build());
admin.clusters().updateCluster("usw",
ClusterData.builder().serviceUrl("http://new-broker.messaging.use.example.com:8080").build());
assertEquals(admin.clusters().getClusters(), Lists.newArrayList("use", "usw"));
assertEquals(admin.clusters().getCluster("usw"),
ClusterData.builder().serviceUrl("http://new-broker.messaging.use.example.com:8080").build());
admin.clusters().updateCluster("usw",
ClusterData.builder()
.serviceUrl("http://new-broker.messaging.usw.example.com:8080")
.serviceUrlTls("https://new-broker.messaging.usw.example.com:4443")
.build());
assertEquals(admin.clusters().getClusters(), Lists.newArrayList("use", "usw"));
assertEquals(admin.clusters().getCluster("usw"),
ClusterData.builder()
.serviceUrl("http://new-broker.messaging.usw.example.com:8080")
.serviceUrlTls("https://new-broker.messaging.usw.example.com:4443")
.build());
admin.clusters().deleteCluster("usw");
Thread.sleep(300);
assertEquals(admin.clusters().getClusters(), Lists.newArrayList("use"));
admin.namespaces().deleteNamespace("prop-xyz/use/ns1");
admin.clusters().deleteCluster("use");
assertEquals(admin.clusters().getClusters(), Lists.newArrayList());
// Check name validation
try {
admin.clusters().createCluster("bf!", ClusterData.builder().serviceUrl("http://dummy.messaging.example.com").build());
fail("should have failed");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
}
@Test
public void clusterNamespaceIsolationPolicies() throws PulsarAdminException {
try {
// create
String policyName1 = "policy-1";
Map<String, String> parameters1 = new HashMap<>();
parameters1.put("min_limit", "1");
parameters1.put("usage_threshold", "100");
NamespaceIsolationData nsPolicyData1 = NamespaceIsolationData.builder()
.namespaces(Lists.newArrayList("other/use/other.*"))
.primary(Lists.newArrayList(".*")) // match all broker. make it easy to verify `getBrokersWithNamespaceIsolationPolicy` later
.secondary(Lists.newArrayList("prod1-broker.*.messaging.use.example.com"))
.autoFailoverPolicy(AutoFailoverPolicyData.builder()
.policyType(AutoFailoverPolicyType.min_available)
.parameters(parameters1)
.build())
.build();
admin.clusters().createNamespaceIsolationPolicy("use", policyName1, nsPolicyData1);
String policyName2 = "policy-2";
Map<String, String> parameters2 = new HashMap<>();
parameters2.put("min_limit", "1");
parameters2.put("usage_threshold", "100");
NamespaceIsolationData nsPolicyData2 = NamespaceIsolationData.builder()
.namespaces(Lists.newArrayList("other/use/other.*"))
.primary(Lists.newArrayList("prod1-broker[4-6].messaging.use.example.com"))
.secondary(Lists.newArrayList("prod1-broker.*.messaging.use.example.com"))
.autoFailoverPolicy(AutoFailoverPolicyData.builder()
.policyType(AutoFailoverPolicyType.min_available)
.parameters(parameters1)
.build())
.build();
admin.clusters().createNamespaceIsolationPolicy("use", policyName2, nsPolicyData2);
// verify create indirectly with get
Map<String, ? extends NamespaceIsolationData> policiesMap = admin.clusters().getNamespaceIsolationPolicies("use");
assertEquals(policiesMap.get(policyName1), nsPolicyData1);
assertEquals(policiesMap.get(policyName2), nsPolicyData2);
// verify local broker get matched.
List<BrokerNamespaceIsolationData> isoList = admin.clusters().getBrokersWithNamespaceIsolationPolicy("use");
assertEquals(isoList.size(), 1);
assertTrue(isoList.get(0).isPrimary());
// verify update of primary
nsPolicyData1.getPrimary().remove(0);
nsPolicyData1.getPrimary().add("prod1-broker[1-2].messaging.use.example.com");
admin.clusters().updateNamespaceIsolationPolicy("use", policyName1, nsPolicyData1);
// verify primary change
policiesMap = admin.clusters().getNamespaceIsolationPolicies("use");
assertEquals(policiesMap.get(policyName1), nsPolicyData1);
// verify update of secondary
nsPolicyData1.getSecondary().remove(0);
nsPolicyData1.getSecondary().add("prod1-broker[3-4].messaging.use.example.com");
admin.clusters().updateNamespaceIsolationPolicy("use", policyName1, nsPolicyData1);
// verify secondary change
policiesMap = admin.clusters().getNamespaceIsolationPolicies("use");
assertEquals(policiesMap.get(policyName1), nsPolicyData1);
// verify update of failover policy limit
nsPolicyData1.getAutoFailoverPolicy().getParameters().put("min_limit", "10");
admin.clusters().updateNamespaceIsolationPolicy("use", policyName1, nsPolicyData1);
// verify min_limit change
policiesMap = admin.clusters().getNamespaceIsolationPolicies("use");
assertEquals(policiesMap.get(policyName1), nsPolicyData1);
// verify update of failover usage_threshold limit
nsPolicyData1.getAutoFailoverPolicy().getParameters().put("usage_threshold", "80");
admin.clusters().updateNamespaceIsolationPolicy("use", policyName1, nsPolicyData1);
// verify usage_threshold change
policiesMap = admin.clusters().getNamespaceIsolationPolicies("use");
assertEquals(policiesMap.get(policyName1), nsPolicyData1);
// verify single get
NamespaceIsolationDataImpl policy1Data =
(NamespaceIsolationDataImpl) admin.clusters().getNamespaceIsolationPolicy("use", policyName1);
assertEquals(policy1Data, nsPolicyData1);
// verify creation of more than one policy
admin.clusters().createNamespaceIsolationPolicy("use", policyName2, nsPolicyData1);
try {
admin.clusters().getNamespaceIsolationPolicy("use", "no-such-policy");
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof NotFoundException);
}
// verify delete cluster failed
try {
admin.clusters().deleteCluster("use");
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
// verify delete
admin.clusters().deleteNamespaceIsolationPolicy("use", policyName1);
admin.clusters().deleteNamespaceIsolationPolicy("use", policyName2);
try {
admin.clusters().getNamespaceIsolationPolicy("use", policyName1);
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof NotFoundException);
}
try {
admin.clusters().getNamespaceIsolationPolicy("use", policyName2);
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof NotFoundException);
}
try {
admin.clusters().getNamespaceIsolationPolicies("usc");
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof NotFoundException);
}
try {
admin.clusters().getNamespaceIsolationPolicy("usc", "no-such-cluster");
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
try {
admin.clusters().createNamespaceIsolationPolicy("usc", "no-such-cluster", nsPolicyData1);
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
try {
admin.clusters().updateNamespaceIsolationPolicy("usc", "no-such-cluster", policy1Data);
fail("should have raised exception");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
} catch (PulsarAdminException e) {
LOG.warn("TEST FAILED [{}]", e.getMessage());
throw e;
}
}
@Test
public void brokers() throws Exception {
List<String> list = admin.brokers().getActiveBrokers("use");
Assert.assertNotNull(list);
Assert.assertEquals(list.size(), 1);
List<String> list2 = otheradmin.brokers().getActiveBrokers("test");
Assert.assertNotNull(list2);
Assert.assertEquals(list2.size(), 1);
Map<String, NamespaceOwnershipStatus> nsMap = admin.brokers().getOwnedNamespaces("use", list.get(0));
// since sla-monitor ns is not created nsMap.size() == 1 (for HeartBeat Namespace)
Assert.assertEquals(nsMap.size(), 2);
for (String ns : nsMap.keySet()) {
NamespaceOwnershipStatus nsStatus = nsMap.get(ns);
if (ns.equals(
NamespaceService.getHeartbeatNamespace(pulsar.getAdvertisedAddress(), pulsar.getConfiguration())
+ "/0x00000000_0xffffffff")) {
assertEquals(nsStatus.broker_assignment, BrokerAssignment.shared);
assertFalse(nsStatus.is_controlled);
assertTrue(nsStatus.is_active);
}
}
String[] parts = list.get(0).split(":");
Assert.assertEquals(parts.length, 2);
Map<String, NamespaceOwnershipStatus> nsMap2 = adminTls.brokers().getOwnedNamespaces("use",
String.format("%s:%d", parts[0], pulsar.getListenPortHTTPS().get()));
Assert.assertEquals(nsMap2.size(), 2);
admin.namespaces().deleteNamespace("prop-xyz/use/ns1");
admin.clusters().deleteCluster("use");
assertEquals(admin.clusters().getClusters(), Lists.newArrayList());
}
/**
* <pre>
* Verifies: zk-update configuration updates service-config
* 1. create znode for dynamic-config
* 2. start pulsar service so, pulsar can set the watch on that znode
* 3. update the configuration with new value
* 4. wait and verify that new value has been updated
* </pre>
*
* @throws Exception
*/
@Test
public void testUpdateDynamicConfigurationWithZkWatch() throws Exception {
final int initValue = 30000;
pulsar.getConfiguration().setBrokerShutdownTimeoutMs(initValue);
// (1) try to update dynamic field
final long shutdownTime = 10;
// update configuration
admin.brokers().updateDynamicConfiguration("brokerShutdownTimeoutMs", Long.toString(shutdownTime));
// sleep incrementally as zk-watch notification is async and may take some time
for (int i = 0; i < 5; i++) {
if (pulsar.getConfiguration().getBrokerShutdownTimeoutMs() != initValue) {
Thread.sleep(50 + (i * 10));
}
}
// wait config to be updated
for (int i = 0; i < 5; i++) {
if (pulsar.getConfiguration().getBrokerShutdownTimeoutMs() != shutdownTime) {
Thread.sleep(100 + (i * 10));
} else {
break;
}
}
// verify value is updated
assertEquals(pulsar.getConfiguration().getBrokerShutdownTimeoutMs(), shutdownTime);
// (2) try to update non-dynamic field
try {
admin.brokers().updateDynamicConfiguration("zookeeperServers", "test-zk:1234");
} catch (Exception e) {
assertTrue(e instanceof PreconditionFailedException);
}
// (3) try to update non-existent field
try {
admin.brokers().updateDynamicConfiguration("test", Long.toString(shutdownTime));
} catch (Exception e) {
assertTrue(e instanceof PreconditionFailedException);
}
}
/**
* Verifies broker sets watch on dynamic-configuration map even with invalid init json data
*
* <pre>
* 1. Set invalid json at dynamic-config znode
* 2. Broker fails to deserialize znode content but sets the watch on znode
* 3. Update znode with valid json map
* 4. Broker should get watch and update the dynamic-config map
* </pre>
*
* @throws Exception
*/
@Test
public void testInvalidDynamicConfigContentInZK() throws Exception {
final int newValue = 10;
// set invalid data into dynamic-config znode so, broker startup fail to deserialize data
pulsar.getLocalMetadataStore().put("/admin/configuration", "$".getBytes(),
Optional.empty()).join();
stopBroker();
// start broker: it should have set watch even if with failure of deserialization
startBroker();
Assert.assertNotEquals(pulsar.getConfiguration().getBrokerShutdownTimeoutMs(), newValue);
// update zk with config-value which should fire watch and broker should update the config value
Map<String, String> configMap = Maps.newHashMap();
configMap.put("brokerShutdownTimeoutMs", Integer.toString(newValue));
pulsar.getLocalMetadataStore().put("/admin/configuration",
ObjectMapperFactory.getThreadLocal().writeValueAsBytes(configMap),
Optional.empty()).join();
// wait config to be updated
for (int i = 0; i < 5; i++) {
if (pulsar.getConfiguration().getBrokerShutdownTimeoutMs() != newValue) {
Thread.sleep(100 + (i * 10));
} else {
break;
}
}
// verify value is updated
assertEquals(pulsar.getConfiguration().getBrokerShutdownTimeoutMs(), newValue);
}
/**
* <pre>
* verifies: that registerListener updates pulsar.config value with newly updated zk-dynamic config
* 1.start pulsar
* 2.update zk-config with admin api
* 3. trigger watch and listener
* 4. verify that config is updated
* </pre>
*
* @throws Exception
*/
@Test
public void testUpdateDynamicLocalConfiguration() throws Exception {
// (1) try to update dynamic field
final long initValue = 30000;
final long shutdownTime = 10;
pulsar.getConfiguration().setBrokerShutdownTimeoutMs(initValue);
// update configuration
admin.brokers().updateDynamicConfiguration("brokerShutdownTimeoutMs", Long.toString(shutdownTime));
// sleep incrementally as zk-watch notification is async and may take some time
for (int i = 0; i < 5; i++) {
if (pulsar.getConfiguration().getBrokerShutdownTimeoutMs() == initValue) {
Thread.sleep(50 + (i * 10));
}
}
// verify value is updated
assertEquals(pulsar.getConfiguration().getBrokerShutdownTimeoutMs(), shutdownTime);
}
@Test
public void testUpdatableConfigurationName() throws Exception {
// (1) try to update dynamic field
final String configName = "brokerShutdownTimeoutMs";
assertTrue(admin.brokers().getDynamicConfigurationNames().contains(configName));
}
@Test
public void testGetDynamicLocalConfiguration() throws Exception {
// (1) try to update dynamic field
final String configName = "brokerShutdownTimeoutMs";
final long shutdownTime = 10;
pulsar.getConfiguration().setBrokerShutdownTimeoutMs(30000);
Map<String, String> configs = admin.brokers().getAllDynamicConfigurations();
assertTrue(configs.isEmpty());
assertNotEquals(pulsar.getConfiguration().getBrokerShutdownTimeoutMs(), shutdownTime);
// update configuration
admin.brokers().updateDynamicConfiguration(configName, Long.toString(shutdownTime));
// Now, znode is created: updateConfigurationAndregisterListeners and check if configuration updated
assertEquals(Long.parseLong(admin.brokers().getAllDynamicConfigurations().get(configName)), shutdownTime);
}
@Test
public void properties() throws PulsarAdminException {
Set<String> allowedClusters = Sets.newHashSet("use");
TenantInfoImpl tenantInfo = new TenantInfoImpl(Sets.newHashSet("role1", "role2"), allowedClusters);
admin.tenants().updateTenant("prop-xyz", tenantInfo);
assertEquals(admin.tenants().getTenants(), Lists.newArrayList("prop-xyz"));
assertEquals(admin.tenants().getTenantInfo("prop-xyz"), tenantInfo);
TenantInfoImpl newPropertyAdmin = new TenantInfoImpl(Sets.newHashSet("role3", "role4"), allowedClusters);
admin.tenants().updateTenant("prop-xyz", newPropertyAdmin);
assertEquals(admin.tenants().getTenantInfo("prop-xyz"), newPropertyAdmin);
admin.namespaces().deleteNamespace("prop-xyz/use/ns1");
admin.tenants().deleteTenant("prop-xyz");
assertEquals(admin.tenants().getTenants(), Lists.newArrayList());
// Check name validation
try {
admin.tenants().createTenant("prop-xyz&", tenantInfo);
fail("should have failed");
} catch (PulsarAdminException e) {
assertTrue(e instanceof PreconditionFailedException);
}
}
@Test
public void namespaces() throws Exception {
admin.clusters().createCluster("usw", ClusterData.builder().build());
TenantInfoImpl tenantInfo = new TenantInfoImpl(Sets.newHashSet("role1", "role2"),
Sets.newHashSet("use", "usw"));
admin.tenants().updateTenant("prop-xyz", tenantInfo);
assertEquals(admin.namespaces().getPolicies("prop-xyz/use/ns1").bundles, PoliciesUtil.defaultBundle());
admin.namespaces().createNamespace("prop-xyz/use/ns2");
admin.namespaces().createNamespace("prop-xyz/use/ns3", 4);
assertEquals(admin.namespaces().getPolicies("prop-xyz/use/ns3").bundles.getNumBundles(), 4);
assertEquals(admin.namespaces().getPolicies("prop-xyz/use/ns3").bundles.getBoundaries().size(), 5);
admin.namespaces().deleteNamespace("prop-xyz/use/ns3");
try {
admin.namespaces().createNamespace("non-existing/usw/ns1");
fail("Should not have passed");
} catch (NotFoundException e) {
// Ok
}
assertEquals(admin.namespaces().getNamespaces("prop-xyz"),
Lists.newArrayList("prop-xyz/use/ns1", "prop-xyz/use/ns2"));
assertEquals(admin.namespaces().getNamespaces("prop-xyz", "use"),
Lists.newArrayList("prop-xyz/use/ns1", "prop-xyz/use/ns2"));
try {
admin.namespaces().createNamespace("prop-xyz/usc/ns1");
fail("Should not have passed");
} catch (NotAuthorizedException e) {
// Ok, got the non authorized exception since usc cluster is not in the allowed clusters list.
}
// no need to clear cache once authorization-provide also start using metadata-store
clearCache();
admin.namespaces().grantPermissionOnNamespace("prop-xyz/use/ns1", "my-role", EnumSet.allOf(AuthAction.class));
Policies policies = new Policies();
policies.bundles = PoliciesUtil.defaultBundle();
policies.auth_policies.getNamespaceAuthentication().put("my-role", EnumSet.allOf(AuthAction.class));
policies.is_allow_auto_update_schema = conf.isAllowAutoUpdateSchemaEnabled();
assertEquals(admin.namespaces().getPolicies("prop-xyz/use/ns1"), policies);
assertEquals(admin.namespaces().getPermissions("prop-xyz/use/ns1"), policies.auth_policies.getNamespaceAuthentication());
assertEquals(admin.namespaces().getTopics("prop-xyz/use/ns1"), Lists.newArrayList());
admin.namespaces().revokePermissionsOnNamespace("prop-xyz/use/ns1", "my-role");
policies.auth_policies.getNamespaceAuthentication().remove("my-role");
policies.is_allow_auto_update_schema = conf.isAllowAutoUpdateSchemaEnabled();
assertEquals(admin.namespaces().getPolicies("prop-xyz/use/ns1"), policies);
assertNull(admin.namespaces().getPersistence("prop-xyz/use/ns1"));
admin.namespaces().setPersistence("prop-xyz/use/ns1", new PersistencePolicies(3, 2, 1, 10.0));
assertEquals(admin.namespaces().getPersistence("prop-xyz/use/ns1"), new PersistencePolicies(3, 2, 1, 10.0));
// Force topic creation and namespace being loaded
Producer<byte[]> producer = pulsarClient.newProducer(Schema.BYTES).topic("persistent://prop-xyz/use/ns1/my-topic").create();
producer.close();
admin.topics().delete("persistent://prop-xyz/use/ns1/my-topic");
admin.namespaces().unloadNamespaceBundle("prop-xyz/use/ns1", "0x00000000_0xffffffff");
NamespaceName ns = NamespaceName.get("prop-xyz/use/ns1");
// Now, w/ bundle policies, we will use default bundle
NamespaceBundle defaultBundle = bundleFactory.getFullBundle(ns);
int i = 0;
for (; i < 10; i++) {
Optional<NamespaceEphemeralData> data1 = pulsar.getNamespaceService().getOwnershipCache()
.getOwnerAsync(defaultBundle).get();
if (!data1.isPresent()) {
// Already unloaded
break;
}
LOG.info("Waiting for unload namespace {} to complete. Current service unit isDisabled: {}", defaultBundle,
data1.get().isDisabled());
Thread.sleep(1000);
}
assertTrue(i < 10);
admin.namespaces().deleteNamespace("prop-xyz/use/ns1");
assertEquals(admin.namespaces().getNamespaces("prop-xyz", "use"), Lists.newArrayList("prop-xyz/use/ns2"));
try {
admin.namespaces().unload("prop-xyz/use/ns1");
fail("should have raised exception");
} catch (Exception e) {
// OK excepted
}
// Force topic creation and namespace being loaded
producer = pulsarClient.newProducer(Schema.BYTES).topic("persistent://prop-xyz/use/ns2/my-topic").create();
producer.close();
admin.topics().delete("persistent://prop-xyz/use/ns2/my-topic");
// both unload and delete should succeed for ns2 on other broker with a redirect
// otheradmin.namespaces().unload("prop-xyz/use/ns2");
}
@Test(dataProvider = "topicName")
public void persistentTopics(String topicName) throws Exception {
assertEquals(admin.topics().getList("prop-xyz/use/ns1"), Lists.newArrayList());
final String persistentTopicName = "persistent://prop-xyz/use/ns1/" + topicName;
// Force to create a topic
publishMessagesOnPersistentTopic("persistent://prop-xyz/use/ns1/" + topicName, 0);
assertEquals(admin.topics().getList("prop-xyz/use/ns1"),
Lists.newArrayList("persistent://prop-xyz/use/ns1/" + topicName));
// create consumer and subscription
@Cleanup
PulsarClient client = PulsarClient.builder()
.serviceUrl(pulsar.getWebServiceAddress())
.statsInterval(0, TimeUnit.SECONDS)
.build();
Consumer<byte[]> consumer = client.newConsumer().topic(persistentTopicName).subscriptionName("my-sub")
.subscriptionType(SubscriptionType.Exclusive).subscribe();
assertEquals(admin.topics().getSubscriptions(persistentTopicName), Lists.newArrayList("my-sub"));
publishMessagesOnPersistentTopic("persistent://prop-xyz/use/ns1/" + topicName, 10);
TopicStats topicStats = admin.topics().getStats(persistentTopicName);
assertEquals(topicStats.getSubscriptions().keySet(), Sets.newTreeSet(Lists.newArrayList("my-sub")));
assertEquals(topicStats.getSubscriptions().get("my-sub").getConsumers().size(), 1);
assertEquals(topicStats.getSubscriptions().get("my-sub").getMsgBacklog(), 10);
assertEquals(topicStats.getPublishers().size(), 0);
PersistentTopicInternalStats internalStats = admin.topics().getInternalStats(persistentTopicName, false);
assertEquals(internalStats.cursors.keySet(), Sets.newTreeSet(Lists.newArrayList("my-sub")));
List<Message<byte[]>> messages = admin.topics().peekMessages(persistentTopicName, "my-sub", 3);
assertEquals(messages.size(), 3);
for (int i = 0; i < 3; i++) {
String expectedMessage = "message-" + i;
assertEquals(messages.get(i).getData(), expectedMessage.getBytes());
}
messages = admin.topics().peekMessages(persistentTopicName, "my-sub", 15);
assertEquals(messages.size(), 10);
for (int i = 0; i < 10; i++) {
String expectedMessage = "message-" + i;
assertEquals(messages.get(i).getData(), expectedMessage.getBytes());
}
admin.topics().skipMessages(persistentTopicName, "my-sub", 5);
topicStats = admin.topics().getStats(persistentTopicName);
assertEquals(topicStats.getSubscriptions().get("my-sub").getMsgBacklog(), 5);
admin.topics().skipAllMessages(persistentTopicName, "my-sub");
topicStats = admin.topics().getStats(persistentTopicName);
assertEquals(topicStats.getSubscriptions().get("my-sub").getMsgBacklog(), 0);
consumer.close();
client.close();
admin.topics().deleteSubscription(persistentTopicName, "my-sub");
assertEquals(admin.topics().getSubscriptions(persistentTopicName), Lists.newArrayList());
topicStats = admin.topics().getStats(persistentTopicName);
assertEquals(topicStats.getSubscriptions().keySet(), Sets.newTreeSet());
assertEquals(topicStats.getPublishers().size(), 0);
try {
admin.topics().skipAllMessages(persistentTopicName, "my-sub");
} catch (NotFoundException e) {
}
admin.topics().delete(persistentTopicName);
try {
admin.topics().delete(persistentTopicName);
fail("Should have received 404");
} catch (NotFoundException e) {
}
assertEquals(admin.topics().getList("prop-xyz/use/ns1"), Lists.newArrayList());
}
@Test(dataProvider = "topicName")
public void partitionedTopics(String topicName) throws Exception {
assertEquals(admin.topics().getPartitionedTopicList("prop-xyz/use/ns1"), Lists.newArrayList());
final String partitionedTopicName = "persistent://prop-xyz/use/ns1/" + topicName;
admin.topics().createPartitionedTopic(partitionedTopicName, 4);
assertEquals(admin.topics().getPartitionedTopicList("prop-xyz/use/ns1"),
Lists.newArrayList(partitionedTopicName));
assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 4);
List<String> topics = admin.topics().getList("prop-xyz/use/ns1");
assertEquals(topics.size(), 4);
try {
admin.topics().getPartitionedTopicMetadata("persistent://prop-xyz/use/ns1/ds2");
fail("getPartitionedTopicMetadata of persistent://prop-xyz/use/ns1/ds2 should not succeed");
} catch (NotFoundException expected) {
}
// create consumer and subscription
@Cleanup
PulsarClient client = PulsarClient.builder()
.serviceUrl(pulsar.getWebServiceAddress())
.statsInterval(0, TimeUnit.SECONDS)
.build();
Consumer<byte[]> consumer = client.newConsumer().topic(partitionedTopicName).subscriptionName("my-sub")
.subscriptionType(SubscriptionType.Exclusive).subscribe();
assertEquals(admin.topics().getSubscriptions(partitionedTopicName), Lists.newArrayList("my-sub"));
try {
admin.topics().deleteSubscription(partitionedTopicName, "my-sub");
fail("should have failed");
} catch (PulsarAdminException.PreconditionFailedException e) {
// ok
} catch (Exception e) {
fail(e.getMessage());
}
List<String> subscriptions = admin.topics().getSubscriptions(partitionedTopicName);
assertEquals(subscriptions.size(), 1);
Consumer<byte[]> consumer1 = client.newConsumer().topic(partitionedTopicName).subscriptionName("my-sub-1")
.subscribe();
assertEquals(Sets.newHashSet(admin.topics().getSubscriptions(partitionedTopicName)),
Sets.newHashSet("my-sub", "my-sub-1"));
consumer1.close();
admin.topics().deleteSubscription(partitionedTopicName, "my-sub-1");
assertEquals(admin.topics().getSubscriptions(partitionedTopicName), Lists.newArrayList("my-sub"));
Producer<byte[]> producer = client.newProducer(Schema.BYTES)
.topic(partitionedTopicName)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.RoundRobinPartition)
.create();
for (int i = 0; i < 10; i++) {
String message = "message-" + i;
producer.send(message.getBytes());
}
assertEquals(Sets.newHashSet(admin.topics().getList("prop-xyz/use/ns1")),
Sets.newHashSet(partitionedTopicName + "-partition-0", partitionedTopicName + "-partition-1",
partitionedTopicName + "-partition-2", partitionedTopicName + "-partition-3"));
// test cumulative stats for partitioned topic
PartitionedTopicStats topicStats = admin.topics().getPartitionedStats(partitionedTopicName, false);
assertEquals(topicStats.getSubscriptions().keySet(), Sets.newTreeSet(Lists.newArrayList("my-sub")));
assertEquals(topicStats.getSubscriptions().get("my-sub").getConsumers().size(), 1);
assertEquals(topicStats.getSubscriptions().get("my-sub").getMsgBacklog(), 10);
assertEquals(topicStats.getPublishers().size(), 1);
assertEquals(topicStats.getPartitions(), Maps.newHashMap());
// test per partition stats for partitioned topic
topicStats = admin.topics().getPartitionedStats(partitionedTopicName, true);
assertEquals(topicStats.getMetadata().partitions, 4);
assertEquals(topicStats.getPartitions().keySet(),
Sets.newHashSet(partitionedTopicName + "-partition-0", partitionedTopicName + "-partition-1",
partitionedTopicName + "-partition-2", partitionedTopicName + "-partition-3"));
TopicStats partitionStats = topicStats.getPartitions().get(partitionedTopicName + "-partition-0");
assertEquals(partitionStats.getPublishers().size(), 1);
assertEquals(partitionStats.getSubscriptions().get("my-sub").getConsumers().size(), 1);
assertEquals(partitionStats.getSubscriptions().get("my-sub").getMsgBacklog(), 3, 1);
try {
admin.topics().skipMessages(partitionedTopicName, "my-sub", 5);
fail("skip messages for partitioned topics should fail");
} catch (Exception e) {
// ok
}
admin.topics().skipAllMessages(partitionedTopicName, "my-sub");
topicStats = admin.topics().getPartitionedStats(partitionedTopicName, false);
assertEquals(topicStats.getSubscriptions().get("my-sub").getMsgBacklog(), 0);
producer.close();
consumer.close();
admin.topics().deleteSubscription(partitionedTopicName, "my-sub");
assertEquals(admin.topics().getSubscriptions(partitionedTopicName), Lists.newArrayList());
try {
admin.topics().createPartitionedTopic(partitionedTopicName, 32);
fail("Should have failed as the partitioned topic exists with its partition created");
} catch (ConflictException ignore) {
}
producer = client.newProducer(Schema.BYTES)
.topic(partitionedTopicName)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.SinglePartition)
.create();
topics = admin.topics().getList("prop-xyz/use/ns1");
assertEquals(topics.size(), 4);
try {
admin.topics().deletePartitionedTopic(partitionedTopicName);
fail("The topic is busy");
} catch (PreconditionFailedException pfe) {
// ok
}
producer.close();
client.close();
admin.topics().deletePartitionedTopic(partitionedTopicName);
try {
admin.topics().getPartitionedTopicMetadata(partitionedTopicName);
fail("getPartitionedTopicMetadata of " + partitionedTopicName + " should not succeed");
} catch (NotFoundException expected) {
}
admin.topics().createPartitionedTopic(partitionedTopicName, 32);
assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 32);
try {
admin.topics().deletePartitionedTopic("persistent://prop-xyz/use/ns1/ds2");
fail("Should have failed as the partitioned topic was not created");
} catch (NotFoundException nfe) {
}
admin.topics().deletePartitionedTopic(partitionedTopicName);
// delete a partitioned topic in a global namespace
admin.topics().createPartitionedTopic(partitionedTopicName, 4);
admin.topics().deletePartitionedTopic(partitionedTopicName);
}
@Test(dataProvider = "numBundles")
public void testDeleteNamespaceBundle(Integer numBundles) throws Exception {
admin.namespaces().deleteNamespace("prop-xyz/use/ns1");
admin.namespaces().createNamespace("prop-xyz/use/ns1-bundles", numBundles);
// since we have 2 brokers running, we try to let both of them acquire bundle ownership
admin.lookups().lookupTopic("persistent://prop-xyz/use/ns1-bundles/ds1");
admin.lookups().lookupTopic("persistent://prop-xyz/use/ns1-bundles/ds2");
admin.lookups().lookupTopic("persistent://prop-xyz/use/ns1-bundles/ds3");
admin.lookups().lookupTopic("persistent://prop-xyz/use/ns1-bundles/ds4");
assertEquals(admin.namespaces().getTopics("prop-xyz/use/ns1-bundles"), Lists.newArrayList());
admin.namespaces().deleteNamespace("prop-xyz/use/ns1-bundles");
assertEquals(admin.namespaces().getNamespaces("prop-xyz", "use"), Lists.newArrayList());
}
@Test
public void testNamespaceSplitBundle() throws Exception {
// Force to create a topic
final String namespace = "prop-xyz/use/ns1";
final String topicName = "persistent://" + namespace + "/ds2";
Producer<byte[]> producer = pulsarClient.newProducer(Schema.BYTES)
.topic(topicName)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.SinglePartition)
.create();
producer.send("message".getBytes());
publishMessagesOnPersistentTopic(topicName, 0);
assertEquals(admin.topics().getList(namespace), Lists.newArrayList(topicName));
try {
admin.namespaces().splitNamespaceBundle(namespace, "0x00000000_0xffffffff", true, null);
} catch (Exception e) {
fail("split bundle shouldn't have thrown exception");
}
// bundle-factory cache must have updated split bundles
NamespaceBundles bundles = bundleFactory.getBundles(NamespaceName.get(namespace));
String[] splitRange = { namespace + "/0x00000000_0x7fffffff", namespace + "/0x7fffffff_0xffffffff" };
for (int i = 0; i < bundles.getBundles().size(); i++) {
assertEquals(bundles.getBundles().get(i).toString(), splitRange[i]);
}
producer.close();
}
@Test
public void testNamespaceSplitBundleConcurrent() throws Exception {
// Force to create a topic
final String namespace = "prop-xyz/use/ns1";
final String topicName = "persistent://" + namespace + "/ds2";
Producer<byte[]> producer = pulsarClient.newProducer(Schema.BYTES)
.topic(topicName)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.SinglePartition)
.create();