-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathSetting.java
2442 lines (2166 loc) · 93.2 KB
/
Setting.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
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.settings;
import org.apache.logging.log4j.Logger;
import org.opensearch.OpenSearchException;
import org.opensearch.OpenSearchParseException;
import org.opensearch.Version;
import org.opensearch.common.Booleans;
import org.opensearch.common.Nullable;
import org.opensearch.common.Strings;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.regex.Regex;
import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.MemorySizeValue;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.DeprecationHandler;
import org.opensearch.common.xcontent.NamedXContentRegistry;
import org.opensearch.common.xcontent.ToXContentObject;
import org.opensearch.common.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A setting. Encapsulates typical stuff like default value, parsing, and scope.
* Some (Settings.Property.Dynamic) can be modified at run time using the API.
* All settings inside opensearch or in any of the plugins should use this type-safe and generic settings infrastructure
* together with {@link AbstractScopedSettings}. This class contains several utility methods that makes it straight forward
* to add settings for the majority of the cases. For instance a simple boolean settings can be defined like this:
* <pre>{@code
* public static final Setting<Boolean> MY_BOOLEAN = Setting.boolSetting("my.bool.setting", true, Setting.Property.NodeScope);}
* </pre>
* To retrieve the value of the setting a {@link Settings} object can be passed directly to the {@link Setting#get(Settings)} method.
* <pre>
* final boolean myBooleanValue = MY_BOOLEAN.get(settings);
* </pre>
* It's recommended to use typed settings rather than string based settings. For example adding a setting for an enum type:
* <pre>{@code
* public enum Color {
* RED, GREEN, BLUE;
* }
* public static final Setting<Color> MY_BOOLEAN =
* new Setting<>("my.color.setting", Color.RED.toString(), Color::valueOf, Setting.Property.NodeScope);
* }
* </pre>
*
* @opensearch.internal
*/
public class Setting<T> implements ToXContentObject {
/**
* Property of the setting
*
* @opensearch.internal
*/
public enum Property {
/**
* should be filtered in some api (mask password/credentials)
*/
Filtered,
/**
* iff this setting can be dynamically updateable
*/
Dynamic,
/**
* mark this setting as final, not updateable even when the context is not dynamic
* ie. Setting this property on an index scoped setting will fail update when the index is closed
*/
Final,
/**
* mark this setting as deprecated
*/
Deprecated,
/**
* Node scope
*/
NodeScope,
/**
* Secure setting values equal on all nodes
*/
Consistent,
/**
* Index scope
*/
IndexScope,
/**
* Mark this setting as not copyable during an index resize (shrink or split). This property can only be applied to settings that
* also have {@link Property#IndexScope}.
*/
NotCopyableOnResize,
/**
* Indicates an index-level setting that is managed internally. Such a setting can only be added to an index on index creation but
* can not be updated via the update API.
*/
InternalIndex,
/**
* Indicates an index-level setting that is privately managed. Such a setting can not even be set on index creation.
*/
PrivateIndex
}
private final Key key;
protected final Function<Settings, String> defaultValue;
@Nullable
protected final Setting<T> fallbackSetting;
private final Function<String, T> parser;
private final Validator<T> validator;
private final EnumSet<Property> properties;
private static final EnumSet<Property> EMPTY_PROPERTIES = EnumSet.noneOf(Property.class);
private Setting(
Key key,
@Nullable Setting<T> fallbackSetting,
Function<Settings, String> defaultValue,
Function<String, T> parser,
Validator<T> validator,
Property... properties
) {
assert this instanceof SecureSetting || this.isGroupSetting() || parser.apply(defaultValue.apply(Settings.EMPTY)) != null
: "parser returned null";
this.key = key;
this.fallbackSetting = fallbackSetting;
this.defaultValue = defaultValue;
this.parser = parser;
this.validator = validator;
if (properties == null) {
throw new IllegalArgumentException("properties cannot be null for setting [" + key + "]");
}
if (properties.length == 0) {
this.properties = EMPTY_PROPERTIES;
} else {
final EnumSet<Property> propertiesAsSet = EnumSet.copyOf(Arrays.asList(properties));
if (propertiesAsSet.contains(Property.Dynamic) && propertiesAsSet.contains(Property.Final)) {
throw new IllegalArgumentException("final setting [" + key + "] cannot be dynamic");
}
checkPropertyRequiresIndexScope(propertiesAsSet, Property.NotCopyableOnResize);
checkPropertyRequiresIndexScope(propertiesAsSet, Property.InternalIndex);
checkPropertyRequiresIndexScope(propertiesAsSet, Property.PrivateIndex);
checkPropertyRequiresNodeScope(propertiesAsSet, Property.Consistent);
this.properties = propertiesAsSet;
}
}
private void checkPropertyRequiresIndexScope(final EnumSet<Property> properties, final Property property) {
if (properties.contains(property) && properties.contains(Property.IndexScope) == false) {
throw new IllegalArgumentException("non-index-scoped setting [" + key + "] can not have property [" + property + "]");
}
}
private void checkPropertyRequiresNodeScope(final EnumSet<Property> properties, final Property property) {
if (properties.contains(property) && properties.contains(Property.NodeScope) == false) {
throw new IllegalArgumentException("non-node-scoped setting [" + key + "] can not have property [" + property + "]");
}
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(Key key, Function<Settings, String> defaultValue, Function<String, T> parser, Property... properties) {
this(key, defaultValue, parser, v -> {}, properties);
}
/**
* Creates a new {@code Setting} instance.
*
* @param key the settings key for this setting
* @param defaultValue a default value function that results a string representation of the default value
* @param parser a parser that parses a string representation into the concrete type for this setting
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting
*/
public Setting(
Key key,
Function<Settings, String> defaultValue,
Function<String, T> parser,
Validator<T> validator,
Property... properties
) {
this(key, null, defaultValue, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, String defaultValue, Function<String, T> parser, Property... properties) {
this(key, s -> defaultValue, parser, properties);
}
/**
* Creates a new {@code Setting} instance.
*
* @param key the settings key for this setting
* @param defaultValue a default value function that results a string representation of the default value
* @param parser a parser that parses a string representation into the concrete type for this setting
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting
*/
public Setting(String key, String defaultValue, Function<String, T> parser, Validator<T> validator, Property... properties) {
this(new SimpleKey(key), s -> defaultValue, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Function<Settings, String> defaultValue, Function<String, T> parser, Property... properties) {
this(new SimpleKey(key), defaultValue, parser, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallbackSetting a setting whose value to fallback on if this setting is not defined
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(Key key, Setting<T> fallbackSetting, Function<String, T> parser, Property... properties) {
this(key, fallbackSetting, fallbackSetting::getRaw, parser, v -> {}, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallBackSetting a setting to fall back to if the current setting is not set.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Setting<T> fallBackSetting, Function<String, T> parser, Property... properties) {
this(new SimpleKey(key), fallBackSetting, parser, properties);
}
/**
* Returns the settings key or a prefix if this setting is a group setting.
* <b>Note: this method should not be used to retrieve a value from a {@link Settings} object.
* Use {@link #get(Settings)} instead</b>
*
* @see #isGroupSetting()
*/
public final String getKey() {
return key.toString();
}
/**
* Returns the original representation of a setting key.
*/
public final Key getRawKey() {
return key;
}
/**
* Returns <code>true</code> if this setting is dynamically updateable, otherwise <code>false</code>
*/
public final boolean isDynamic() {
return properties.contains(Property.Dynamic);
}
/**
* Returns <code>true</code> if this setting is final, otherwise <code>false</code>
*/
public final boolean isFinal() {
return properties.contains(Property.Final);
}
public final boolean isInternalIndex() {
return properties.contains(Property.InternalIndex);
}
public final boolean isPrivateIndex() {
return properties.contains(Property.PrivateIndex);
}
/**
* Returns the setting properties
* @see Property
*/
public EnumSet<Property> getProperties() {
return properties;
}
/**
* Returns <code>true</code> if this setting must be filtered, otherwise <code>false</code>
*/
public boolean isFiltered() {
return properties.contains(Property.Filtered);
}
/**
* Returns <code>true</code> if this setting has a node scope, otherwise <code>false</code>
*/
public boolean hasNodeScope() {
return properties.contains(Property.NodeScope);
}
/**
* Returns <code>true</code> if this setting's value can be checked for equality across all nodes. Only {@link SecureSetting} instances
* may have this qualifier.
*/
public boolean isConsistent() {
return properties.contains(Property.Consistent);
}
/**
* Returns <code>true</code> if this setting has an index scope, otherwise <code>false</code>
*/
public boolean hasIndexScope() {
return properties.contains(Property.IndexScope);
}
/**
* Returns <code>true</code> if this setting is deprecated, otherwise <code>false</code>
*/
public boolean isDeprecated() {
return properties.contains(Property.Deprecated);
}
/**
* Returns <code>true</code> iff this setting is a group setting. Group settings represent a set of settings rather than a single value.
* The key, see {@link #getKey()}, in contrast to non-group settings is a prefix like {@code cluster.store.} that matches all settings
* with this prefix.
*/
boolean isGroupSetting() {
return false;
}
final boolean isListSetting() {
return this instanceof ListSetting;
}
boolean hasComplexMatcher() {
return isGroupSetting();
}
/**
* Validate the current setting value only without dependencies with {@link Setting.Validator#validate(Object)}.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
void validateWithoutDependencies(Settings settings) {
validator.validate(get(settings, false));
}
/**
* Returns the default value string representation for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public String getDefaultRaw(Settings settings) {
return defaultValue.apply(settings);
}
/**
* Returns the default value for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public T getDefault(Settings settings) {
return parser.apply(getDefaultRaw(settings));
}
/**
* Returns true if and only if this setting is present in the given settings instance. Note that fallback settings are excluded.
*
* @param settings the settings
* @return true if the setting is present in the given settings instance, otherwise false
*/
public boolean exists(final Settings settings) {
return exists(settings.keySet());
}
public boolean exists(final Settings.Builder builder) {
return exists(builder.keys());
}
private boolean exists(final Set<String> keys) {
return keys.contains(getKey());
}
/**
* Returns true if and only if this setting including fallback settings is present in the given settings instance.
*
* @param settings the settings
* @return true if the setting including fallback settings is present in the given settings instance, otherwise false
*/
public boolean existsOrFallbackExists(final Settings settings) {
return settings.keySet().contains(getKey()) || (fallbackSetting != null && fallbackSetting.existsOrFallbackExists(settings));
}
/**
* Returns the settings value. If the setting is not present in the given settings object the default value is returned
* instead.
*/
public T get(Settings settings) {
return get(settings, true);
}
private T get(Settings settings, boolean validate) {
String value = getRaw(settings);
try {
T parsed = parser.apply(value);
if (validate) {
final Iterator<Setting<?>> it = validator.settings();
final Map<Setting<?>, Object> map;
if (it.hasNext()) {
map = new HashMap<>();
while (it.hasNext()) {
final Setting<?> setting = it.next();
if (setting instanceof AffixSetting) {
// Collect all possible concrete settings
AffixSetting<?> as = ((AffixSetting<?>) setting);
for (String ns : as.getNamespaces(settings)) {
Setting<?> s = as.getConcreteSettingForNamespace(ns);
map.put(s, s.get(settings, false));
}
} else {
map.put(setting, setting.get(settings, false)); // we have to disable validation or we will stack overflow
}
}
} else {
map = Collections.emptyMap();
}
validator.validate(parsed);
validator.validate(parsed, map);
validator.validate(parsed, map, exists(settings));
}
return parsed;
} catch (OpenSearchParseException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
} catch (NumberFormatException ex) {
String err = "Failed to parse value" + (isFiltered() ? "" : " [" + value + "]") + " for setting [" + getKey() + "]";
throw new IllegalArgumentException(err, ex);
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception t) {
String err = "Failed to parse value" + (isFiltered() ? "" : " [" + value + "]") + " for setting [" + getKey() + "]";
throw new IllegalArgumentException(err, t);
}
}
/**
* Add this setting to the builder if it doesn't exist in the source settings.
* The value added to the builder is taken from the given default settings object.
* @param builder the settings builder to fill the diff into
* @param source the source settings object to diff
* @param defaultSettings the default settings object to diff against
*/
public void diff(Settings.Builder builder, Settings source, Settings defaultSettings) {
if (exists(source) == false) {
if (exists(defaultSettings)) {
// If the setting is only in the defaults, use the value from the defaults
builder.put(getKey(), getRaw(defaultSettings));
} else {
// If the setting is in neither `source` nor `default`, get the value
// from `source` as it may depend on the value of other settings
builder.put(getKey(), getRaw(source));
}
}
}
/**
* Returns the raw (string) settings value. If the setting is not present in the given settings object the default value is returned
* instead. This is useful if the value can't be parsed due to an invalid value to access the actual value.
*/
private String getRaw(final Settings settings) {
checkDeprecation(settings);
return innerGetRaw(settings);
}
/**
* The underlying implementation for {@link #getRaw(Settings)}. Setting specializations can override this as needed to convert the
* actual settings value to raw strings.
*
* @param settings the settings instance
* @return the raw string representation of the setting value
*/
String innerGetRaw(final Settings settings) {
SecureSettings secureSettings = settings.getSecureSettings();
if (secureSettings != null && secureSettings.getSettingNames().contains(getKey())) {
throw new IllegalArgumentException(
"Setting ["
+ getKey()
+ "] is a non-secure setting"
+ " and must be stored inside opensearch.yml, but was found inside the OpenSearch keystore"
);
}
return settings.get(getKey(), defaultValue.apply(settings));
}
/** Logs a deprecation warning if the setting is deprecated and used. */
void checkDeprecation(Settings settings) {
// They're using the setting, so we need to tell them to stop
if (this.isDeprecated() && this.exists(settings)) {
// It would be convenient to show its replacement key, but replacement is often not so simple
final String key = getKey();
Settings.DeprecationLoggerHolder.deprecationLogger.deprecate(
key,
"[{}] setting was deprecated in OpenSearch and will be removed in a future release! "
+ "See the breaking changes documentation for the next major version.",
key
);
}
}
/**
* Returns <code>true</code> iff the given key matches the settings key or if this setting is a group setting if the
* given key is part of the settings group.
* @see #isGroupSetting()
*/
public final boolean match(String toTest) {
return key.match(toTest);
}
@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("key", key.toString());
builder.field("properties", properties);
builder.field("is_group_setting", isGroupSetting());
builder.field("default", defaultValue.apply(Settings.EMPTY));
builder.endObject();
return builder;
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
/**
* Returns the value for this setting but falls back to the second provided settings object
*/
public final T get(Settings primary, Settings secondary) {
if (exists(primary)) {
return get(primary);
}
if (exists(secondary)) {
return get(secondary);
}
if (fallbackSetting == null) {
return get(primary);
}
if (fallbackSetting.exists(primary)) {
return fallbackSetting.get(primary);
}
return fallbackSetting.get(secondary);
}
public Setting<T> getConcreteSetting(String key) {
// we use startsWith here since the key might be foo.bar.0 if it's an array
assert key.startsWith(this.getKey()) : "was " + key + " expected: " + getKey();
return this;
}
/**
* Allows a setting to declare a dependency on another setting being set. Optionally, a setting can validate the value of the dependent
* setting.
*
* @opensearch.internal
*/
public interface SettingDependency {
/**
* The setting to declare a dependency on.
*
* @return the setting
*/
Setting getSetting();
/**
* Validates the dependent setting value.
*
* @param key the key for this setting
* @param value the value of this setting
* @param dependency the value of the dependent setting
*/
default void validate(String key, Object value, Object dependency) {
}
}
/**
* Returns a set of settings that are required at validation time. Unless all of the dependencies are present in the settings
* object validation of setting must fail.
*/
public Set<SettingDependency> getSettingsDependencies(final String key) {
return Collections.emptySet();
}
/**
* Build a new updater with a noop validator.
*/
final AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, Logger logger) {
return newUpdater(consumer, logger, (s) -> {});
}
/**
* Build the updater responsible for validating new values, logging the new
* value, and eventually setting the value where it belongs.
*/
AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, Logger logger, Consumer<T> validator) {
if (isDynamic()) {
return new Updater(consumer, logger, validator);
} else {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
}
/**
* Updates settings that depend on each other.
* See {@link AbstractScopedSettings#addSettingsUpdateConsumer(Setting, Setting, BiConsumer)} and its usage for details.
*/
static <A, B> AbstractScopedSettings.SettingUpdater<Tuple<A, B>> compoundUpdater(
final BiConsumer<A, B> consumer,
final BiConsumer<A, B> validator,
final Setting<A> aSetting,
final Setting<B> bSetting,
Logger logger
) {
final AbstractScopedSettings.SettingUpdater<A> aSettingUpdater = aSetting.newUpdater(null, logger);
final AbstractScopedSettings.SettingUpdater<B> bSettingUpdater = bSetting.newUpdater(null, logger);
return new AbstractScopedSettings.SettingUpdater<Tuple<A, B>>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return aSettingUpdater.hasChanged(current, previous) || bSettingUpdater.hasChanged(current, previous);
}
@Override
public Tuple<A, B> getValue(Settings current, Settings previous) {
A valueA = aSettingUpdater.getValue(current, previous);
B valueB = bSettingUpdater.getValue(current, previous);
validator.accept(valueA, valueB);
return new Tuple<>(valueA, valueB);
}
@Override
public void apply(Tuple<A, B> value, Settings current, Settings previous) {
if (aSettingUpdater.hasChanged(current, previous)) {
logSettingUpdate(aSetting, current, previous, logger);
}
if (bSettingUpdater.hasChanged(current, previous)) {
logSettingUpdate(bSetting, current, previous, logger);
}
consumer.accept(value.v1(), value.v2());
}
@Override
public String toString() {
return "CompoundUpdater for: " + aSettingUpdater + " and " + bSettingUpdater;
}
};
}
static AbstractScopedSettings.SettingUpdater<Settings> groupedSettingsUpdater(
Consumer<Settings> consumer,
final List<? extends Setting<?>> configuredSettings
) {
return groupedSettingsUpdater(consumer, configuredSettings, (v) -> {});
}
static AbstractScopedSettings.SettingUpdater<Settings> groupedSettingsUpdater(
Consumer<Settings> consumer,
final List<? extends Setting<?>> configuredSettings,
Consumer<Settings> validator
) {
return new AbstractScopedSettings.SettingUpdater<Settings>() {
private Settings get(Settings settings) {
return settings.filter(s -> {
for (Setting<?> setting : configuredSettings) {
if (setting.key.match(s)) {
return true;
}
}
return false;
});
}
@Override
public boolean hasChanged(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
return currentSettings.equals(previousSettings) == false;
}
@Override
public Settings getValue(Settings current, Settings previous) {
validator.accept(current);
return get(current);
}
@Override
public void apply(Settings value, Settings current, Settings previous) {
consumer.accept(value);
}
@Override
public String toString() {
return "Updater grouped: " + configuredSettings.stream().map(Setting::getKey).collect(Collectors.joining(", "));
}
};
}
/**
* Allows an affix setting to declare a dependency on another affix setting.
*
* @opensearch.internal
*/
public interface AffixSettingDependency extends SettingDependency {
@Override
AffixSetting getSetting();
}
/**
* An affix setting
*
* @opensearch.internal
*/
public static class AffixSetting<T> extends Setting<T> {
private final AffixKey key;
private final BiFunction<String, String, Setting<T>> delegateFactory;
private final Set<AffixSettingDependency> dependencies;
public AffixSetting(
AffixKey key,
Setting<T> delegate,
BiFunction<String, String, Setting<T>> delegateFactory,
AffixSettingDependency... dependencies
) {
super(key, delegate.defaultValue, delegate.parser, delegate.properties.toArray(new Property[0]));
this.key = key;
this.delegateFactory = delegateFactory;
this.dependencies = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(dependencies)));
}
boolean isGroupSetting() {
return true;
}
private Stream<String> matchStream(Settings settings) {
return settings.keySet().stream().filter(this::match).map(key::getConcreteString);
}
/**
* Get the raw list of dependencies. This method is exposed for testing purposes and {@link #getSettingsDependencies(String)}
* should be preferred for most all cases.
* @return the raw list of dependencies for this setting
*/
public Set<AffixSettingDependency> getDependencies() {
return Collections.unmodifiableSet(dependencies);
}
@Override
public Set<SettingDependency> getSettingsDependencies(String settingsKey) {
if (dependencies.isEmpty()) {
return Collections.emptySet();
} else {
String namespace = key.getNamespace(settingsKey);
return dependencies.stream().map(s -> new SettingDependency() {
@Override
public Setting<Object> getSetting() {
return s.getSetting().getConcreteSettingForNamespace(namespace);
}
@Override
public void validate(final String key, final Object value, final Object dependency) {
s.validate(key, value, dependency);
};
}).collect(Collectors.toSet());
}
}
AbstractScopedSettings.SettingUpdater<Map<AbstractScopedSettings.SettingUpdater<T>, T>> newAffixUpdater(
BiConsumer<String, T> consumer,
Logger logger,
BiConsumer<String, T> validator
) {
return new AbstractScopedSettings.SettingUpdater<Map<AbstractScopedSettings.SettingUpdater<T>, T>>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return Stream.concat(matchStream(current), matchStream(previous)).findAny().isPresent();
}
@Override
public Map<AbstractScopedSettings.SettingUpdater<T>, T> getValue(Settings current, Settings previous) {
// we collect all concrete keys and then delegate to the actual setting for validation and settings extraction
final Map<AbstractScopedSettings.SettingUpdater<T>, T> result = new IdentityHashMap<>();
Stream.concat(matchStream(current), matchStream(previous)).distinct().forEach(aKey -> {
String namespace = key.getNamespace(aKey);
Setting<T> concreteSetting = getConcreteSetting(namespace, aKey);
AbstractScopedSettings.SettingUpdater<T> updater = concreteSetting.newUpdater(
(v) -> consumer.accept(namespace, v),
logger,
(v) -> validator.accept(namespace, v)
);
if (updater.hasChanged(current, previous)) {
// only the ones that have changed otherwise we might get too many updates
// the hasChanged above checks only if there are any changes
T value = updater.getValue(current, previous);
result.put(updater, value);
}
});
return result;
}
@Override
public void apply(Map<AbstractScopedSettings.SettingUpdater<T>, T> value, Settings current, Settings previous) {
for (Map.Entry<AbstractScopedSettings.SettingUpdater<T>, T> entry : value.entrySet()) {
entry.getKey().apply(entry.getValue(), current, previous);
}
}
};
}
AbstractScopedSettings.SettingUpdater<Map<String, T>> newAffixMapUpdater(
Consumer<Map<String, T>> consumer,
Logger logger,
BiConsumer<String, T> validator
) {
return new AbstractScopedSettings.SettingUpdater<Map<String, T>>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return current.filter(k -> match(k)).equals(previous.filter(k -> match(k))) == false;
}
@Override
public Map<String, T> getValue(Settings current, Settings previous) {
// we collect all concrete keys and then delegate to the actual setting for validation and settings extraction
final Map<String, T> result = new IdentityHashMap<>();
Stream.concat(matchStream(current), matchStream(previous)).distinct().forEach(aKey -> {
String namespace = key.getNamespace(aKey);
Setting<T> concreteSetting = getConcreteSetting(namespace, aKey);
AbstractScopedSettings.SettingUpdater<T> updater = concreteSetting.newUpdater(
(v) -> {},
logger,
(v) -> validator.accept(namespace, v)
);
if (updater.hasChanged(current, previous)) {
// only the ones that have changed otherwise we might get too many updates
// the hasChanged above checks only if there are any changes
T value = updater.getValue(current, previous);
result.put(namespace, value);
}
});
return result;
}
@Override
public void apply(Map<String, T> value, Settings current, Settings previous) {
consumer.accept(value);
}
};
}
@Override
public T get(Settings settings) {
throw new UnsupportedOperationException(
"affix settings can't return values" + " use #getConcreteSetting to obtain a concrete setting"
);
}
@Override
public String innerGetRaw(final Settings settings) {
throw new UnsupportedOperationException(
"affix settings can't return values" + " use #getConcreteSetting to obtain a concrete setting"
);
}
@Override
public Setting<T> getConcreteSetting(String key) {
if (match(key)) {
String namespace = this.key.getNamespace(key);
return delegateFactory.apply(namespace, key);
} else {
throw new IllegalArgumentException("key [" + key + "] must match [" + getKey() + "] but didn't.");
}
}
private Setting<T> getConcreteSetting(String namespace, String key) {
if (match(key)) {
return delegateFactory.apply(namespace, key);
} else {
throw new IllegalArgumentException("key [" + key + "] must match [" + getKey() + "] but didn't.");
}
}
/**
* Get a setting with the given namespace filled in for prefix and suffix.
*/
public Setting<T> getConcreteSettingForNamespace(String namespace) {
String fullKey = key.toConcreteKey(namespace).toString();
return getConcreteSetting(namespace, fullKey);
}
@Override
public void diff(Settings.Builder builder, Settings source, Settings defaultSettings) {
matchStream(defaultSettings).forEach((key) -> getConcreteSetting(key).diff(builder, source, defaultSettings));
}
/**
* Returns the namespace for a concrete setting. Ie. an affix setting with prefix: {@code search.} and suffix: {@code username}
* will return {@code remote} as a namespace for the setting {@code cluster.remote.username}
*/
public String getNamespace(Setting<T> concreteSetting) {
return key.getNamespace(concreteSetting.getKey());
}
/**
* Returns a stream of all concrete setting instances for the given settings. AffixSetting is only a specification, concrete
* settings depend on an actual set of setting keys.
*/
public Stream<Setting<T>> getAllConcreteSettings(Settings settings) {
return matchStream(settings).distinct().map(this::getConcreteSetting);
}
/**
* Returns distinct namespaces for the given settings
*/
public Set<String> getNamespaces(Settings settings) {
return settings.keySet().stream().filter(this::match).map(key::getNamespace).collect(Collectors.toSet());
}
/**
* Returns a map of all namespaces to its values give the provided settings
*/