org.opensearch.common.settings.Setting Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of opensearch Show documentation
Show all versions of opensearch Show documentation
OpenSearch subproject :server
/*
* 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.annotation.PublicApi;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.regex.Regex;
import org.opensearch.common.unit.MemorySizeValue;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
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:
* {@code
* public static final Setting MY_BOOLEAN = Setting.boolSetting("my.bool.setting", true, Setting.Property.NodeScope);}
*
* To retrieve the value of the setting a {@link Settings} object can be passed directly to the {@link Setting#get(Settings)} method.
*
* final boolean myBooleanValue = MY_BOOLEAN.get(settings);
*
* It's recommended to use typed settings rather than string based settings. For example adding a setting for an enum type:
* {@code
* public enum Color {
* RED, GREEN, BLUE;
* }
* public static final Setting MY_BOOLEAN =
* new Setting<>("my.color.setting", Color.RED.toString(), Color::valueOf, Setting.Property.NodeScope);
* }
*
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public class Setting implements ToXContentObject {
/**
* Property of the setting
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
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,
/**
* Extension scope
*/
ExtensionScope
}
private final Key key;
protected final Function defaultValue;
@Nullable
protected final Setting fallbackSetting;
protected final Function parser;
protected final Validator validator;
private final EnumSet properties;
private static final EnumSet EMPTY_PROPERTIES = EnumSet.noneOf(Property.class);
private Setting(
Key key,
@Nullable Setting fallbackSetting,
Function defaultValue,
Function parser,
Validator 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 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 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 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 defaultValue, Function 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 defaultValue,
Function parser,
Validator 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 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 parser, Validator 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 defaultValue, Function 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 fallbackSetting, Function 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 fallBackSetting, Function parser, Property... properties) {
this(new SimpleKey(key), fallBackSetting, parser, properties);
}
/**
* Returns the settings key or a prefix if this setting is a group setting.
* Note: this method should not be used to retrieve a value from a {@link Settings} object.
* Use {@link #get(Settings)} instead
*
* @see #isGroupSetting()
*/
public final String getKey() {
return key.toString();
}
/**
* Returns the original representation of a setting key.
*/
public final Key getRawKey() {
return key;
}
/**
* Returns true
if this setting is dynamically updateable, otherwise false
*/
public final boolean isDynamic() {
return properties.contains(Property.Dynamic);
}
/**
* Returns true
if this setting is final, otherwise false
*/
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 getProperties() {
return properties;
}
/**
* Returns true
if this setting must be filtered, otherwise false
*/
public boolean isFiltered() {
return properties.contains(Property.Filtered);
}
/**
* Returns true
if this setting has a node scope, otherwise false
*/
public boolean hasNodeScope() {
return properties.contains(Property.NodeScope);
}
/**
* Returns true
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 true
if this setting has an index scope, otherwise false
*/
public boolean hasIndexScope() {
return properties.contains(Property.IndexScope);
}
/**
* Returns true
if this setting is deprecated, otherwise false
*/
public boolean isDeprecated() {
return properties.contains(Property.Deprecated);
}
/**
* Returns true
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 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> it = validator.settings();
final Map, 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 true
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(MediaTypeRegistry.JSON, 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 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.api
*/
@PublicApi(since = "1.0.0")
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 getSettingsDependencies(final String key) {
return Collections.emptySet();
}
/**
* Build a new updater with a noop validator.
*/
final AbstractScopedSettings.SettingUpdater newUpdater(Consumer 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 newUpdater(Consumer consumer, Logger logger, Consumer 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 AbstractScopedSettings.SettingUpdater> compoundUpdater(
final BiConsumer consumer,
final BiConsumer validator,
final Setting aSetting,
final Setting bSetting,
Logger logger
) {
final AbstractScopedSettings.SettingUpdater aSettingUpdater = aSetting.newUpdater(null, logger);
final AbstractScopedSettings.SettingUpdater bSettingUpdater = bSetting.newUpdater(null, logger);
return new AbstractScopedSettings.SettingUpdater>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return aSettingUpdater.hasChanged(current, previous) || bSettingUpdater.hasChanged(current, previous);
}
@Override
public Tuple 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 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 groupedSettingsUpdater(
Consumer consumer,
final List extends Setting>> configuredSettings
) {
return groupedSettingsUpdater(consumer, configuredSettings, (v) -> {});
}
static AbstractScopedSettings.SettingUpdater groupedSettingsUpdater(
Consumer consumer,
final List extends Setting>> configuredSettings,
Consumer validator
) {
return new AbstractScopedSettings.SettingUpdater() {
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.api
*/
@PublicApi(since = "1.0.0")
public interface AffixSettingDependency extends SettingDependency {
@Override
AffixSetting getSetting();
}
/**
* An affix setting
*
* @opensearch.api
*/
@PublicApi(since = "1.0.0")
public static class AffixSetting extends Setting {
private final AffixKey key;
private final BiFunction> delegateFactory;
private final Set dependencies;
public AffixSetting(
AffixKey key,
Setting delegate,
BiFunction> 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 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 getDependencies() {
return Collections.unmodifiableSet(dependencies);
}
@Override
public Set 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