Always use deprecateAndMaybeLog for deprecation warnings (#55319)

Backport of #55115.

Replace calls to deprecate(String,Object...) with deprecateAndMaybeLog(...),
with an appropriate key, so that all messages can potentially be deduplicated.
This commit is contained in:
Rory Hunter 2020-04-23 09:20:54 +01:00 committed by GitHub
parent 87f4751eca
commit d66af46724
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
72 changed files with 194 additions and 160 deletions

View file

@ -445,7 +445,8 @@ public class CommonAnalysisPlugin extends Plugin implements AnalysisPlugin, Scri
"[delimited_payload_filter] is not supported for new indices, use [delimited_payload] instead"); "[delimited_payload_filter] is not supported for new indices, use [delimited_payload] instead");
} }
if (version.onOrAfter(Version.V_6_2_0)) { if (version.onOrAfter(Version.V_6_2_0)) {
deprecationLogger.deprecated("Deprecated [delimited_payload_filter] used, replaced by [delimited_payload]"); deprecationLogger.deprecatedAndMaybeLog("analysis_delimited_payload_filter",
"Deprecated [delimited_payload_filter] used, replaced by [delimited_payload]");
} }
return new DelimitedPayloadTokenFilter(input, return new DelimitedPayloadTokenFilter(input,
DelimitedPayloadTokenFilterFactory.DEFAULT_DELIMITER, DelimitedPayloadTokenFilterFactory.DEFAULT_DELIMITER,

View file

@ -38,7 +38,8 @@ public class LegacyDelimitedPayloadTokenFilterFactory extends DelimitedPayloadTo
"[delimited_payload_filter] is not supported for new indices, use [delimited_payload] instead"); "[delimited_payload_filter] is not supported for new indices, use [delimited_payload] instead");
} }
if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_6_2_0)) { if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_6_2_0)) {
deprecationLogger.deprecated("Deprecated [delimited_payload_filter] used, replaced by [delimited_payload]"); deprecationLogger.deprecatedAndMaybeLog("analysis_legacy_delimited_payload_filter",
"Deprecated [delimited_payload_filter] used, replaced by [delimited_payload]");
} }
} }
} }

View file

@ -53,7 +53,8 @@ public class NGramTokenFilterFactory extends AbstractTokenFilterFactory {
+ maxAllowedNgramDiff + "] but was [" + ngramDiff + "]. This limit can be set by changing the [" + maxAllowedNgramDiff + "] but was [" + ngramDiff + "]. This limit can be set by changing the ["
+ IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting."); + IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting.");
} else { } else {
deprecationLogger.deprecated("Deprecated big difference between max_gram and min_gram in NGram Tokenizer," deprecationLogger.deprecatedAndMaybeLog("ngram_big_difference",
"Deprecated big difference between max_gram and min_gram in NGram Tokenizer,"
+ "expected difference must be less than or equal to: [" + maxAllowedNgramDiff + "]"); + "expected difference must be less than or equal to: [" + maxAllowedNgramDiff + "]");
} }
} }

View file

@ -118,7 +118,8 @@ public class NGramTokenizerFactory extends AbstractTokenizerFactory {
+ maxAllowedNgramDiff + "] but was [" + ngramDiff + "]. This limit can be set by changing the [" + maxAllowedNgramDiff + "] but was [" + ngramDiff + "]. This limit can be set by changing the ["
+ IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting."); + IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting.");
} else { } else {
deprecationLogger.deprecated("Deprecated big difference between max_gram and min_gram in NGram Tokenizer," deprecationLogger.deprecatedAndMaybeLog("ngram_big_difference",
"Deprecated big difference between max_gram and min_gram in NGram Tokenizer,"
+ "expected difference must be less than or equal to: [" + maxAllowedNgramDiff + "]"); + "expected difference must be less than or equal to: [" + maxAllowedNgramDiff + "]");
} }
} }

View file

@ -59,7 +59,8 @@ public class SynonymTokenFilterFactory extends AbstractTokenFilterFactory {
this.settings = settings; this.settings = settings;
if (settings.get("ignore_case") != null) { if (settings.get("ignore_case") != null) {
DEPRECATION_LOGGER.deprecated( DEPRECATION_LOGGER.deprecatedAndMaybeLog(
"synonym_ignore_case_option",
"The ignore_case option on the synonym_graph filter is deprecated. " + "The ignore_case option on the synonym_graph filter is deprecated. " +
"Instead, insert a lowercase filter in the filter chain before the synonym_graph filter."); "Instead, insert a lowercase filter in the filter chain before the synonym_graph filter.");
} }

View file

@ -315,7 +315,8 @@ public class UserAgentProcessor extends AbstractProcessor {
} }
if (useECS == false) { if (useECS == false) {
deprecationLogger.deprecated("setting [ecs] to false for non-common schema " + deprecationLogger.deprecatedAndMaybeLog("ecs_false_non_common_schema",
"setting [ecs] to false for non-common schema " +
"format is deprecated and will be removed in 8.0, set to true or remove to use the non-deprecated format"); "format is deprecated and will be removed in 8.0, set to true or remove to use the non-deprecated format");
} }
@ -356,7 +357,9 @@ public class UserAgentProcessor extends AbstractProcessor {
try { try {
Property value = valueOf(propertyName.toUpperCase(Locale.ROOT)); Property value = valueOf(propertyName.toUpperCase(Locale.ROOT));
if (DEPRECATED_PROPERTIES.contains(value)) { if (DEPRECATED_PROPERTIES.contains(value)) {
deprecationLogger.deprecated("the [{}] property is deprecated for the user-agent processor", propertyName); final String key = "user_agent_processor_property_" + propertyName.replaceAll("[^\\w_]+", "_");
deprecationLogger.deprecatedAndMaybeLog(key,
"the [{}] property is deprecated for the user-agent processor", propertyName);
} }
return value; return value;
} }

View file

@ -67,7 +67,7 @@ class ReindexValidator {
state); state);
SearchSourceBuilder searchSource = request.getSearchRequest().source(); SearchSourceBuilder searchSource = request.getSearchRequest().source();
if (searchSource != null && searchSource.sorts() != null && searchSource.sorts().isEmpty() == false) { if (searchSource != null && searchSource.sorts() != null && searchSource.sorts().isEmpty() == false) {
deprecationLogger.deprecated(SORT_DEPRECATED_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("reindex_sort", SORT_DEPRECATED_MESSAGE);
} }
} }

View file

