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");
}
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,
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");
}
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 ["
+ IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting.");
} 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 + "]");
}
}

View File

@ -118,7 +118,8 @@ public class NGramTokenizerFactory extends AbstractTokenizerFactory {
+ maxAllowedNgramDiff + "] but was [" + ngramDiff + "]. This limit can be set by changing the ["
+ IndexSettings.MAX_NGRAM_DIFF_SETTING.getKey() + "] index level setting.");
} 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 + "]");
}
}

View File

@ -59,7 +59,8 @@ public class SynonymTokenFilterFactory extends AbstractTokenFilterFactory {
this.settings = settings;
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. " +
"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) {
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");
}
@ -356,7 +357,9 @@ public class UserAgentProcessor extends AbstractProcessor {
try {
Property value = valueOf(propertyName.toUpperCase(Locale.ROOT));
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;
}

View File

@ -67,7 +67,7 @@ class ReindexValidator {
state);
SearchSourceBuilder searchSource = request.getSearchRequest().source();
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) {
if (s.contains("%")) { // already encoded, pass-through to allow this in mixed version clusters
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;
}
try {

View File

@ -62,7 +62,8 @@ public class IcuNormalizerTokenFilterFactory extends AbstractTokenFilterFactory
String unicodeSetFilter = settings.get("unicodeSetFilter");
if (indexSettings.getIndexVersionCreated().onOrAfter(Version.V_7_0_0)) {
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 {
unicodeSetFilter = settings.get("unicode_set_filter");
}

View File

@ -48,7 +48,7 @@ public class AzureDiscoveryPlugin extends Plugin implements DiscoveryPlugin {
public AzureDiscoveryPlugin(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...");
}

View File

@ -135,11 +135,13 @@ final class Ec2ClientSettings {
return null;
} else {
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());
}
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());
}

View File

@ -249,7 +249,8 @@ class S3Repository extends BlobStoreRepository {
if (S3ClientSettings.checkDeprecatedCredentials(metadata.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.");
}

View File

@ -104,33 +104,6 @@ public class EvilLoggerTests extends ESTestCase {
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 {
setupLogging("deprecation");

View File

@ -80,7 +80,7 @@ public class TestDeprecatedQueryBuilder extends AbstractQueryBuilder<TestDepreca
@Override
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();
}

View File

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

View File

@ -343,7 +343,8 @@ public class PutIndexTemplateRequest extends MasterNodeRequest<PutIndexTemplateR
if (name.equals("template")) {
// This is needed to allow for bwc (beats, logstash) with pre-5.0 templates (#21009)
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()));
}
} else if (name.equals("index_patterns")) {

View File

@ -191,7 +191,8 @@ public class MultiSearchRequest extends ActionRequest implements CompositeIndice
// support first line with \n
if (nextMarker == 0) {
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");
continue;
}

View File

@ -361,7 +361,7 @@ final class Bootstrap {
"future versions of Elasticsearch will require Java 11; " +
"your Java version from [%s] does not meet this requirement",
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) {
try {

View File

@ -186,7 +186,8 @@ public class MetadataCreateIndexService {
.filter(descriptor -> descriptor.matchesIndexPattern(index))
.collect(toList());
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);
} else if (matchingDescriptors.size() > 1) {
// 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(",")),
name);
logger.warn(warning);
deprecationLogger.deprecated(warning);
deprecationLogger.deprecatedAndMaybeLog("index_template_pattern_overlap", warning);
}
IndexTemplateV2 finalIndexTemplate = template;
@ -593,7 +593,7 @@ public class MetadataIndexTemplateService {
.collect(Collectors.joining(",")),
request.name);
logger.warn(warning);
deprecationLogger.deprecated(warning);
deprecationLogger.deprecatedAndMaybeLog("index_template_pattern_overlap", warning);
} else {
// 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" +

View File

@ -67,7 +67,8 @@ public class OperationRouting {
if (ignoreAwarenessAttr == false) {
awarenessAttributes = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.get(settings);
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,
this::setAwarenessAttributes);
@ -91,7 +92,8 @@ public class OperationRouting {
boolean ignoreAwarenessAttr = parseBoolean(System.getProperty(IGNORE_AWARENESS_ATTRIBUTES_PROPERTY), false);
if (ignoreAwarenessAttr == 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;
}

View File

@ -101,7 +101,8 @@ public class DiskThresholdMonitor {
this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterSettings);
this.client = client;
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);
}
}
@ -292,7 +293,9 @@ public class DiskThresholdMonitor {
logger.info("releasing read-only-allow-delete block on indices: [{}]", indicesToAutoRelease);
updateIndicesReadOnly(indicesToAutoRelease, listener, false);
} 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);
logger.debug("[{}] disabled, not releasing read-only-allow-delete block on indices: [{}]",
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 java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.BitSet;
@ -110,15 +111,8 @@ public class DeprecationLogger {
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
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
protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) {
return size() > 128;
@ -135,8 +129,8 @@ public class DeprecationLogger {
*/
public void deprecatedAndMaybeLog(final String key, final String msg, final Object... params) {
String xOpaqueId = getXOpaqueId(THREAD_CONTEXT);
boolean log = keys.add(xOpaqueId + key);
deprecated(THREAD_CONTEXT, msg, log, params);
boolean shouldLog = keys.add(xOpaqueId + key);
deprecated(THREAD_CONTEXT, msg, shouldLog, params);
}
/*
@ -234,7 +228,7 @@ public class DeprecationLogger {
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();
if (iterator.hasNext()) {
final String formattedMessage = LoggerMessageFormat.format(message, params);
@ -251,12 +245,12 @@ public class DeprecationLogger {
}
}
if (log) {
if (shouldLog) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@SuppressLoggerChecks(reason = "safely delegates to logger")
@Override
public Void run() {
/**
/*
* There should be only one threadContext (in prod env), @see DeprecationLogger#setThreadContext
*/
String opaqueId = getXOpaqueId(threadContexts);
@ -360,7 +354,7 @@ public class DeprecationLogger {
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.

View File

@ -245,7 +245,8 @@ public class ByteSizeValue implements Writeable, Comparable<ByteSizeValue>, ToXC
} catch (final NumberFormatException e) {
try {
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 [{}]",
initialInput, settingName);
return new ByteSizeValue((long) (doubleValue * unit.toBytes(1)));

View File

@ -53,21 +53,21 @@ public class LoggingDeprecationHandler implements DeprecationHandler {
@Override
public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) {
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);
}
@Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) {
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);
}
@Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) {
String prefix = parserName == null ? "" : "[" + parserName + "][" + location.get() + "] ";
deprecationLogger.deprecated("{}Deprecated field [{}] used, this field is unused and will be removed entirely",
prefix, usedName);
deprecationLogger.deprecatedAndMaybeLog("deprecated_field",
"{}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 hostString = publishAddress.address().getHostString();
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 " +
"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"
+ " can be set by changing the [" + IndexSettings.MAX_SHINGLE_DIFF_SETTING.getKey() + "] index level setting.");
} 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 + "]");
}
}

