/
ConfigDef.java
1364 lines (1238 loc) · 58.4 KB
/
ConfigDef.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.kafka.common.config;
import org.apache.kafka.common.config.types.Password;
import org.apache.kafka.common.utils.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* This class is used for specifying the set of expected configurations. For each configuration, you can specify
* the name, the type, the default value, the documentation, the group information, the order in the group,
* the width of the configuration value and the name suitable for display in the UI.
*
* You can provide special validation logic used for single configuration validation by overriding {@link Validator}.
*
* Moreover, you can specify the dependents of a configuration. The valid values and visibility of a configuration
* may change according to the values of other configurations. You can override {@link Recommender} to get valid
* values and set visibility of a configuration given the current configuration values.
*
* <p/>
* To use the class:
* <p/>
* <pre>
* ConfigDef defs = new ConfigDef();
*
* defs.define("config_with_default", Type.STRING, "default string value", "Configuration with default value.");
* defs.define("config_with_validator", Type.INT, 42, Range.atLeast(0), "Configuration with user provided validator.");
* defs.define("config_with_dependents", Type.INT, "Configuration with dependents.", "group", 1, "Config With Dependents", Arrays.asList("config_with_default","config_with_validator"));
*
* Map<String, String> props = new HashMap<>();
* props.put("config_with_default", "some value");
* props.put("config_with_dependents", "some other value");
*
* Map<String, Object> configs = defs.parse(props);
* // will return "some value"
* String someConfig = (String) configs.get("config_with_default");
* // will return default value of 42
* int anotherConfig = (Integer) configs.get("config_with_validator");
*
* To validate the full configuration, use:
* List<Config> configs = defs.validate(props);
* The {@link Config} contains updated configuration information given the current configuration values.
* </pre>
* <p/>
* This class can be used standalone or in combination with {@link AbstractConfig} which provides some additional
* functionality for accessing configs.
*/
public class ConfigDef {
private static final Pattern COMMA_WITH_WHITESPACE = Pattern.compile("\\s*,\\s*");
/**
* A unique Java object which represents the lack of a default value.
*/
public static final Object NO_DEFAULT_VALUE = new Object();
private final Map<String, ConfigKey> configKeys;
private final List<String> groups;
private Set<String> configsWithNoParent;
public ConfigDef() {
configKeys = new LinkedHashMap<>();
groups = new LinkedList<>();
configsWithNoParent = null;
}
public ConfigDef(ConfigDef base) {
configKeys = new LinkedHashMap<>(base.configKeys);
groups = new LinkedList<>(base.groups);
// It is not safe to copy this from the parent because we may subsequently add to the set of configs and
// invalidate this
configsWithNoParent = null;
}
/**
* Returns unmodifiable set of properties names defined in this {@linkplain ConfigDef}
*
* @return new unmodifiable {@link Set} instance containing the keys
*/
public Set<String> names() {
return Collections.unmodifiableSet(configKeys.keySet());
}
public Map<String, Object> defaultValues() {
Map<String, Object> defaultValues = new HashMap<>();
for (ConfigKey key : configKeys.values()) {
if (key.defaultValue != NO_DEFAULT_VALUE)
defaultValues.put(key.name, key.defaultValue);
}
return defaultValues;
}
public ConfigDef define(ConfigKey key) {
if (configKeys.containsKey(key.name)) {
throw new ConfigException("Configuration " + key.name + " is defined twice.");
}
if (key.group != null && !groups.contains(key.group)) {
groups.add(key.group);
}
configKeys.put(key.name, key);
return this;
}
/**
* Define a new configuration
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param validator the validator to use in checking the correctness of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @param recommender the recommender provides valid values given the parent configuration values
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, List<String> dependents, Recommender recommender) {
return define(new ConfigKey(name, type, defaultValue, validator, importance, documentation, group, orderInGroup, width, displayName, dependents, recommender, false));
}
/**
* Define a new configuration with no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param validator the validator to use in checking the correctness of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, List<String> dependents) {
return define(name, type, defaultValue, validator, importance, documentation, group, orderInGroup, width, displayName, dependents, null);
}
/**
* Define a new configuration with no dependents
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param validator the validator to use in checking the correctness of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param recommender the recommender provides valid values given the parent configuration values
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, Recommender recommender) {
return define(name, type, defaultValue, validator, importance, documentation, group, orderInGroup, width, displayName, Collections.emptyList(), recommender);
}
/**
* Define a new configuration with no dependents and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param validator the validator to use in checking the correctness of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName) {
return define(name, type, defaultValue, validator, importance, documentation, group, orderInGroup, width, displayName, Collections.<String>emptyList());
}
/**
* Define a new configuration with no special validation logic
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @param recommender the recommender provides valid values given the parent configuration values
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, List<String> dependents, Recommender recommender) {
return define(name, type, defaultValue, null, importance, documentation, group, orderInGroup, width, displayName, dependents, recommender);
}
/**
* Define a new configuration with no special validation logic and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, List<String> dependents) {
return define(name, type, defaultValue, null, importance, documentation, group, orderInGroup, width, displayName, dependents, null);
}
/**
* Define a new configuration with no special validation logic and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param recommender the recommender provides valid values given the parent configuration values
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName, Recommender recommender) {
return define(name, type, defaultValue, null, importance, documentation, group, orderInGroup, width, displayName, Collections.emptyList(), recommender);
}
/**
* Define a new configuration with no special validation logic, not dependents and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Importance importance, String documentation,
String group, int orderInGroup, Width width, String displayName) {
return define(name, type, defaultValue, null, importance, documentation, group, orderInGroup, width, displayName, Collections.<String>emptyList());
}
/**
* Define a new configuration with no default value and no special validation logic
* @param name the name of the config parameter
* @param type the type of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @param recommender the recommender provides valid values given the parent configuration value
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Importance importance, String documentation, String group, int orderInGroup,
Width width, String displayName, List<String> dependents, Recommender recommender) {
return define(name, type, NO_DEFAULT_VALUE, null, importance, documentation, group, orderInGroup, width, displayName, dependents, recommender);
}
/**
* Define a new configuration with no default value, no special validation logic and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param dependents the configurations that are dependents of this configuration
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Importance importance, String documentation, String group, int orderInGroup,
Width width, String displayName, List<String> dependents) {
return define(name, type, NO_DEFAULT_VALUE, null, importance, documentation, group, orderInGroup, width, displayName, dependents, null);
}
/**
* Define a new configuration with no default value, no special validation logic and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @param recommender the recommender provides valid values given the parent configuration value
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Importance importance, String documentation, String group, int orderInGroup,
Width width, String displayName, Recommender recommender) {
return define(name, type, NO_DEFAULT_VALUE, null, importance, documentation, group, orderInGroup, width, displayName, Collections.emptyList(), recommender);
}
/**
* Define a new configuration with no default value, no special validation logic, no dependents and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @param group the group this config belongs to
* @param orderInGroup the order of this config in the group
* @param width the width of the config
* @param displayName the name suitable for display
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Importance importance, String documentation, String group, int orderInGroup,
Width width, String displayName) {
return define(name, type, NO_DEFAULT_VALUE, null, importance, documentation, group, orderInGroup, width, displayName, Collections.<String>emptyList());
}
/**
* Define a new configuration with no group, no order in group, no width, no display name, no dependents and no custom recommender
* @param name the name of the config parameter
* @param type the type of the config
* @param defaultValue the default value to use if this config isn't present
* @param validator the validator to use in checking the correctness of the config
* @param importance the importance of this config
* @param documentation the documentation string for the config
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentation) {
return define(name, type, defaultValue, validator, importance, documentation, null, -1, Width.NONE, name);
}
/**
* Define a new configuration with no special validation logic
* @param name The name of the config parameter
* @param type The type of the config
* @param defaultValue The default value to use if this config isn't present
* @param importance The importance of this config: is this something you will likely need to change.
* @param documentation The documentation string for the config
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Object defaultValue, Importance importance, String documentation) {
return define(name, type, defaultValue, null, importance, documentation);
}
/**
* Define a new configuration with no default value and no special validation logic
* @param name The name of the config parameter
* @param type The type of the config
* @param importance The importance of this config: is this something you will likely need to change.
* @param documentation The documentation string for the config
* @return This ConfigDef so you can chain calls
*/
public ConfigDef define(String name, Type type, Importance importance, String documentation) {
return define(name, type, NO_DEFAULT_VALUE, null, importance, documentation);
}
/**
* Define a new internal configuration. Internal configuration won't show up in the docs and aren't
* intended for general use.
* @param name The name of the config parameter
* @param type The type of the config
* @param defaultValue The default value to use if this config isn't present
* @param importance
* @return This ConfigDef so you can chain calls
*/
public ConfigDef defineInternal(final String name, final Type type, final Object defaultValue, final Importance importance) {
return define(new ConfigKey(name, type, defaultValue, null, importance, "", "", -1, Width.NONE, name, Collections.<String>emptyList(), null, true));
}
/**
* Get the configuration keys
* @return a map containing all configuration keys
*/
public Map<String, ConfigKey> configKeys() {
return configKeys;
}
/**
* Get the groups for the configuration
* @return a list of group names
*/
public List<String> groups() {
return groups;
}
/**
* Add standard SSL client configuration options.
* @return this
*/
public ConfigDef withClientSslSupport() {
SslConfigs.addClientSslSupport(this);
return this;
}
/**
* Add standard SASL client configuration options.
* @return this
*/
public ConfigDef withClientSaslSupport() {
SaslConfigs.addClientSaslSupport(this);
return this;
}
/**
* Parse and validate configs against this configuration definition. The input is a map of configs. It is expected
* that the keys of the map are strings, but the values can either be strings or they may already be of the
* appropriate type (int, string, etc). This will work equally well with either java.util.Properties instances or a
* programmatically constructed map.
*
* @param props The configs to parse and validate.
* @return Parsed and validated configs. The key will be the config name and the value will be the value parsed into
* the appropriate type (int, string, etc).
*/
public Map<String, Object> parse(Map<?, ?> props) {
// Check all configurations are defined
List<String> undefinedConfigKeys = undefinedDependentConfigs();
if (!undefinedConfigKeys.isEmpty()) {
String joined = Utils.join(undefinedConfigKeys, ",");
throw new ConfigException("Some configurations in are referred in the dependents, but not defined: " + joined);
}
// parse all known keys
Map<String, Object> values = new HashMap<>();
for (ConfigKey key : configKeys.values())
values.put(key.name, parseValue(key, props.get(key.name), props.containsKey(key.name)));
return values;
}
Object parseValue(ConfigKey key, Object value, boolean isSet) {
Object parsedValue;
if (isSet) {
parsedValue = parseType(key.name, value, key.type);
// props map doesn't contain setting, the key is required because no default value specified - its an error
} else if (NO_DEFAULT_VALUE.equals(key.defaultValue)) {
throw new ConfigException("Missing required configuration \"" + key.name + "\" which has no default value.");
} else {
// otherwise assign setting its default value
parsedValue = key.defaultValue;
}
if (key.validator != null) {
key.validator.ensureValid(key.name, parsedValue);
}
return parsedValue;
}
/**
* Validate the current configuration values with the configuration definition.
* @param props the current configuration values
* @return List of Config, each Config contains the updated configuration information given
* the current configuration values.
*/
public List<ConfigValue> validate(Map<String, String> props) {
return new ArrayList<>(validateAll(props).values());
}
public Map<String, ConfigValue> validateAll(Map<String, String> props) {
Map<String, ConfigValue> configValues = new HashMap<>();
for (String name: configKeys.keySet()) {
configValues.put(name, new ConfigValue(name));
}
List<String> undefinedConfigKeys = undefinedDependentConfigs();
for (String undefinedConfigKey: undefinedConfigKeys) {
ConfigValue undefinedConfigValue = new ConfigValue(undefinedConfigKey);
undefinedConfigValue.addErrorMessage(undefinedConfigKey + " is referred in the dependents, but not defined.");
undefinedConfigValue.visible(false);
configValues.put(undefinedConfigKey, undefinedConfigValue);
}
Map<String, Object> parsed = parseForValidate(props, configValues);
return validate(parsed, configValues);
}
// package accessible for testing
Map<String, Object> parseForValidate(Map<String, String> props, Map<String, ConfigValue> configValues) {
Map<String, Object> parsed = new HashMap<>();
Set<String> configsWithNoParent = getConfigsWithNoParent();
for (String name: configsWithNoParent) {
parseForValidate(name, props, parsed, configValues);
}
return parsed;
}
private Map<String, ConfigValue> validate(Map<String, Object> parsed, Map<String, ConfigValue> configValues) {
Set<String> configsWithNoParent = getConfigsWithNoParent();
for (String name: configsWithNoParent) {
validate(name, parsed, configValues);
}
return configValues;
}
private List<String> undefinedDependentConfigs() {
Set<String> undefinedConfigKeys = new HashSet<>();
for (ConfigKey configKey : configKeys.values()) {
for (String dependent: configKey.dependents) {
if (!configKeys.containsKey(dependent)) {
undefinedConfigKeys.add(dependent);
}
}
}
return new ArrayList<>(undefinedConfigKeys);
}
// package accessible for testing
Set<String> getConfigsWithNoParent() {
if (this.configsWithNoParent != null) {
return this.configsWithNoParent;
}
Set<String> configsWithParent = new HashSet<>();
for (ConfigKey configKey: configKeys.values()) {
List<String> dependents = configKey.dependents;
configsWithParent.addAll(dependents);
}
Set<String> configs = new HashSet<>(configKeys.keySet());
configs.removeAll(configsWithParent);
this.configsWithNoParent = configs;
return configs;
}
private void parseForValidate(String name, Map<String, String> props, Map<String, Object> parsed, Map<String, ConfigValue> configs) {
if (!configKeys.containsKey(name)) {
return;
}
ConfigKey key = configKeys.get(name);
ConfigValue config = configs.get(name);
Object value = null;
if (props.containsKey(key.name)) {
try {
value = parseType(key.name, props.get(key.name), key.type);
} catch (ConfigException e) {
config.addErrorMessage(e.getMessage());
}
} else if (NO_DEFAULT_VALUE.equals(key.defaultValue)) {
config.addErrorMessage("Missing required configuration \"" + key.name + "\" which has no default value.");
} else {
value = key.defaultValue;
}
if (key.validator != null) {
try {
key.validator.ensureValid(key.name, value);
} catch (ConfigException e) {
config.addErrorMessage(e.getMessage());
}
}
config.value(value);
parsed.put(name, value);
for (String dependent: key.dependents) {
parseForValidate(dependent, props, parsed, configs);
}
}
private void validate(String name, Map<String, Object> parsed, Map<String, ConfigValue> configs) {
if (!configKeys.containsKey(name)) {
return;
}
ConfigKey key = configKeys.get(name);
ConfigValue value = configs.get(name);
if (key.recommender != null) {
try {
List<Object> recommendedValues = key.recommender.validValues(name, parsed);
List<Object> originalRecommendedValues = value.recommendedValues();
if (!originalRecommendedValues.isEmpty()) {
Set<Object> originalRecommendedValueSet = new HashSet<>(originalRecommendedValues);
recommendedValues.removeIf(o -> !originalRecommendedValueSet.contains(o));
}
value.recommendedValues(recommendedValues);
value.visible(key.recommender.visible(name, parsed));
} catch (ConfigException e) {
value.addErrorMessage(e.getMessage());
}
}
configs.put(name, value);
for (String dependent: key.dependents) {
validate(dependent, parsed, configs);
}
}
/**
* Parse a value according to its expected type.
* @param name The config name
* @param value The config value
* @param type The expected type
* @return The parsed object
*/
public static Object parseType(String name, Object value, Type type) {
try {
if (value == null) return null;
String trimmed = null;
if (value instanceof String)
trimmed = ((String) value).trim();
switch (type) {
case BOOLEAN:
if (value instanceof String) {
if (trimmed.equalsIgnoreCase("true"))
return true;
else if (trimmed.equalsIgnoreCase("false"))
return false;
else
throw new ConfigException(name, value, "Expected value to be either true or false");
} else if (value instanceof Boolean)
return value;
else
throw new ConfigException(name, value, "Expected value to be either true or false");
case PASSWORD:
if (value instanceof Password)
return value;
else if (value instanceof String)
return new Password(trimmed);
else
throw new ConfigException(name, value, "Expected value to be a string, but it was a " + value.getClass().getName());
case STRING:
if (value instanceof String)
return trimmed;
else
throw new ConfigException(name, value, "Expected value to be a string, but it was a " + value.getClass().getName());
case INT:
if (value instanceof Integer) {
return value;
} else if (value instanceof String) {
return Integer.parseInt(trimmed);
} else {
throw new ConfigException(name, value, "Expected value to be a 32-bit integer, but it was a " + value.getClass().getName());
}
case SHORT:
if (value instanceof Short) {
return value;
} else if (value instanceof String) {
return Short.parseShort(trimmed);
} else {
throw new ConfigException(name, value, "Expected value to be a 16-bit integer (short), but it was a " + value.getClass().getName());
}
case LONG:
if (value instanceof Integer)
return ((Integer) value).longValue();
if (value instanceof Long)
return value;
else if (value instanceof String)
return Long.parseLong(trimmed);
else
throw new ConfigException(name, value, "Expected value to be a 64-bit integer (long), but it was a " + value.getClass().getName());
case DOUBLE:
if (value instanceof Number)
return ((Number) value).doubleValue();
else if (value instanceof String)
return Double.parseDouble(trimmed);
else
throw new ConfigException(name, value, "Expected value to be a double, but it was a " + value.getClass().getName());
case LIST:
if (value instanceof List)
return value;
else if (value instanceof String)
if (trimmed.isEmpty())
return Collections.emptyList();
else
return Arrays.asList(COMMA_WITH_WHITESPACE.split(trimmed, -1));
else
throw new ConfigException(name, value, "Expected a comma separated list.");
case CLASS:
if (value instanceof Class)
return value;
else if (value instanceof String)
return Class.forName(trimmed, true, Utils.getContextOrKafkaClassLoader());
else
throw new ConfigException(name, value, "Expected a Class instance or class name.");
default:
throw new IllegalStateException("Unknown type.");
}
} catch (NumberFormatException e) {
throw new ConfigException(name, value, "Not a number of type " + type);
} catch (ClassNotFoundException e) {
throw new ConfigException(name, value, "Class " + value + " could not be found.");
}
}
public static String convertToString(Object parsedValue, Type type) {
if (parsedValue == null) {
return null;
}
if (type == null) {
return parsedValue.toString();
}
switch (type) {
case BOOLEAN:
case SHORT:
case INT:
case LONG:
case DOUBLE:
case STRING:
case PASSWORD:
return parsedValue.toString();
case LIST:
List<?> valueList = (List<?>) parsedValue;
return Utils.join(valueList, ",");
case CLASS:
Class<?> clazz = (Class<?>) parsedValue;
return clazz.getName();
default:
throw new IllegalStateException("Unknown type.");
}
}
/**
* Converts a map of config (key, value) pairs to a map of strings where each value
* is converted to a string. This method should be used with care since it stores
* actual password values to String. Values from this map should never be used in log entries.
*/
public static Map<String, String> convertToStringMapWithPasswordValues(Map<String, ?> configs) {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, ?> entry : configs.entrySet()) {
Object value = entry.getValue();
String strValue;
if (value instanceof Password)
strValue = ((Password) value).value();
else if (value instanceof List)
strValue = convertToString(value, Type.LIST);
else if (value instanceof Class)
strValue = convertToString(value, Type.CLASS);
else
strValue = convertToString(value, null);
if (strValue != null)
result.put(entry.getKey(), strValue);
}
return result;
}
/**
* The config types
*/
public enum Type {
BOOLEAN, STRING, INT, SHORT, LONG, DOUBLE, LIST, CLASS, PASSWORD
}
/**
* The importance level for a configuration
*/
public enum Importance {
HIGH, MEDIUM, LOW
}
/**
* The width of a configuration value
*/
public enum Width {
NONE, SHORT, MEDIUM, LONG
}
/**
* This is used by the {@link #validate(Map)} to get valid values for a configuration given the current
* configuration values in order to perform full configuration validation and visibility modification.
* In case that there are dependencies between configurations, the valid values and visibility
* for a configuration may change given the values of other configurations.
*/
public interface Recommender {
/**
* The valid values for the configuration given the current configuration values.
* @param name The name of the configuration
* @param parsedConfig The parsed configuration values
* @return The list of valid values. To function properly, the returned objects should have the type
* defined for the configuration using the recommender.
*/
List<Object> validValues(String name, Map<String, Object> parsedConfig);
/**
* Set the visibility of the configuration given the current configuration values.
* @param name The name of the configuration
* @param parsedConfig The parsed configuration values
* @return The visibility of the configuration
*/
boolean visible(String name, Map<String, Object> parsedConfig);
}
/**
* Validation logic the user may provide to perform single configuration validation.
*/
public interface Validator {
/**
* Perform single configuration validation.
* @param name The name of the configuration
* @param value The value of the configuration
* @throws ConfigException if the value is invalid.
*/
void ensureValid(String name, Object value);
}
/**
* Validation logic for numeric ranges
*/
public static class Range implements Validator {
private final Number min;
private final Number max;
/**
* A numeric range with inclusive upper bound and inclusive lower bound
* @param min the lower bound
* @param max the upper bound
*/
private Range(Number min, Number max) {
this.min = min;
this.max = max;
}
/**
* A numeric range that checks only the lower bound
*
* @param min The minimum acceptable value
*/
public static Range atLeast(Number min) {
return new Range(min, null);
}
/**
* A numeric range that checks both the upper (inclusive) and lower bound
*/
public static Range between(Number min, Number max) {
return new Range(min, max);
}
public void ensureValid(String name, Object o) {
if (o == null)
throw new ConfigException(name, null, "Value must be non-null");
Number n = (Number) o;
if (min != null && n.doubleValue() < min.doubleValue())
throw new ConfigException(name, o, "Value must be at least " + min);
if (max != null && n.doubleValue() > max.doubleValue())
throw new ConfigException(name, o, "Value must be no more than " + max);
}
public String toString() {
if (min == null && max == null)
return "[...]";
else if (min == null)
return "[...," + max + "]";
else if (max == null)
return "[" + min + ",...]";
else
return "[" + min + ",...," + max + "]";
}
}
public static class ValidList implements Validator {
final ValidString validString;
private ValidList(List<String> validStrings) {
this.validString = new ValidString(validStrings);
}
public static ValidList in(String... validStrings) {
return new ValidList(Arrays.asList(validStrings));
}
@Override
public void ensureValid(final String name, final Object value) {
@SuppressWarnings("unchecked")
List<String> values = (List<String>) value;
for (String string : values) {
validString.ensureValid(name, string);
}
}
public String toString() {
return validString.toString();
}
}
public static class ValidString implements Validator {
final List<String> validStrings;
private ValidString(List<String> validStrings) {
this.validStrings = validStrings;
}
public static ValidString in(String... validStrings) {
return new ValidString(Arrays.asList(validStrings));
}
@Override
public void ensureValid(String name, Object o) {
String s = (String) o;
if (!validStrings.contains(s)) {
throw new ConfigException(name, o, "String must be one of: " + Utils.join(validStrings, ", "));
}
}
public String toString() {
return "[" + Utils.join(validStrings, ", ") + "]";
}
}
public static class NonNullValidator implements Validator {
@Override
public void ensureValid(String name, Object value) {
if (value == null) {
// Pass in the string null to avoid the spotbugs warning
throw new ConfigException(name, "null", "entry must be non null");
}
}
public String toString() {
return "non-null string";
}
}
public static class CompositeValidator implements Validator {
private final List<Validator> validators;
private CompositeValidator(List<Validator> validators) {
this.validators = Collections.unmodifiableList(validators);
}
public static CompositeValidator of(Validator... validators) {
return new CompositeValidator(Arrays.asList(validators));
}
@Override
public void ensureValid(String name, Object value) {
for (Validator validator: validators) {
validator.ensureValid(name, value);
}
}
@Override
public String toString() {
if (validators == null) return "";
StringBuilder desc = new StringBuilder();
for (Validator v: validators) {
if (desc.length() > 0) {
desc.append(',').append(' ');
}
desc.append(String.valueOf(v));
}
return desc.toString();
}
}
public static class NonEmptyString implements Validator {
@Override
public void ensureValid(String name, Object o) {
String s = (String) o;
if (s != null && s.isEmpty()) {
throw new ConfigException(name, o, "String must be non-empty");
}
}
@Override
public String toString() {
return "non-empty string";
}