@ -186,7 +186,7 @@ final class RemoteRequestBuilders {
private static String encodeIndex(String s) { private static String encodeIndex(String s) {
if (s.contains("%")) { // already encoded, pass-through to allow this in mixed version clusters if (s.contains("%")) { // already encoded, pass-through to allow this in mixed version clusters
checkIndexOrType("Index", s); checkIndexOrType("Index", s);
DEPRECATION_LOGGER.deprecated(DEPRECATED_URL_ENCODED_INDEX_WARNING); DEPRECATION_LOGGER.deprecatedAndMaybeLog("reindex_url_encoded_index", DEPRECATED_URL_ENCODED_INDEX_WARNING);
return s; return s;
} }
try { try {

View file

@ -62,7 +62,8 @@ public class IcuNormalizerTokenFilterFactory extends AbstractTokenFilterFactory
String unicodeSetFilter = settings.get("unicodeSetFilter"); String unicodeSetFilter = settings.get("unicodeSetFilter");
if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) { if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) {
if (unicodeSetFilter != null) { if (unicodeSetFilter != null) {
deprecationLogger.deprecated("[unicodeSetFilter] has been deprecated in favor of [unicode_set_filter]"); deprecationLogger.deprecatedAndMaybeLog("icu_normalizer_unicode_set_filter",
"[unicodeSetFilter] has been deprecated in favor of [unicode_set_filter]");
} else { } else {
unicodeSetFilter = settings.get("unicode_set_filter"); unicodeSetFilter = settings.get("unicode_set_filter");
} }

View file

@ -48,7 +48,7 @@ public class AzureDiscoveryPlugin extends Plugin implements DiscoveryPlugin {
public AzureDiscoveryPlugin(Settings settings) { public AzureDiscoveryPlugin(Settings settings) {
this.settings = settings; this.settings = settings;
deprecationLogger.deprecated("azure classic discovery plugin is deprecated."); deprecationLogger.deprecatedAndMaybeLog("azure_discovery_plugin", "azure classic discovery plugin is deprecated.");
logger.trace("starting azure classic discovery plugin..."); logger.trace("starting azure classic discovery plugin...");
} }

View file

@ -135,11 +135,13 @@ final class Ec2ClientSettings {
return null; return null;
} else { } else {
if (key.length() == 0) { if (key.length() == 0) {
deprecationLogger.deprecated("Setting [{}] is set but [{}] is not, which will be unsupported in future", deprecationLogger.deprecatedAndMaybeLog("ec2_invalid_settings",
"Setting [{}] is set but [{}] is not, which will be unsupported in future",
SECRET_KEY_SETTING.getKey(), ACCESS_KEY_SETTING.getKey()); SECRET_KEY_SETTING.getKey(), ACCESS_KEY_SETTING.getKey());
} }
if (secret.length() == 0) { if (secret.length() == 0) {
deprecationLogger.deprecated("Setting [{}] is set but [{}] is not, which will be unsupported in future", deprecationLogger.deprecatedAndMaybeLog("ec2_invalid_settings",
"Setting [{}] is set but [{}] is not, which will be unsupported in future",
ACCESS_KEY_SETTING.getKey(), SECRET_KEY_SETTING.getKey()); ACCESS_KEY_SETTING.getKey(), SECRET_KEY_SETTING.getKey());
} }

View file

@ -249,7 +249,8 @@ class S3Repository extends BlobStoreRepository {
if (S3ClientSettings.checkDeprecatedCredentials(metadata.settings())) { if (S3ClientSettings.checkDeprecatedCredentials(metadata.settings())) {
// provided repository settings // provided repository settings
deprecationLogger.deprecated("Using s3 access/secret key from repository settings. Instead " deprecationLogger.deprecatedAndMaybeLog("s3_repository_secret_settings",
"Using s3 access/secret key from repository settings. Instead "
+ "store these in named clients and the elasticsearch keystore for secure settings."); + "store these in named clients and the elasticsearch keystore for secure settings.");
} }

View file

@ -104,33 +104,6 @@ public class EvilLoggerTests extends ESTestCase {
assertLogLine(events.get(4), Level.TRACE, location, "This is a trace message"); assertLogLine(events.get(4), Level.TRACE, location, "This is a trace message");
} }
public void testDeprecationLogger() throws IOException, UserException {
setupLogging("deprecation");
final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger("deprecation"));
final int deprecatedIterations = randomIntBetween(0, 256);
for (int i = 0; i < deprecatedIterations; i++) {
deprecationLogger.deprecated("This is a deprecation message");
assertWarnings("This is a deprecation message");
}
final String deprecationPath =
System.getProperty("es.logs.base_path") +
System.getProperty("file.separator") +
System.getProperty("es.logs.cluster_name") +
"_deprecation.log";
final List<String> deprecationEvents = Files.readAllLines(PathUtils.get(deprecationPath));
assertThat(deprecationEvents.size(), equalTo(deprecatedIterations));
for (int i = 0; i < deprecatedIterations; i++) {
assertLogLine(
deprecationEvents.get(i),
Level.WARN,
"org.elasticsearch.common.logging.DeprecationLogger\\$2\\.run",
"This is a deprecation message");
}
}
public void testConcurrentDeprecationLogger() throws IOException, UserException, BrokenBarrierException, InterruptedException { public void testConcurrentDeprecationLogger() throws IOException, UserException, BrokenBarrierException, InterruptedException {
setupLogging("deprecation"); setupLogging("deprecation");

View file

@ -80,7 +80,7 @@ public class TestDeprecatedQueryBuilder extends AbstractQueryBuilder<TestDepreca
@Override @Override
protected Query doToQuery(QueryShardContext context) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
deprecationLogger.deprecated("[{}] query is deprecated, but used on [{}] index", NAME, context.index().getName()); deprecationLogger.deprecatedAndMaybeLog(NAME, "[{}] query is deprecated, but used on [{}] index", NAME, context.index().getName());
return Queries.newMatchAllQuery(); return Queries.newMatchAllQuery();
} }

View file

@ -106,7 +106,7 @@ public class TestDeprecationHeaderRestAction extends BaseRestHandler {
final Map<String, Object> source = parser.map(); final Map<String, Object> source = parser.map();
if (source.containsKey("deprecated_settings")) { if (source.containsKey("deprecated_settings")) {
deprecationLogger.deprecated(DEPRECATED_USAGE); deprecationLogger.deprecatedAndMaybeLog("deprecated_settings", DEPRECATED_USAGE);
settings = (List<String>)source.get("deprecated_settings"); settings = (List<String>)source.get("deprecated_settings");
} else { } else {

View file

@ -343,7 +343,8 @@ public class PutIndexTemplateRequest extends MasterNodeRequest<PutIndexTemplateR
if (name.equals("template")) { if (name.equals("template")) {
// This is needed to allow for bwc (beats, logstash) with pre-5.0 templates (#21009) // This is needed to allow for bwc (beats, logstash) with pre-5.0 templates (#21009)
if(entry.getValue() instanceof String) { if(entry.getValue() instanceof String) {
deprecationLogger.deprecated("Deprecated field [template] used, replaced by [index_patterns]"); deprecationLogger.deprecatedAndMaybeLog("put_index_template_field",
"Deprecated field [template] used, replaced by [index_patterns]");
patterns(Collections.singletonList((String) entry.getValue())); patterns(Collections.singletonList((String) entry.getValue()));
} }
} else if (name.equals("index_patterns")) { } else if (name.equals("index_patterns")) {

View file

@ -191,7 +191,8 @@ public class MultiSearchRequest extends ActionRequest implements CompositeIndice
// support first line with \n // support first line with \n
if (nextMarker == 0) { if (nextMarker == 0) {
from = nextMarker + 1; from = nextMarker + 1;
deprecationLogger.deprecated("support for empty first line before any action metadata in msearch API is deprecated and " + deprecationLogger.deprecatedAndMaybeLog("multi_search_empty_first_line",
"support for empty first line before any action metadata in msearch API is deprecated and " +
"will be removed in the next major version"); "will be removed in the next major version");
continue; continue;
} }

View file

@ -361,7 +361,7 @@ final class Bootstrap {
"future versions of Elasticsearch will require Java 11; " + "future versions of Elasticsearch will require Java 11; " +
"your Java version from [%s] does not meet this requirement", "your Java version from [%s] does not meet this requirement",
System.getProperty("java.home")); System.getProperty("java.home"));
new DeprecationLogger(LogManager.getLogger(Bootstrap.class)).deprecated(message); new DeprecationLogger(LogManager.getLogger(Bootstrap.class)).deprecatedAndMaybeLog("java_version_11_required", message);
} }
if (environment.pidFile() != null) { if (environment.pidFile() != null) {
try { try {

View file

@ -186,7 +186,8 @@ public class MetadataCreateIndexService {
.filter(descriptor -> descriptor.matchesIndexPattern(index)) .filter(descriptor -> descriptor.matchesIndexPattern(index))
.collect(toList()); .collect(toList());
if (matchingDescriptors.isEmpty() && (isHidden == null || isHidden == Boolean.FALSE)) { if (matchingDescriptors.isEmpty() && (isHidden == null || isHidden == Boolean.FALSE)) {
DEPRECATION_LOGGER.deprecated("index name [{}] starts with a dot '.', in the next major version, index names " + DEPRECATION_LOGGER.deprecatedAndMaybeLog("index_name_starts_with_dot",
"index name [{}] starts with a dot '.', in the next major version, index names " +
"starting with a dot are reserved for hidden indices and system indices", index); "starting with a dot are reserved for hidden indices and system indices", index);
} else if (matchingDescriptors.size() > 1) { } else if (matchingDescriptors.size() > 1) {
// This should be prevented by erroring on overlapping patterns at startup time, but is here just in case. // This should be prevented by erroring on overlapping patterns at startup time, but is here just in case.

View file

@ -368,7 +368,7 @@ public class MetadataIndexTemplateService {
.collect(Collectors.joining(",")), .collect(Collectors.joining(",")),
name); name);
logger.warn(warning); logger.warn(warning);
deprecationLogger.deprecated(warning); deprecationLogger.deprecatedAndMaybeLog("index_template_pattern_overlap", warning);
} }
IndexTemplateV2 finalIndexTemplate = template; IndexTemplateV2 finalIndexTemplate = template;
@ -593,7 +593,7 @@ public class MetadataIndexTemplateService {
.collect(Collectors.joining(",")), .collect(Collectors.joining(",")),
request.name); request.name);
logger.warn(warning); logger.warn(warning);
deprecationLogger.deprecated(warning); deprecationLogger.deprecatedAndMaybeLog("index_template_pattern_overlap", warning);
} else { } else {
// Otherwise, this is a hard error, the user should use V2 index templates instead // Otherwise, this is a hard error, the user should use V2 index templates instead
String error = String.format(Locale.ROOT, "template [%s] has index patterns %s matching patterns" + String error = String.format(Locale.ROOT, "template [%s] has index patterns %s matching patterns" +

View file

@ -67,7 +67,8 @@ public class OperationRouting {
if (ignoreAwarenessAttr == false) { if (ignoreAwarenessAttr == false) {
awarenessAttributes = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.get(settings); awarenessAttributes = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.get(settings);
if (awarenessAttributes.isEmpty() == false) { if (awarenessAttributes.isEmpty() == false) {
deprecationLogger.deprecated(IGNORE_AWARENESS_ATTRIBUTES_DEPRECATION_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("searches_not_routed_on_awareness_attributes",
IGNORE_AWARENESS_ATTRIBUTES_DEPRECATION_MESSAGE);
} }
clusterSettings.addSettingsUpdateConsumer(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING, clusterSettings.addSettingsUpdateConsumer(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING,
this::setAwarenessAttributes); this::setAwarenessAttributes);
@ -91,7 +92,8 @@ public class OperationRouting {
boolean ignoreAwarenessAttr = parseBoolean(System.getProperty(IGNORE_AWARENESS_ATTRIBUTES_PROPERTY), false); boolean ignoreAwarenessAttr = parseBoolean(System.getProperty(IGNORE_AWARENESS_ATTRIBUTES_PROPERTY), false);
if (ignoreAwarenessAttr == false) { if (ignoreAwarenessAttr == false) {
if (this.awarenessAttributes.isEmpty() && awarenessAttributes.isEmpty() == false) { if (this.awarenessAttributes.isEmpty() && awarenessAttributes.isEmpty() == false) {
deprecationLogger.deprecated(IGNORE_AWARENESS_ATTRIBUTES_DEPRECATION_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("searches_not_routed_on_awareness_attributes",
IGNORE_AWARENESS_ATTRIBUTES_DEPRECATION_MESSAGE);
} }
this.awarenessAttributes = awarenessAttributes; this.awarenessAttributes = awarenessAttributes;
} }

View file

@ -101,7 +101,8 @@ public class DiskThresholdMonitor {
this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterSettings); this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterSettings);
this.client = client; this.client = client;
if (diskThresholdSettings.isAutoReleaseIndexEnabled() == false) { if (diskThresholdSettings.isAutoReleaseIndexEnabled() == false) {
deprecationLogger.deprecated("[{}] will be removed in version {}", deprecationLogger.deprecatedAndMaybeLog(DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY.replace(".", "_"),
"[{}] will be removed in version {}",
DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, Version.V_7_4_0.major + 1); DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, Version.V_7_4_0.major + 1);
} }
} }
@ -292,7 +293,9 @@ public class DiskThresholdMonitor {
logger.info("releasing read-only-allow-delete block on indices: [{}]", indicesToAutoRelease); logger.info("releasing read-only-allow-delete block on indices: [{}]", indicesToAutoRelease);
updateIndicesReadOnly(indicesToAutoRelease, listener, false); updateIndicesReadOnly(indicesToAutoRelease, listener, false);
} else { } else {
deprecationLogger.deprecated("[{}] will be removed in version {}", deprecationLogger.deprecatedAndMaybeLog(
DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY.replace(".", "_"),
"[{}] will be removed in version {}",
DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, Version.V_7_4_0.major + 1); DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, Version.V_7_4_0.major + 1);
logger.debug("[{}] disabled, not releasing read-only-allow-delete block on indices: [{}]", logger.debug("[{}] disabled, not releasing read-only-allow-delete block on indices: [{}]",
DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, indicesToAutoRelease); DiskThresholdSettings.AUTO_RELEASE_INDEX_ENABLED_KEY, indicesToAutoRelease);

View file

@ -28,6 +28,7 @@ import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.Task;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.BitSet; import java.util.BitSet;
@ -110,15 +111,8 @@ public class DeprecationLogger {
this.logger = LogManager.getLogger(name); this.logger = LogManager.getLogger(name);
} }
/**
* Logs a deprecation message, adding a formatted warning message as a response header on the thread context.
*/
public void deprecated(String msg, Object... params) {
deprecated(THREAD_CONTEXT, msg, params);
}
// LRU set of keys used to determine if a deprecation message should be emitted to the deprecation logs // LRU set of keys used to determine if a deprecation message should be emitted to the deprecation logs
private Set<String> keys = Collections.newSetFromMap(Collections.synchronizedMap(new LinkedHashMap<String, Boolean>() { private final Set<String> keys = Collections.newSetFromMap(Collections.synchronizedMap(new LinkedHashMap<String, Boolean>() {
@Override @Override
protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) { protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) {
return size() > 128; return size() > 128;
@ -135,8 +129,8 @@ public class DeprecationLogger {
*/ */
public void deprecatedAndMaybeLog(final String key, final String msg, final Object... params) { public void deprecatedAndMaybeLog(final String key, final String msg, final Object... params) {
String xOpaqueId = getXOpaqueId(THREAD_CONTEXT); String xOpaqueId = getXOpaqueId(THREAD_CONTEXT);
boolean log = keys.add(xOpaqueId + key); boolean shouldLog = keys.add(xOpaqueId + key);
deprecated(THREAD_CONTEXT, msg, log, params); deprecated(THREAD_CONTEXT, msg, shouldLog, params);
} }
/* /*
@ -234,7 +228,7 @@ public class DeprecationLogger {
deprecated(threadContexts, message, true, params); deprecated(threadContexts, message, true, params);
} }
void deprecated(final Set<ThreadContext> threadContexts, final String message, final boolean log, final Object... params) { void deprecated(final Set<ThreadContext> threadContexts, final String message, final boolean shouldLog, final Object... params) {
final Iterator<ThreadContext> iterator = threadContexts.iterator(); final Iterator<ThreadContext> iterator = threadContexts.iterator();
if (iterator.hasNext()) { if (iterator.hasNext()) {
final String formattedMessage = LoggerMessageFormat.format(message, params); final String formattedMessage = LoggerMessageFormat.format(message, params);
@ -251,12 +245,12 @@ public class DeprecationLogger {
} }
} }
if (log) { if (shouldLog) {
AccessController.doPrivileged(new PrivilegedAction<Void>() { AccessController.doPrivileged(new PrivilegedAction<Void>() {
@SuppressLoggerChecks(reason = "safely delegates to logger") @SuppressLoggerChecks(reason = "safely delegates to logger")
@Override @Override
public Void run() { public Void run() {
/** /*
* There should be only one threadContext (in prod env), @see DeprecationLogger#setThreadContext * There should be only one threadContext (in prod env), @see DeprecationLogger#setThreadContext
*/ */
String opaqueId = getXOpaqueId(threadContexts); String opaqueId = getXOpaqueId(threadContexts);
@ -360,7 +354,7 @@ public class DeprecationLogger {
assert doesNotNeedEncoding.get('%') == false : doesNotNeedEncoding; assert doesNotNeedEncoding.get('%') == false : doesNotNeedEncoding;
} }
private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Charset UTF_8 = StandardCharsets.UTF_8;
/** /**
* Encode a string containing characters outside of the legal characters for an RFC 7230 quoted-string. * Encode a string containing characters outside of the legal characters for an RFC 7230 quoted-string.

View file

@ -245,7 +245,8 @@ public class ByteSizeValue implements Writeable, Comparable<ByteSizeValue>, ToXC
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
try { try {
final double doubleValue = Double.parseDouble(s); final double doubleValue = Double.parseDouble(s);
DeprecationLoggerHolder.deprecationLogger.deprecated( DeprecationLoggerHolder.deprecationLogger.deprecatedAndMaybeLog(
"fractional_byte_values",
"Fractional bytes values are deprecated. Use non-fractional bytes values instead: [{}] found for setting [{}]", "Fractional bytes values are deprecated. Use non-fractional bytes values instead: [{}] found for setting [{}]",
initialInput, settingName); initialInput, settingName);
return new ByteSizeValue((long) (doubleValue * unit.toBytes(1))); return new ByteSizeValue((long) (doubleValue * unit.toBytes(1)));

View file

@ -53,21 +53,21 @@ public class LoggingDeprecationHandler implements DeprecationHandler {
@Override @Override
public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) { public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used, expected [{}] instead", deprecationLogger.deprecatedAndMaybeLog("deprecated_field", "{}Deprecated field [{}] used, expected [{}] instead",
prefix, usedName, modernName); prefix, usedName, modernName);
} }
@Override @Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) { public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used, replaced by [{}]", deprecationLogger.deprecatedAndMaybeLog("deprecated_field", "{}Deprecated field [{}] used, replaced by [{}]",
prefix, usedName, replacedWith); prefix, usedName, replacedWith);
} }
@Override @Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) { public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used, this field is unused and will be removed entirely", deprecationLogger.deprecatedAndMaybeLog("deprecated_field",
prefix, usedName); "{}Deprecated field [{}] used, this field is unused and will be removed entirely", prefix, usedName);
} }
} }

View file

@ -73,7 +73,8 @@ public class HttpInfo implements ReportingService.Info {
String publishAddressString = publishAddress.toString(); String publishAddressString = publishAddress.toString();
String hostString = publishAddress.address().getHostString(); String hostString = publishAddress.address().getHostString();
if (CNAME_IN_PUBLISH_HOST) { if (CNAME_IN_PUBLISH_HOST) {
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog(
"cname_in_publish_address",
"es.http.cname_in_publish_address system property is deprecated and no longer affects http.publish_address " + "es.http.cname_in_publish_address system property is deprecated and no longer affects http.publish_address " +
"formatting. Remove this property to get rid of this deprecation warning." "formatting. Remove this property to get rid of this deprecation warning."
); );

View file

@ -51,7 +51,8 @@ public class ShingleTokenFilterFactory extends AbstractTokenFilterFactory {
+ " must be less than or equal to: [" + maxAllowedShingleDiff + "] but was [" + shingleDiff + "]. This limit" + " must be less than or equal to: [" + maxAllowedShingleDiff + "] but was [" + shingleDiff + "]. This limit"
+ " can be set by changing the [" + IndexSettings.MAX_SHINGLE_DIFF_SETTING.getKey() + "] index level setting."); + " can be set by changing the [" + IndexSettings.MAX_SHINGLE_DIFF_SETTING.getKey() + "] index level setting.");
} else { } else {
deprecationLogger.deprecated("Deprecated big difference between maxShingleSize and minShingleSize" + deprecationLogger.deprecatedAndMaybeLog("excessive_shingle_diff",
"Deprecated big difference between maxShingleSize and minShingleSize" +
" in Shingle TokenFilter, expected difference must be less than or equal to: [" + maxAllowedShingleDiff + "]"); " in Shingle TokenFilter, expected difference must be less than or equal to: [" + maxAllowedShingleDiff + "]");
} }
} }

View file

@ -419,7 +419,8 @@ public class CompletionFieldMapper extends FieldMapper implements ArrayValueMapp
private void checkCompletionContextsLimit(BuilderContext context) { private void checkCompletionContextsLimit(BuilderContext context) {
if (this.contextMappings != null && this.contextMappings.size() > COMPLETION_CONTEXTS_LIMIT) { if (this.contextMappings != null && this.contextMappings.size() > COMPLETION_CONTEXTS_LIMIT) {
deprecationLogger.deprecated("You have defined more than [" + COMPLETION_CONTEXTS_LIMIT + "] completion contexts" + deprecationLogger.deprecatedAndMaybeLog("excessive_completion_contexts",
"You have defined more than [" + COMPLETION_CONTEXTS_LIMIT + "] completion contexts" +
" in the mapping for index [" + context.indexSettings().get(IndexMetadata.SETTING_INDEX_PROVIDED_NAME) + "]. " + " in the mapping for index [" + context.indexSettings().get(IndexMetadata.SETTING_INDEX_PROVIDED_NAME) + "]. " +
"The maximum allowed number of completion contexts in a mapping will be limited to " + "The maximum allowed number of completion contexts in a mapping will be limited to " +
"[" + COMPLETION_CONTEXTS_LIMIT + "] starting in version [8.0]."); "[" + COMPLETION_CONTEXTS_LIMIT + "] starting in version [8.0].");

View file

@ -208,8 +208,9 @@ public class DynamicTemplate implements ToXContentObject {
if (indexVersionCreated.onOrAfter(Version.V_6_0_0_alpha1)) { if (indexVersionCreated.onOrAfter(Version.V_6_0_0_alpha1)) {
throw e; throw e;
} else { } else {
deprecationLogger.deprecated("match_mapping_type [" + matchMappingType + "] is invalid and will be ignored: " deprecationLogger.deprecatedAndMaybeLog("invalid_mapping_type",
+ e.getMessage()); "match_mapping_type [" + matchMappingType + "] is invalid and will be ignored: "
+ e.getMessage());
// this template is on an unknown type so it will never match anything // this template is on an unknown type so it will never match anything
// null indicates that the template should be ignored // null indicates that the template should be ignored
return null; return null;

View file

@ -185,7 +185,8 @@ public class FieldNamesFieldMapper extends MetadataFieldMapper {
if (isEnabled() == false) { if (isEnabled() == false) {
throw new IllegalStateException("Cannot run [exists] queries if the [_field_names] field is disabled"); throw new IllegalStateException("Cannot run [exists] queries if the [_field_names] field is disabled");
} }
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog(
"terms_query_on_field_names",
"terms query on the _field_names field is deprecated and will be removed, use exists query instead"); "terms query on the _field_names field is deprecated and will be removed, use exists query instead");
return super.termQuery(value, context); return super.termQuery(value, context);
} }

View file

@ -170,8 +170,8 @@ public class LegacyGeoShapeFieldMapper extends AbstractGeometryFieldMapper<Shape
throw new ElasticsearchParseException("Field parameter [{}] is not supported for [{}] field type", throw new ElasticsearchParseException("Field parameter [{}] is not supported for [{}] field type",
fieldName, CONTENT_TYPE); fieldName, CONTENT_TYPE);
} }
DEPRECATION_LOGGER.deprecated("Field parameter [{}] is deprecated and will be removed in a future version.", DEPRECATION_LOGGER.deprecatedAndMaybeLog("geo_mapper_field_parameter",
fieldName); "Field parameter [{}] is deprecated and will be removed in a future version.", fieldName);
} }
} }

View file

@ -454,7 +454,7 @@ public class MapperService extends AbstractIndexComponent implements Closeable {
if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) { if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) {
throw new IllegalArgumentException(DEFAULT_MAPPING_ERROR_MESSAGE); throw new IllegalArgumentException(DEFAULT_MAPPING_ERROR_MESSAGE);
} else if (reason == MergeReason.MAPPING_UPDATE) { // only log in case of explicit mapping updates } else if (reason == MergeReason.MAPPING_UPDATE) { // only log in case of explicit mapping updates
deprecationLogger.deprecated(DEFAULT_MAPPING_ERROR_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("default_mapping_not_allowed", DEFAULT_MAPPING_ERROR_MESSAGE);
} }
assert defaultMapper.type().equals(DEFAULT_MAPPING); assert defaultMapper.type().equals(DEFAULT_MAPPING);
results.put(DEFAULT_MAPPING, defaultMapper); results.put(DEFAULT_MAPPING, defaultMapper);
@ -785,7 +785,8 @@ public class MapperService extends AbstractIndexComponent implements Closeable {
*/ */
public MappedFieldType unmappedFieldType(String type) { public MappedFieldType unmappedFieldType(String type) {
if (type.equals("string")) { if (type.equals("string")) {
deprecationLogger.deprecated("[unmapped_type:string] should be replaced with [unmapped_type:keyword]"); deprecationLogger.deprecatedAndMaybeLog("unmapped_type_string",
"[unmapped_type:string] should be replaced with [unmapped_type:keyword]");
type = "keyword"; type = "keyword";
} }
MappedFieldType fieldType = unmappedFieldTypes.get(type); MappedFieldType fieldType = unmappedFieldTypes.get(type);

View file

@ -197,7 +197,8 @@ public class ObjectMapper extends Mapper implements Cloneable {
} }
return true; return true;
} else if (fieldName.equals("include_in_all")) { } else if (fieldName.equals("include_in_all")) {
deprecationLogger.deprecated("[include_in_all] is deprecated, the _all field have been removed in this version"); deprecationLogger.deprecatedAndMaybeLog("include_in_all",
"[include_in_all] is deprecated, the _all field have been removed in this version");
return true; return true;
} }
return false; return false;

View file

@ -168,7 +168,7 @@ public class RandomScoreFunctionBuilder extends ScoreFunctionBuilder<RandomScore
if (field != null) { if (field != null) {
fieldType = context.getMapperService().fieldType(field); fieldType = context.getMapperService().fieldType(field);
} else { } else {
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog("seed_requires_field",
"As of version 7.0 Elasticsearch will require that a [field] parameter is provided when a [seed] is set"); "As of version 7.0 Elasticsearch will require that a [field] parameter is provided when a [seed] is set");
fieldType = context.getMapperService().fieldType(IdFieldMapper.NAME); fieldType = context.getMapperService().fieldType(IdFieldMapper.NAME);
} }

View file

@ -143,7 +143,7 @@ final class SimilarityProviders {
throw new IllegalArgumentException("Basic model [" + basicModel + "] isn't supported anymore, " + throw new IllegalArgumentException("Basic model [" + basicModel + "] isn't supported anymore, " +
"please use another model."); "please use another model.");
} else { } else {
deprecationLogger.deprecated("Basic model [" + basicModel + deprecationLogger.deprecatedAndMaybeLog(basicModel + "_similarity_model_replaced", "Basic model [" + basicModel +
"] isn't supported anymore and has arbitrarily been replaced with [" + replacement + "]."); "] isn't supported anymore and has arbitrarily been replaced with [" + replacement + "].");
model = BASIC_MODELS.get(replacement); model = BASIC_MODELS.get(replacement);
assert model != null; assert model != null;
@ -174,7 +174,7 @@ final class SimilarityProviders {
throw new IllegalArgumentException("After effect [" + afterEffect + throw new IllegalArgumentException("After effect [" + afterEffect +
"] isn't supported anymore, please use another effect."); "] isn't supported anymore, please use another effect.");
} else { } else {
deprecationLogger.deprecated("After effect [" + afterEffect + deprecationLogger.deprecatedAndMaybeLog(afterEffect + "_after_effect_replaced", "After effect [" + afterEffect +
"] isn't supported anymore and has arbitrarily been replaced with [" + replacement + "]."); "] isn't supported anymore and has arbitrarily been replaced with [" + replacement + "].");
effect = AFTER_EFFECTS.get(replacement); effect = AFTER_EFFECTS.get(replacement);
assert effect != null; assert effect != null;
@ -264,7 +264,8 @@ final class SimilarityProviders {
if (version.onOrAfter(Version.V_7_0_0)) { if (version.onOrAfter(Version.V_7_0_0)) {
throw new IllegalArgumentException("Unknown settings for similarity of type [" + type + "]: " + unknownSettings); throw new IllegalArgumentException("Unknown settings for similarity of type [" + type + "]: " + unknownSettings);
} else { } else {
deprecationLogger.deprecated("Unknown settings for similarity of type [" + type + "]: " + unknownSettings); deprecationLogger.deprecatedAndMaybeLog("unknown_similarity_setting",
"Unknown settings for similarity of type [" + type + "]: " + unknownSettings);
} }
} }
} }

View file

@ -67,7 +67,8 @@ public final class SimilarityService extends AbstractIndexComponent {
} else { } else {
final ClassicSimilarity similarity = SimilarityProviders.createClassicSimilarity(Settings.EMPTY, version); final ClassicSimilarity similarity = SimilarityProviders.createClassicSimilarity(Settings.EMPTY, version);
return () -> { return () -> {
deprecationLogger.deprecated("The [classic] similarity is now deprecated in favour of BM25, which is generally " deprecationLogger.deprecatedAndMaybeLog("classic_similarity",
"The [classic] similarity is now deprecated in favour of BM25, which is generally "
+ "accepted as a better alternative. Use the [BM25] similarity or build a custom [scripted] similarity " + "accepted as a better alternative. Use the [BM25] similarity or build a custom [scripted] similarity "
+ "instead."); + "instead.");
return similarity; return similarity;
@ -90,7 +91,8 @@ public final class SimilarityService extends AbstractIndexComponent {
throw new IllegalArgumentException("The [classic] similarity may not be used anymore. Please use the [BM25] " throw new IllegalArgumentException("The [classic] similarity may not be used anymore. Please use the [BM25] "
+ "similarity or build a custom [scripted] similarity instead."); + "similarity or build a custom [scripted] similarity instead.");
} else { } else {
deprecationLogger.deprecated("The [classic] similarity is now deprecated in favour of BM25, which is generally " deprecationLogger.deprecatedAndMaybeLog("classic_similarity",
"The [classic] similarity is now deprecated in favour of BM25, which is generally "
+ "accepted as a better alternative. Use the [BM25] similarity or build a custom [scripted] similarity " + "accepted as a better alternative. Use the [BM25] similarity or build a custom [scripted] similarity "
+ "instead."); + "instead.");
return SimilarityProviders.createClassicSimilarity(settings, version); return SimilarityProviders.createClassicSimilarity(settings, version);
@ -154,7 +156,8 @@ public final class SimilarityService extends AbstractIndexComponent {
defaultSimilarity = (providers.get("default") != null) ? providers.get("default").get() defaultSimilarity = (providers.get("default") != null) ? providers.get("default").get()
: providers.get(SimilarityService.DEFAULT_SIMILARITY).get(); : providers.get(SimilarityService.DEFAULT_SIMILARITY).get();
if (providers.get("base") != null) { if (providers.get("base") != null) {
deprecationLogger.deprecated("The [base] similarity is ignored since query normalization and coords have been removed"); deprecationLogger.deprecatedAndMaybeLog("base_similarity_ignored",
"The [base] similarity is ignored since query normalization and coords have been removed");
} }
} }
@ -270,7 +273,7 @@ public final class SimilarityService extends AbstractIndexComponent {
if (indexCreatedVersion.onOrAfter(Version.V_7_0_0)) { if (indexCreatedVersion.onOrAfter(Version.V_7_0_0)) {
throw new IllegalArgumentException(message); throw new IllegalArgumentException(message);
} else if (indexCreatedVersion.onOrAfter(Version.V_6_5_0)) { } else if (indexCreatedVersion.onOrAfter(Version.V_6_5_0)) {
deprecationLogger.deprecated(message); deprecationLogger.deprecatedAndMaybeLog("similarity_failure", message);
} }
} }

View file

@ -57,7 +57,7 @@ public class DeprecationRestHandler implements RestHandler {
*/ */
@Override @Override
public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception { public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
deprecationLogger.deprecated(deprecationMessage); deprecationLogger.deprecatedAndMaybeLog("deprecated_route", deprecationMessage);
handler.handleRequest(request, channel, client); handler.handleRequest(request, channel, client);
} }

View file

@ -89,7 +89,8 @@ public class RestGetMappingAction extends BaseRestHandler {
boolean includeTypeName = request.paramAsBoolean(INCLUDE_TYPE_NAME_PARAMETER, DEFAULT_INCLUDE_TYPE_NAME_POLICY); boolean includeTypeName = request.paramAsBoolean(INCLUDE_TYPE_NAME_PARAMETER, DEFAULT_INCLUDE_TYPE_NAME_POLICY);
if (request.method().equals(HEAD)) { if (request.method().equals(HEAD)) {
deprecationLogger.deprecated("Type exists requests are deprecated, as types have been deprecated."); deprecationLogger.deprecatedAndMaybeLog("get_mapping_types_removal",
"Type exists requests are deprecated, as types have been deprecated.");
} else if (includeTypeName == false && types.length > 0) { } else if (includeTypeName == false && types.length > 0) {
throw new IllegalArgumentException("Types cannot be provided in get mapping requests, unless" + throw new IllegalArgumentException("Types cannot be provided in get mapping requests, unless" +
" include_type_name is set to true."); " include_type_name is set to true.");

View file

@ -69,7 +69,8 @@ public class RestPutIndexTemplateAction extends BaseRestHandler {
deprecationLogger.deprecatedAndMaybeLog("put_index_template_with_types", TYPES_DEPRECATION_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("put_index_template_with_types", TYPES_DEPRECATION_MESSAGE);
} }
if (request.hasParam("template")) { if (request.hasParam("template")) {
deprecationLogger.deprecated("Deprecated parameter[template] used, replaced by [index_patterns]"); deprecationLogger.deprecatedAndMaybeLog("put_index_template_deprecated_parameter",
"Deprecated parameter [template] used, replaced by [index_patterns]");
putRequest.patterns(Collections.singletonList(request.param("template"))); putRequest.patterns(Collections.singletonList(request.param("template")));
} else { } else {
putRequest.patterns(Arrays.asList(request.paramAsStringArray("index_patterns", Strings.EMPTY_ARRAY))); putRequest.patterns(Arrays.asList(request.paramAsStringArray("index_patterns", Strings.EMPTY_ARRAY)));

View file

@ -71,7 +71,8 @@ public abstract class RestResizeHandler extends BaseRestHandler {
throw new IllegalArgumentException("parameter [copy_settings] can not be explicitly set to [false]"); throw new IllegalArgumentException("parameter [copy_settings] can not be explicitly set to [false]");
} }
} }
deprecationLogger.deprecated("parameter [copy_settings] is deprecated and will be removed in 8.0.0"); deprecationLogger.deprecatedAndMaybeLog("resize_deprecated_parameter",
"parameter [copy_settings] is deprecated and will be removed in 8.0.0");
} }
resizeRequest.setCopySettings(copySettings); resizeRequest.setCopySettings(copySettings);
request.applyContentParser(resizeRequest::fromXContent); request.applyContentParser(resizeRequest::fromXContent);

View file

@ -96,7 +96,7 @@ public class RestNodesAction extends AbstractCatAction {
final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
clusterStateRequest.clear().nodes(true); clusterStateRequest.clear().nodes(true);
if (request.hasParam("local")) { if (request.hasParam("local")) {
deprecationLogger.deprecated(LOCAL_DEPRECATED_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("cat_nodes_local_parameter", LOCAL_DEPRECATED_MESSAGE);
} }
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));

View file

@ -96,7 +96,7 @@ public class RestMultiGetAction extends BaseRestHandler {
for (MultiGetRequest.Item item : multiGetRequest.getItems()) { for (MultiGetRequest.Item item : multiGetRequest.getItems()) {
if (item.type() != null) { if (item.type() != null) {
deprecationLogger.deprecated(TYPES_DEPRECATION_MESSAGE); deprecationLogger.deprecatedAndMaybeLog("multi_get_types_removal", TYPES_DEPRECATION_MESSAGE);
break; break;
} }
} }

View file

@ -219,9 +219,9 @@ public final class ScriptMetadata implements Metadata.Custom, Writeable, ToXCont
if (source.getSource().isEmpty()) { if (source.getSource().isEmpty()) {
if (source.getLang().equals(Script.DEFAULT_TEMPLATE_LANG)) { if (source.getLang().equals(Script.DEFAULT_TEMPLATE_LANG)) {
deprecationLogger.deprecated("empty templates should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_templates","empty templates should no longer be used");
} else { } else {
deprecationLogger.deprecated("empty scripts should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_scripts", "empty scripts should no longer be used");
} }
} }
} }

View file

@ -145,9 +145,9 @@ public class StoredScriptSource extends AbstractDiffable<StoredScriptSource> imp
if (source == null) { if (source == null) {
if (ignoreEmpty || Script.DEFAULT_TEMPLATE_LANG.equals(lang)) { if (ignoreEmpty || Script.DEFAULT_TEMPLATE_LANG.equals(lang)) {
if (Script.DEFAULT_TEMPLATE_LANG.equals(lang)) { if (Script.DEFAULT_TEMPLATE_LANG.equals(lang)) {
deprecationLogger.deprecated("empty templates should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_templates", "empty templates should no longer be used");
} else { } else {
deprecationLogger.deprecated("empty scripts should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_scripts", "empty scripts should no longer be used");
} }
} else { } else {
throw new IllegalArgumentException("must specify source for stored script"); throw new IllegalArgumentException("must specify source for stored script");
@ -155,9 +155,9 @@ public class StoredScriptSource extends AbstractDiffable<StoredScriptSource> imp
} else if (source.isEmpty()) { } else if (source.isEmpty()) {
if (ignoreEmpty || Script.DEFAULT_TEMPLATE_LANG.equals(lang)) { if (ignoreEmpty || Script.DEFAULT_TEMPLATE_LANG.equals(lang)) {
if (Script.DEFAULT_TEMPLATE_LANG.equals(lang)) { if (Script.DEFAULT_TEMPLATE_LANG.equals(lang)) {
deprecationLogger.deprecated("empty templates should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_templates", "empty templates should no longer be used");
} else { } else {
deprecationLogger.deprecated("empty scripts should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_scripts", "empty scripts should no longer be used");
} }
} else { } else {
throw new IllegalArgumentException("source cannot be empty"); throw new IllegalArgumentException("source cannot be empty");
@ -257,7 +257,7 @@ public class StoredScriptSource extends AbstractDiffable<StoredScriptSource> imp
token = parser.nextToken(); token = parser.nextToken();
if (token == Token.END_OBJECT) { if (token == Token.END_OBJECT) {
deprecationLogger.deprecated("empty templates should no longer be used"); deprecationLogger.deprecatedAndMaybeLog("empty_templates", "empty templates should no longer be used");
return new StoredScriptSource(Script.DEFAULT_TEMPLATE_LANG, "", Collections.emptyMap()); return new StoredScriptSource(Script.DEFAULT_TEMPLATE_LANG, "", Collections.emptyMap());
} }

View file

@ -574,7 +574,8 @@ public abstract class InternalOrder extends BucketOrder {
} }
// _term and _time order deprecated in 6.0; replaced by _key // _term and _time order deprecated in 6.0; replaced by _key
if ("_term".equals(orderKey) || "_time".equals(orderKey)) { if ("_term".equals(orderKey) || "_time".equals(orderKey)) {
deprecationLogger.deprecated("Deprecated aggregation order key [{}] used, replaced by [_key]", orderKey); deprecationLogger.deprecatedAndMaybeLog("aggregation_order_key",
"Deprecated aggregation order key [{}] used, replaced by [_key]", orderKey);
} }
switch (orderKey) { switch (orderKey) {
case "_term": case "_term":

View file

@ -387,7 +387,8 @@ public class SignificantTermsAggregatorFactory extends ValuesSourceAggregatorFac
if ("global_ordinals".equals(value)) { if ("global_ordinals".equals(value)) {
return GLOBAL_ORDINALS; return GLOBAL_ORDINALS;
} else if ("global_ordinals_hash".equals(value)) { } else if ("global_ordinals_hash".equals(value)) {
deprecationLogger.deprecated("global_ordinals_hash is deprecated. Please use [global_ordinals] instead."); deprecationLogger.deprecatedAndMaybeLog("global_ordinals_hash",
"global_ordinals_hash is deprecated. Please use [global_ordinals] instead.");
return GLOBAL_ORDINALS; return GLOBAL_ORDINALS;
} else if ("map".equals(value)) { } else if ("map".equals(value)) {
return MAP; return MAP;

View file

@ -301,7 +301,8 @@ public class MovAvgPipelineAggregationBuilder extends AbstractPipelineAggregatio
Integer predict = null; Integer predict = null;
Boolean minimize = null; Boolean minimize = null;
DEPRECATION_LOGGER.deprecated("The moving_avg aggregation has been deprecated in favor of the moving_fn aggregation."); DEPRECATION_LOGGER.deprecatedAndMaybeLog("moving_avg_aggregation",
"The moving_avg aggregation has been deprecated in favor of the moving_fn aggregation.");
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {

View file

@ -1106,7 +1106,7 @@ public final class SearchSourceBuilder implements Writeable, ToXContentObject, R
scriptFields.add(new ScriptField(parser)); scriptFields.add(new ScriptField(parser));
} }
} else if (INDICES_BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { } else if (INDICES_BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog("indices_boost_object_format",
"Object format in indices_boost is deprecated, please use array format instead"); "Object format in indices_boost is deprecated, please use array format instead");
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {

View file

@ -87,7 +87,8 @@ public final class FetchDocValuesPhase implements FetchSubPhase {
.filter(USE_DEFAULT_FORMAT::equals) .filter(USE_DEFAULT_FORMAT::equals)
.findAny() .findAny()
.isPresent()) { .isPresent()) {
DEPRECATION_LOGGER.deprecated("[" + USE_DEFAULT_FORMAT + "] is a special format that was only used to " + DEPRECATION_LOGGER.deprecatedAndMaybeLog("explicit_default_format",
"[" + USE_DEFAULT_FORMAT + "] is a special format that was only used to " +
"ease the transition to 7.x. It has become the default and shouldn't be set explicitly anymore."); "ease the transition to 7.x. It has become the default and shouldn't be set explicitly anymore.");
} }

View file

@ -263,7 +263,8 @@ public class SliceBuilder implements Writeable, ToXContentObject {
if (context.getIndexSettings().getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) { if (context.getIndexSettings().getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) {
throw new IllegalArgumentException("Computing slices on the [_uid] field is illegal for 7.x indices, use [_id] instead"); throw new IllegalArgumentException("Computing slices on the [_uid] field is illegal for 7.x indices, use [_id] instead");
} }
DEPRECATION_LOG.deprecated("Computing slices on the [_uid] field is deprecated for 6.x indices, use [_id] instead"); DEPRECATION_LOG.deprecatedAndMaybeLog("slice_on_uid",
"Computing slices on the [_uid] field is deprecated for 6.x indices, use [_id] instead");
useTermQuery = true; useTermQuery = true;
} else if (IdFieldMapper.NAME.equals(field)) { } else if (IdFieldMapper.NAME.equals(field)) {
useTermQuery = true; useTermQuery = true;

View file

@ -693,14 +693,16 @@ public class FieldSortBuilder extends SortBuilder<FieldSortBuilder> {
static { static {
PARSER.declareField(FieldSortBuilder::missing, XContentParser::objectText, MISSING, ValueType.VALUE); PARSER.declareField(FieldSortBuilder::missing, XContentParser::objectText, MISSING, ValueType.VALUE);
PARSER.declareString((fieldSortBuilder, nestedPath) -> { PARSER.declareString((fieldSortBuilder, nestedPath) -> {
deprecationLogger.deprecated("[nested_path] has been deprecated in favor of the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("field_sort_nested_path",
"[nested_path] has been deprecated in favor of the [nested] parameter");
fieldSortBuilder.setNestedPath(nestedPath); fieldSortBuilder.setNestedPath(nestedPath);
}, NESTED_PATH_FIELD); }, NESTED_PATH_FIELD);
PARSER.declareString(FieldSortBuilder::unmappedType , UNMAPPED_TYPE); PARSER.declareString(FieldSortBuilder::unmappedType , UNMAPPED_TYPE);
PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)) , ORDER_FIELD); PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)) , ORDER_FIELD);
PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORT_MODE); PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORT_MODE);
PARSER.declareObject(FieldSortBuilder::setNestedFilter, (p, c) -> { PARSER.declareObject(FieldSortBuilder::setNestedFilter, (p, c) -> {
deprecationLogger.deprecated("[nested_filter] has been deprecated in favour for the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("field_sort_nested_filter",
"[nested_filter] has been deprecated in favour for the [nested] parameter");
return SortBuilder.parseNestedFilter(p); return SortBuilder.parseNestedFilter(p);
}, NESTED_FILTER_FIELD); }, NESTED_FILTER_FIELD);
PARSER.declareObject(FieldSortBuilder::setNestedSort, (p, c) -> NestedSortBuilder.fromXContent(p), NESTED_FIELD); PARSER.declareObject(FieldSortBuilder::setNestedSort, (p, c) -> NestedSortBuilder.fromXContent(p), NESTED_FIELD);

View file

@ -491,7 +491,8 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
fieldName = currentName; fieldName = currentName;
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (NESTED_FILTER_FIELD.match(currentName, parser.getDeprecationHandler())) { if (NESTED_FILTER_FIELD.match(currentName, parser.getDeprecationHandler())) {
deprecationLogger.deprecated("[nested_filter] has been deprecated in favour of the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("geo_distance_nested_filter",
"[nested_filter] has been deprecated in favour of the [nested] parameter");
nestedFilter = parseInnerQueryBuilder(parser); nestedFilter = parseInnerQueryBuilder(parser);
} else if (NESTED_FIELD.match(currentName, parser.getDeprecationHandler())) { } else if (NESTED_FIELD.match(currentName, parser.getDeprecationHandler())) {
nestedSort = NestedSortBuilder.fromXContent(parser); nestedSort = NestedSortBuilder.fromXContent(parser);
@ -521,7 +522,8 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
} else if (SORTMODE_FIELD.match(currentName, parser.getDeprecationHandler())) { } else if (SORTMODE_FIELD.match(currentName, parser.getDeprecationHandler())) {
sortMode = SortMode.fromString(parser.text()); sortMode = SortMode.fromString(parser.text());
} else if (NESTED_PATH_FIELD.match(currentName, parser.getDeprecationHandler())) { } else if (NESTED_PATH_FIELD.match(currentName, parser.getDeprecationHandler())) {
deprecationLogger.deprecated("[nested_path] has been deprecated in favour of the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("geo_distance_nested_path",
"[nested_path] has been deprecated in favour of the [nested] parameter");
nestedPath = parser.text(); nestedPath = parser.text();
} else if (IGNORE_UNMAPPED.match(currentName, parser.getDeprecationHandler())) { } else if (IGNORE_UNMAPPED.match(currentName, parser.getDeprecationHandler())) {
ignoreUnmapped = parser.booleanValue(); ignoreUnmapped = parser.booleanValue();

View file

@ -281,11 +281,13 @@ public class ScriptSortBuilder extends SortBuilder<ScriptSortBuilder> {
PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)), ORDER_FIELD); PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)), ORDER_FIELD);
PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORTMODE_FIELD); PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORTMODE_FIELD);
PARSER.declareString((fieldSortBuilder, nestedPath) -> { PARSER.declareString((fieldSortBuilder, nestedPath) -> {
deprecationLogger.deprecated("[nested_path] has been deprecated in favor of the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("script_nested_path",
"[nested_path] has been deprecated in favor of the [nested] parameter");
fieldSortBuilder.setNestedPath(nestedPath); fieldSortBuilder.setNestedPath(nestedPath);
}, NESTED_PATH_FIELD); }, NESTED_PATH_FIELD);
PARSER.declareObject(ScriptSortBuilder::setNestedFilter, (p, c) -> { PARSER.declareObject(ScriptSortBuilder::setNestedFilter, (p, c) -> {
deprecationLogger.deprecated("[nested_filter] has been deprecated in favour for the [nested] parameter"); deprecationLogger.deprecatedAndMaybeLog("script_nested_filter",
"[nested_filter] has been deprecated in favour for the [nested] parameter");
return SortBuilder.parseNestedFilter(p); return SortBuilder.parseNestedFilter(p);
}, NESTED_FILTER_FIELD); }, NESTED_FILTER_FIELD);
PARSER.declareObject(ScriptSortBuilder::setNestedSort, (p, c) -> NestedSortBuilder.fromXContent(p), NESTED_FIELD); PARSER.declareObject(ScriptSortBuilder::setNestedSort, (p, c) -> NestedSortBuilder.fromXContent(p), NESTED_FIELD);

View file

@ -103,7 +103,7 @@ public class TransportInfo implements ReportingService.Info {
if (cnameInPublishAddress) { if (cnameInPublishAddress) {
publishAddressString = hostString + '/' + publishAddress.toString(); publishAddressString = hostString + '/' + publishAddress.toString();
} else { } else {
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog("cname_in_publish_address",
propertyName + " was printed as [ip:port] instead of [hostname/ip:port]. " propertyName + " was printed as [ip:port] instead of [hostname/ip:port]. "
+ "This format is deprecated and will change to [hostname/ip:port] in a future version. " + "This format is deprecated and will change to [hostname/ip:port] in a future version. "
+ "Use -Des.transport.cname_in_publish_address=true to enforce non-deprecated formatting." + "Use -Des.transport.cname_in_publish_address=true to enforce non-deprecated formatting."

View file

@ -118,13 +118,15 @@ public class TransportAnalyzeActionTests extends ESTestCase {
@Override @Override
public TokenStream create(TokenStream tokenStream) { public TokenStream create(TokenStream tokenStream) {
deprecationLogger.deprecated("Using deprecated token filter [deprecated]"); deprecationLogger.deprecatedAndMaybeLog("deprecated_token_filter_create",
"Using deprecated token filter [deprecated]");
return tokenStream; return tokenStream;
} }
@Override @Override
public TokenStream normalize(TokenStream tokenStream) { public TokenStream normalize(TokenStream tokenStream) {
deprecationLogger.deprecated("Using deprecated token filter [deprecated]"); deprecationLogger.deprecatedAndMaybeLog("deprecated_token_filter_normalize",
"Using deprecated token filter [deprecated]");
return tokenStream; return tokenStream;
} }
} }

View file

@ -166,7 +166,7 @@ public class DeprecationLoggerTests extends ESTestCase {
ThreadContext threadContext = new ThreadContext(Settings.EMPTY); ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
DeprecationLogger.setThreadContext(threadContext); DeprecationLogger.setThreadContext(threadContext);
logger.deprecated(expected); logger.deprecatedAndMaybeLog("testCanRemoveThreadContext_key1", expected);
{ {
final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders(); final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders();
@ -178,7 +178,7 @@ public class DeprecationLoggerTests extends ESTestCase {
} }
DeprecationLogger.removeThreadContext(threadContext); DeprecationLogger.removeThreadContext(threadContext);
logger.deprecated(unexpected); logger.deprecatedAndMaybeLog("testCanRemoveThreadContext_key2", unexpected);
{ {
final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders(); final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders();
@ -340,7 +340,7 @@ public class DeprecationLoggerTests extends ESTestCase {
new ProtectionDomain[]{new ProtectionDomain(null, new Permissions())} new ProtectionDomain[]{new ProtectionDomain(null, new Permissions())}
); );
AccessController.doPrivileged((PrivilegedAction<Void>) () -> { AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
deprecationLogger.deprecated("foo", "bar"); deprecationLogger.deprecatedAndMaybeLog("testLogPermissions_key", "foo", "bar");
return null; return null;
}, noPermissionsAcc); }, noPermissionsAcc);
assertThat("supplier called", supplierCalled.get(), is(true)); assertThat("supplier called", supplierCalled.get(), is(true));

View file

@ -81,8 +81,8 @@ public class AnalysisRegistryTests extends ESTestCase {
public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() { public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() {
return singletonList(PreConfiguredTokenFilter.singleton("reverse", true, ReverseStringFilter::new)); return singletonList(PreConfiguredTokenFilter.singleton("reverse", true, ReverseStringFilter::new));
} }
} }
private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder settings) { private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder settings) {
return IndexSettingsModule.newIndexSettings("index", settings return IndexSettingsModule.newIndexSettings("index", settings
.put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
@ -154,29 +154,29 @@ public class AnalysisRegistryTests extends ESTestCase {
emptyMap(), emptyMap(), emptyMap())); emptyMap(), emptyMap(), emptyMap()));
assertEquals("analyzer [default] contains filters [my_filter] that are not allowed to run in all mode.", ex.getMessage()); assertEquals("analyzer [default] contains filters [my_filter] that are not allowed to run in all mode.", ex.getMessage());
} }
public void testNameClashNormalizer() throws IOException { public void testNameClashNormalizer() throws IOException {
// Test out-of-the-box normalizer works OK. // Test out-of-the-box normalizer works OK.
IndexAnalyzers indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", Settings.EMPTY)); IndexAnalyzers indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", Settings.EMPTY));
assertNotNull(indexAnalyzers.getNormalizer("lowercase")); assertNotNull(indexAnalyzers.getNormalizer("lowercase"));
assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field", "AbC").utf8ToString(), equalTo("abc")); assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field", "AbC").utf8ToString(), equalTo("abc"));
// Test that a name clash with a custom normalizer will favour the index's normalizer rather than the out-of-the-box // Test that a name clash with a custom normalizer will favour the index's normalizer rather than the out-of-the-box
// one of the same name. (However this "feature" will be removed with https://github.com/elastic/elasticsearch/issues/22263 ) // one of the same name. (However this "feature" will be removed with https://github.com/elastic/elasticsearch/issues/22263 )
Settings settings = Settings.builder() Settings settings = Settings.builder()
// Deliberately bad choice of normalizer name for the job it does. // Deliberately bad choice of normalizer name for the job it does.
.put("index.analysis.normalizer.lowercase.type", "custom") .put("index.analysis.normalizer.lowercase.type", "custom")
.putList("index.analysis.normalizer.lowercase.filter", "reverse") .putList("index.analysis.normalizer.lowercase.filter", "reverse")
.build(); .build();
indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", settings)); indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", settings));
assertNotNull(indexAnalyzers.getNormalizer("lowercase")); assertNotNull(indexAnalyzers.getNormalizer("lowercase"));
assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field","AbC").utf8ToString(), equalTo("CbA")); assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field","AbC").utf8ToString(), equalTo("CbA"));
} }
public void testOverrideDefaultIndexAnalyzerIsUnsupported() { public void testOverrideDefaultIndexAnalyzerIsUnsupported() {
Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_alpha1, Version.CURRENT); Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_alpha1, Version.CURRENT);
Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build(); Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build();
@ -326,7 +326,7 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override @Override
public TokenStream create(TokenStream tokenStream) { public TokenStream create(TokenStream tokenStream) {
if (indexSettings.getIndexVersionCreated().equals(Version.CURRENT)) { if (indexSettings.getIndexVersionCreated().equals(Version.CURRENT)) {
deprecationLogger.deprecated("Using deprecated token filter [deprecated]"); deprecationLogger.deprecatedAndMaybeLog("deprecated_token_filter", "Using deprecated token filter [deprecated]");
} }
return tokenStream; return tokenStream;
} }
@ -354,7 +354,7 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override @Override
public TokenStream create(TokenStream tokenStream) { public TokenStream create(TokenStream tokenStream) {
deprecationLogger.deprecated("Using deprecated token filter [unused]"); deprecationLogger.deprecatedAndMaybeLog("unused_token_filter", "Using deprecated token filter [unused]");
return tokenStream; return tokenStream;
} }
} }
@ -367,7 +367,8 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override @Override
public TokenStream create(TokenStream tokenStream) { public TokenStream create(TokenStream tokenStream) {
deprecationLogger.deprecated("Using deprecated token filter [deprecated_normalizer]"); deprecationLogger.deprecatedAndMaybeLog("deprecated_normalizer",
"Using deprecated token filter [deprecated_normalizer]");
return tokenStream; return tokenStream;
} }

View file

@ -77,7 +77,7 @@ public class DeprecationRestHandlerTests extends ESTestCase {
InOrder inOrder = inOrder(handler, request, channel, deprecationLogger); InOrder inOrder = inOrder(handler, request, channel, deprecationLogger);
// log, then forward // log, then forward
inOrder.verify(deprecationLogger).deprecated(deprecationMessage); inOrder.verify(deprecationLogger).deprecatedAndMaybeLog("deprecated_route", deprecationMessage);
inOrder.verify(handler).handleRequest(request, channel, client); inOrder.verify(handler).handleRequest(request, channel, client);
inOrder.verifyNoMoreInteractions(); inOrder.verifyNoMoreInteractions();
} }

View file

@ -54,7 +54,7 @@ public class DeprecatedQueryBuilder extends AbstractQueryBuilder<DeprecatedQuery
@Override @Override
protected Query doToQuery(QueryShardContext context) { protected Query doToQuery(QueryShardContext context) {
deprecationLogger.deprecated("[deprecated] query"); deprecationLogger.deprecatedAndMaybeLog("to_query", "[deprecated] query");
return new MatchAllDocsQuery(); return new MatchAllDocsQuery();
} }

View file

@ -329,7 +329,8 @@ public class XPackPlugin extends XPackClientPlugin implements ExtensiblePlugin,
if (Files.exists(config) == false) { if (Files.exists(config) == false) {
Path legacyConfig = env.configFile().resolve("x-pack").resolve(name); Path legacyConfig = env.configFile().resolve("x-pack").resolve(name);
if (Files.exists(legacyConfig)) { if (Files.exists(legacyConfig)) {
deprecationLogger.deprecated("Config file [" + name + "] is in a deprecated location. Move from " + deprecationLogger.deprecatedAndMaybeLog("config_file_path",
"Config file [" + name + "] is in a deprecated location. Move from " +
legacyConfig.toString() + " to " + config.toString()); legacyConfig.toString() + " to " + config.toString());
return legacyConfig; return legacyConfig;
} }

View file

@ -348,7 +348,7 @@ public class DatafeedUpdate implements Writeable, ToXContentObject {
DatafeedConfig.Builder builder = new DatafeedConfig.Builder(datafeedConfig); DatafeedConfig.Builder builder = new DatafeedConfig.Builder(datafeedConfig);
if (jobId != null) { if (jobId != null) {
if (datafeedConfig.getJobId() != null && datafeedConfig.getJobId().equals(jobId) == false) { if (datafeedConfig.getJobId() != null && datafeedConfig.getJobId().equals(jobId) == false) {
deprecationLogger.deprecated(DEPRECATION_MESSAGE_ON_JOB_ID_UPDATE); deprecationLogger.deprecatedAndMaybeLog("update_datafeed_job_id", DEPRECATION_MESSAGE_ON_JOB_ID_UPDATE);
} }
builder.setJobId(jobId); builder.setJobId(jobId);
} }

View file

@ -542,7 +542,7 @@ public class SSLService {
// Client Authentication _should_ be required, but if someone turns it off, then this check is no longer relevant // Client Authentication _should_ be required, but if someone turns it off, then this check is no longer relevant
final SSLConfigurationSettings configurationSettings = SSLConfigurationSettings.withPrefix(prefix + "."); final SSLConfigurationSettings configurationSettings = SSLConfigurationSettings.withPrefix(prefix + ".");
if (isConfigurationValidForServerUsage(configuration) == false) { if (isConfigurationValidForServerUsage(configuration) == false) {
deprecationLogger.deprecated("invalid SSL configuration for " + prefix + deprecationLogger.deprecatedAndMaybeLog("invalid_ssl_configuration", "invalid SSL configuration for " + prefix +
" - server ssl configuration requires a key and certificate, but these have not been configured; you must set either " + " - server ssl configuration requires a key and certificate, but these have not been configured; you must set either " +
"[" + configurationSettings.x509KeyPair.keystorePath.getKey() + "], or both [" + "[" + configurationSettings.x509KeyPair.keystorePath.getKey() + "], or both [" +
configurationSettings.x509KeyPair.keyPath.getKey() + "] and [" + configurationSettings.x509KeyPair.keyPath.getKey() + "] and [" +
@ -554,7 +554,8 @@ public class SSLService {
.sorted() .sorted()
.collect(Collectors.toList()); .collect(Collectors.toList());
if (sslSettingNames.isEmpty() == false) { if (sslSettingNames.isEmpty() == false) {
deprecationLogger.deprecated("invalid configuration for " + prefix + " - [" + enabledSetting + deprecationLogger.deprecatedAndMaybeLog("invalid_ssl_configuration",
"invalid configuration for " + prefix + " - [" + enabledSetting +
"] is not set, but the following settings have been configured in elasticsearch.yml : [" + "] is not set, but the following settings have been configured in elasticsearch.yml : [" +
Strings.collectionToCommaDelimitedString(sslSettingNames) + "]"); Strings.collectionToCommaDelimitedString(sslSettingNames) + "]");
} }

View file

@ -117,7 +117,11 @@ public class GetTransformAction extends ActionType<GetTransformAction.Response>
builder.field(TransformField.COUNT.getPreferredName(), invalidTransforms.size()); builder.field(TransformField.COUNT.getPreferredName(), invalidTransforms.size());
builder.field(TransformField.TRANSFORMS.getPreferredName(), invalidTransforms); builder.field(TransformField.TRANSFORMS.getPreferredName(), invalidTransforms);
builder.endObject(); builder.endObject();
deprecationLogger.deprecated(INVALID_TRANSFORMS_DEPRECATION_WARNING, invalidTransforms.size()); deprecationLogger.deprecatedAndMaybeLog(
"invalid_transforms",
INVALID_TRANSFORMS_DEPRECATION_WARNING,
invalidTransforms.size()
);
} }
builder.endObject(); builder.endObject();

View file

@ -246,7 +246,8 @@ public class JobManager {
Job job = request.getJobBuilder().build(new Date()); Job job = request.getJobBuilder().build(new Date());
if (job.getDataDescription() != null && job.getDataDescription().getFormat() == DataDescription.DataFormat.DELIMITED) { if (job.getDataDescription() != null && job.getDataDescription().getFormat() == DataDescription.DataFormat.DELIMITED) {
deprecationLogger.deprecated("Creating jobs with delimited data format is deprecated. Please use xcontent instead."); deprecationLogger.deprecatedAndMaybeLog("ml_create_job_delimited_data",
"Creating jobs with delimited data format is deprecated. Please use xcontent instead.");
} }
// Check for the job in the cluster state first // Check for the job in the cluster state first

View file

@ -132,7 +132,8 @@ public class TransportPutRollupJobAction extends TransportMasterNodeAction<PutRo
String timeZone = request.getConfig().getGroupConfig().getDateHistogram().getTimeZone(); String timeZone = request.getConfig().getGroupConfig().getDateHistogram().getTimeZone();
String modernTZ = DateUtils.DEPRECATED_LONG_TIMEZONES.get(timeZone); String modernTZ = DateUtils.DEPRECATED_LONG_TIMEZONES.get(timeZone);
if (modernTZ != null) { if (modernTZ != null) {
deprecationLogger.deprecated("Creating Rollup job [" + request.getConfig().getId() + "] with timezone [" deprecationLogger.deprecatedAndMaybeLog("deprecated_timezone",
"Creating Rollup job [" + request.getConfig().getId() + "] with timezone ["
+ timeZone + "], but [" + timeZone + "] has been deprecated by the IANA. Use [" + modernTZ +"] instead."); + timeZone + "], but [" + timeZone + "] has been deprecated by the IANA. Use [" + modernTZ +"] instead.");
} }
} }

View file

@ -630,21 +630,23 @@ public class ApiKeyService {
@Override @Override
public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) { public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used in api key [{}], expected [{}] instead", deprecationLogger.deprecatedAndMaybeLog("api_key_field",
"{}Deprecated field [{}] used in api key [{}], expected [{}] instead",
prefix, usedName, apiKeyId, modernName); prefix, usedName, apiKeyId, modernName);
} }
@Override @Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) { public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used in api key [{}], replaced by [{}]", deprecationLogger.deprecatedAndMaybeLog("api_key_field",
"{}Deprecated field [{}] used in api key [{}], replaced by [{}]",
prefix, usedName, apiKeyId, replacedWith); prefix, usedName, apiKeyId, replacedWith);
} }
@Override @Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) { public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] "; String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated( deprecationLogger.deprecatedAndMaybeLog("api_key_field",
"{}Deprecated field [{}] used in api key [{}], which is unused and will be removed entirely", "{}Deprecated field [{}] used in api key [{}], which is unused and will be removed entirely",
prefix, usedName); prefix, usedName);
} }

View file

@ -347,7 +347,7 @@ public class Realms implements Iterable<Realm> {
private void logDeprecationIfFound(Set<String> missingOrderRealmSettingKeys, Map<String, Set<String>> orderToRealmOrderSettingKeys) { private void logDeprecationIfFound(Set<String> missingOrderRealmSettingKeys, Map<String, Set<String>> orderToRealmOrderSettingKeys) {
if (missingOrderRealmSettingKeys.size() > 0) { if (missingOrderRealmSettingKeys.size() > 0) {
deprecationLogger.deprecated("Found realms without order config: [{}]. " + deprecationLogger.deprecatedAndMaybeLog("unordered_realm_config", "Found realms without order config: [{}]. " +
"In next major release, node will fail to start with missing realm order.", "In next major release, node will fail to start with missing realm order.",
String.join("; ", missingOrderRealmSettingKeys) String.join("; ", missingOrderRealmSettingKeys)
); );
@ -359,7 +359,8 @@ public class Realms implements Iterable<Realm> {
.sorted() .sorted()
.collect(Collectors.toList()); .collect(Collectors.toList());
if (false == duplicatedRealmOrderSettingKeys.isEmpty()) { if (false == duplicatedRealmOrderSettingKeys.isEmpty()) {
deprecationLogger.deprecated("Found multiple realms configured with the same order: [{}]. " + deprecationLogger.deprecatedAndMaybeLog("duplicate_realm_order",
"Found multiple realms configured with the same order: [{}]. " +
"In next major release, node will fail to start with duplicated realm order.", "In next major release, node will fail to start with duplicated realm order.",
String.join("; ", duplicatedRealmOrderSettingKeys)); String.join("; ", duplicatedRealmOrderSettingKeys));
} }

View file

@ -523,9 +523,10 @@ class ActiveDirectorySessionFactory extends PoolingSessionFactory {
super(config, timeout, ignoreReferralErrors, logger, groupsResolver, metadataResolver, domainDN, super(config, timeout, ignoreReferralErrors, logger, groupsResolver, metadataResolver, domainDN,
ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING, UPN_USER_FILTER, threadPool); ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING, UPN_USER_FILTER, threadPool);
if (userSearchFilter.contains("{0}")) { if (userSearchFilter.contains("{0}")) {
new DeprecationLogger(logger).deprecated("The use of the account name variable {0} in the setting [" new DeprecationLogger(logger).deprecatedAndMaybeLog("ldap_settings",
+ RealmSettings.getFullSettingKey(config, ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING) + "The use of the account name variable {0} in the setting ["
"] has been deprecated and will be removed in a future version!"); + RealmSettings.getFullSettingKey(config, ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING)
+ "] has been deprecated and will be removed in a future version!");
} }
} }

View file

@ -157,10 +157,14 @@ public abstract class SessionFactory {
options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true)); options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true));
} }
} else if (hostnameVerificationExists) { } else if (hostnameVerificationExists) {
new DeprecationLogger(logger).deprecated("the setting [{}] has been deprecated and " + final String fullSettingKey = RealmSettings.getFullSettingKey(config, SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING);
"will be removed in a future version. use [{}] instead", final String deprecationKey = "deprecated_setting_" + fullSettingKey.replace('.', '_');
RealmSettings.getFullSettingKey(config, SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING), new DeprecationLogger(logger).deprecatedAndMaybeLog(
RealmSettings.getFullSettingKey(config, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM)); deprecationKey,
"the setting [{}] has been deprecated and " + "will be removed in a future version. use [{}] instead",
fullSettingKey,
RealmSettings.getFullSettingKey(config, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM)
);
if (config.getSetting(SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING)) { if (config.getSetting(SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING)) {
options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true)); options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true));
} }