View File

@ -419,7 +419,8 @@ public class CompletionFieldMapper extends FieldMapper implements ArrayValueMapp
private void checkCompletionContextsLimit(BuilderContext context) {
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) + "]. " +
"The maximum allowed number of completion contexts in a mapping will be limited to " +
"[" + COMPLETION_CONTEXTS_LIMIT + "] starting in version [8.0].");

View File

@ -208,7 +208,8 @@ public class DynamicTemplate implements ToXContentObject {
if (indexVersionCreated.onOrAfter(Version.V_6_0_0_alpha1)) {
throw e;
} else {
deprecationLogger.deprecated("match_mapping_type [" + matchMappingType + "] is invalid and will be ignored: "
deprecationLogger.deprecatedAndMaybeLog("invalid_mapping_type",
"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
// null indicates that the template should be ignored

View File

@ -185,7 +185,8 @@ public class FieldNamesFieldMapper extends MetadataFieldMapper {
if (isEnabled() == false) {
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");
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",
fieldName, CONTENT_TYPE);
}
DEPRECATION_LOGGER.deprecated("Field parameter [{}] is deprecated and will be removed in a future version.",
fieldName);
DEPRECATION_LOGGER.deprecatedAndMaybeLog("geo_mapper_field_parameter",
"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)) {
throw new IllegalArgumentException(DEFAULT_MAPPING_ERROR_MESSAGE);
} 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);
results.put(DEFAULT_MAPPING, defaultMapper);
@ -785,7 +785,8 @@ public class MapperService extends AbstractIndexComponent implements Closeable {
*/
public MappedFieldType unmappedFieldType(String type) {
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";
}
MappedFieldType fieldType = unmappedFieldTypes.get(type);

View File

@ -197,7 +197,8 @@ public class ObjectMapper extends Mapper implements Cloneable {
}
return true;
} 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 false;

View File

@ -168,7 +168,7 @@ public class RandomScoreFunctionBuilder extends ScoreFunctionBuilder<RandomScore
if (field != null) {
fieldType = context.getMapperService().fieldType(field);
} 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");
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, " +
"please use another model.");
} 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 + "].");
model = BASIC_MODELS.get(replacement);
assert model != null;
@ -174,7 +174,7 @@ final class SimilarityProviders {
throw new IllegalArgumentException("After effect [" + afterEffect +
"] isn't supported anymore, please use another effect.");
} 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 + "].");
effect = AFTER_EFFECTS.get(replacement);
assert effect != null;
@ -264,7 +264,8 @@ final class SimilarityProviders {
if (version.onOrAfter(Version.V_7_0_0)) {
throw new IllegalArgumentException("Unknown settings for similarity of type [" + type + "]: " + unknownSettings);
} 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 {
final ClassicSimilarity similarity = SimilarityProviders.createClassicSimilarity(Settings.EMPTY, version);
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 "
+ "instead.");
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] "
+ "similarity or build a custom [scripted] similarity instead.");
} 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 "
+ "instead.");
return SimilarityProviders.createClassicSimilarity(settings, version);
@ -154,7 +156,8 @@ public final class SimilarityService extends AbstractIndexComponent {
defaultSimilarity = (providers.get("default") != null) ? providers.get("default").get()
: providers.get(SimilarityService.DEFAULT_SIMILARITY).get();
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)) {
throw new IllegalArgumentException(message);
} 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
public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
deprecationLogger.deprecated(deprecationMessage);
deprecationLogger.deprecatedAndMaybeLog("deprecated_route", deprecationMessage);
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);
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) {
throw new IllegalArgumentException("Types cannot be provided in get mapping requests, unless" +
" 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);
}
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")));
} else {
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]");
}
}
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);
request.applyContentParser(resizeRequest::fromXContent);

View File

@ -96,7 +96,7 @@ public class RestNodesAction extends AbstractCatAction {
final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
clusterStateRequest.clear().nodes(true);
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.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));

View File

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

View File

@ -219,9 +219,9 @@ public final class ScriptMetadata implements Metadata.Custom, Writeable, ToXCont
if (source.getSource().isEmpty()) {
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 {
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 (ignoreEmpty || 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 {
deprecationLogger.deprecated("empty scripts should no longer be used");
deprecationLogger.deprecatedAndMaybeLog("empty_scripts", "empty scripts should no longer be used");
}
} else {
throw new IllegalArgumentException("must specify source for stored script");
@ -155,9 +155,9 @@ public class StoredScriptSource extends AbstractDiffable<StoredScriptSource> imp
} else if (source.isEmpty()) {
if (ignoreEmpty || 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 {
deprecationLogger.deprecated("empty scripts should no longer be used");
deprecationLogger.deprecatedAndMaybeLog("empty_scripts", "empty scripts should no longer be used");
}
} else {
throw new IllegalArgumentException("source cannot be empty");
@ -257,7 +257,7 @@ public class StoredScriptSource extends AbstractDiffable<StoredScriptSource> imp
token = parser.nextToken();
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());
}

View File

@ -574,7 +574,8 @@ public abstract class InternalOrder extends BucketOrder {
}
// _term and _time order deprecated in 6.0; replaced by _key
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) {
case "_term":

View File

@ -387,7 +387,8 @@ public class SignificantTermsAggregatorFactory extends ValuesSourceAggregatorFac
if ("global_ordinals".equals(value)) {
return GLOBAL_ORDINALS;
} 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;
} else if ("map".equals(value)) {
return MAP;

View File

@ -301,7 +301,8 @@ public class MovAvgPipelineAggregationBuilder extends AbstractPipelineAggregatio
Integer predict = 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) {
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));
}
} 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");
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {

View File

@ -87,7 +87,8 @@ public final class FetchDocValuesPhase implements FetchSubPhase {
.filter(USE_DEFAULT_FORMAT::equals)
.findAny()
.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.");
}

View File

@ -263,7 +263,8 @@ public class SliceBuilder implements Writeable, ToXContentObject {
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");
}
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;
} else if (IdFieldMapper.NAME.equals(field)) {
useTermQuery = true;

View File

@ -693,14 +693,16 @@ public class FieldSortBuilder extends SortBuilder<FieldSortBuilder> {
static {
PARSER.declareField(FieldSortBuilder::missing, XContentParser::objectText, MISSING, ValueType.VALUE);
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);
}, NESTED_PATH_FIELD);
PARSER.declareString(FieldSortBuilder::unmappedType , UNMAPPED_TYPE);
PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)) , ORDER_FIELD);
PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORT_MODE);
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);
}, NESTED_FILTER_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;
} else if (token == XContentParser.Token.START_OBJECT) {
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);
} else if (NESTED_FIELD.match(currentName, parser.getDeprecationHandler())) {
nestedSort = NestedSortBuilder.fromXContent(parser);
@ -521,7 +522,8 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
} else if (SORTMODE_FIELD.match(currentName, parser.getDeprecationHandler())) {
sortMode = SortMode.fromString(parser.text());
} 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();
} else if (IGNORE_UNMAPPED.match(currentName, parser.getDeprecationHandler())) {
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.sortMode(SortMode.fromString(v)), SORTMODE_FIELD);
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);
}, NESTED_PATH_FIELD);
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);
}, NESTED_FILTER_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) {
publishAddressString = hostString + '/' + publishAddress.toString();
} else {
deprecationLogger.deprecated(
deprecationLogger.deprecatedAndMaybeLog("cname_in_publish_address",
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. "
+ "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
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;
}
@Override
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;
}
}