View file

@ -206,7 +206,7 @@ public final class DeprecationRoleDescriptorConsumer implements Consumer<Collect
if (false == inferiorIndexNames.isEmpty()) { if (false == inferiorIndexNames.isEmpty()) {
final String logMessage = String.format(Locale.ROOT, ROLE_PERMISSION_DEPRECATION_STANZA, roleDescriptor.getName(), final String logMessage = String.format(Locale.ROOT, ROLE_PERMISSION_DEPRECATION_STANZA, roleDescriptor.getName(),
aliasName, String.join(", ", inferiorIndexNames)); aliasName, String.join(", ", inferiorIndexNames));
deprecationLogger.deprecated(logMessage); deprecationLogger.deprecatedAndMaybeLog("index_permissions_on_alias", logMessage);
} }
} }
} }

View file

@ -296,7 +296,8 @@ public final class DeprecationRoleDescriptorConsumerTests extends ESTestCase {
} }
private void verifyLogger(DeprecationLogger deprecationLogger, String roleName, String aliasName, String indexNames) { private void verifyLogger(DeprecationLogger deprecationLogger, String roleName, String aliasName, String indexNames) {
verify(deprecationLogger).deprecated("Role [" + roleName + "] contains index privileges covering the [" + aliasName verify(deprecationLogger).deprecatedAndMaybeLog("index_permissions_on_alias",
"Role [" + roleName + "] contains index privileges covering the [" + aliasName
+ "] alias but which do not cover some of the indices that it points to [" + indexNames + "]. Granting privileges over an" + "] alias but which do not cover some of the indices that it points to [" + indexNames + "]. Granting privileges over an"
+ " alias and hence granting privileges over all the indices that the alias points to is deprecated and will be removed" + " alias and hence granting privileges over all the indices that the alias points to is deprecated and will be removed"
+ " in a future version of Elasticsearch. Instead define permissions exclusively on index names or index name patterns."); + " in a future version of Elasticsearch. Instead define permissions exclusively on index names or index name patterns.");

View file

@ -60,7 +60,8 @@ public class RestWatcherStatsAction extends WatcherRestHandler {
} }
if (metrics.contains("pending_watches")) { if (metrics.contains("pending_watches")) {
deprecationLogger.deprecated("The pending_watches parameter is deprecated, use queued_watches instead"); deprecationLogger.deprecatedAndMaybeLog("pending_watches",
"The pending_watches parameter is deprecated, use queued_watches instead");
} }