View File

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

View File

@ -326,7 +326,7 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override
public TokenStream create(TokenStream tokenStream) {
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;
}
@ -354,7 +354,7 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override
public TokenStream create(TokenStream tokenStream) {
deprecationLogger.deprecated("Using deprecated token filter [unused]");
deprecationLogger.deprecatedAndMaybeLog("unused_token_filter", "Using deprecated token filter [unused]");
return tokenStream;
}
}
@ -367,7 +367,8 @@ public class AnalysisRegistryTests extends ESTestCase {
@Override
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;
}

View File

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

View File

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

View File

@ -329,7 +329,8 @@ public class XPackPlugin extends XPackClientPlugin implements ExtensiblePlugin,
if (Files.exists(config) == false) {
Path legacyConfig = env.configFile().resolve("x-pack").resolve(name);
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());
return legacyConfig;
}

View File

@ -348,7 +348,7 @@ public class DatafeedUpdate implements Writeable, ToXContentObject {
DatafeedConfig.Builder builder = new DatafeedConfig.Builder(datafeedConfig);
if (jobId != null) {
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);
}

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
final SSLConfigurationSettings configurationSettings = SSLConfigurationSettings.withPrefix(prefix + ".");
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 " +
"[" + configurationSettings.x509KeyPair.keystorePath.getKey() + "], or both [" +
configurationSettings.x509KeyPair.keyPath.getKey() + "] and [" +
@ -554,7 +554,8 @@ public class SSLService {
.sorted()
.collect(Collectors.toList());
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 : [" +
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.TRANSFORMS.getPreferredName(), invalidTransforms);
builder.endObject();
deprecationLogger.deprecated(INVALID_TRANSFORMS_DEPRECATION_WARNING, invalidTransforms.size());
deprecationLogger.deprecatedAndMaybeLog(
"invalid_transforms",
INVALID_TRANSFORMS_DEPRECATION_WARNING,
invalidTransforms.size()
);
}
builder.endObject();

View File

@ -246,7 +246,8 @@ public class JobManager {
Job job = request.getJobBuilder().build(new Date());
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

View File

@ -132,7 +132,8 @@ public class TransportPutRollupJobAction extends TransportMasterNodeAction<PutRo
String timeZone = request.getConfig().getGroupConfig().getDateHistogram().getTimeZone();
String modernTZ = DateUtils.DEPRECATED_LONG_TIMEZONES.get(timeZone);
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.");
}
}

View File

@ -630,21 +630,23 @@ public class ApiKeyService {
@Override
public void usedDeprecatedName(String parserName, Supplier<XContentLocation> location, String usedName, String modernName) {
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);
}
@Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName, String replacedWith) {
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);
}
@Override
public void usedDeprecatedField(String parserName, Supplier<XContentLocation> location, String usedName) {
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",
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) {
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.",
String.join("; ", missingOrderRealmSettingKeys)
);
@ -359,7 +359,8 @@ public class Realms implements Iterable<Realm> {
.sorted()
.collect(Collectors.toList());
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.",
String.join("; ", duplicatedRealmOrderSettingKeys));
}

View File

@ -523,9 +523,10 @@ class ActiveDirectorySessionFactory extends PoolingSessionFactory {
super(config, timeout, ignoreReferralErrors, logger, groupsResolver, metadataResolver, domainDN,
ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING, UPN_USER_FILTER, threadPool);
if (userSearchFilter.contains("{0}")) {
new DeprecationLogger(logger).deprecated("The use of the account name variable {0} in the setting ["
+ RealmSettings.getFullSettingKey(config, ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING) +
"] has been deprecated and will be removed in a future version!");
new DeprecationLogger(logger).deprecatedAndMaybeLog("ldap_settings",
"The use of the account name variable {0} in the setting ["
+ 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));
}
} else if (hostnameVerificationExists) {
new DeprecationLogger(logger).deprecated("the setting [{}] has been deprecated and " +
"will be removed in a future version. use [{}] instead",
RealmSettings.getFullSettingKey(config, SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING),
RealmSettings.getFullSettingKey(config, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM));
final String fullSettingKey = RealmSettings.getFullSettingKey(config, SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING);
final String deprecationKey = "deprecated_setting_" + fullSettingKey.replace('.', '_');
new DeprecationLogger(logger).deprecatedAndMaybeLog(
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)) {
options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true));
}

View File

@ -206,7 +206,7 @@ public final class DeprecationRoleDescriptorConsumer implements Consumer<Collect
if (false == inferiorIndexNames.isEmpty()) {
final String logMessage = String.format(Locale.ROOT, ROLE_PERMISSION_DEPRECATION_STANZA, roleDescriptor.getName(),
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) {
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 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.");

View File

@ -60,7 +60,8 @@ public class RestWatcherStatsAction extends WatcherRestHandler {
}
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");
}