Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always use deprecateAndMaybeLog for deprecation warnings #55115

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -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.");
}
Expand Down
Expand Up @@ -187,7 +187,8 @@ public UserAgentProcessor create(Map<String, Processor.Factory> factories, Strin
boolean ignoreMissing = readBooleanProperty(TYPE, processorTag, config, "ignore_missing", false);
Object ecsValue = config.remove("ecs");
if (ecsValue != null) {
deprecationLogger.deprecated("setting [ecs] is deprecated as ECS format is the default and only option");
deprecationLogger.deprecatedAndMaybeLog("ingest_useragent_ecs_settings",
"setting [ecs] is deprecated as ECS format is the default and only option");
}

UserAgentParser parser = userAgentParsers.get(regexFilename);
Expand Down
Expand Up @@ -67,7 +67,7 @@ void initialValidation(ReindexRequest request) {
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);
}
}

Expand Down
Expand Up @@ -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...");
}

Expand Down
Expand Up @@ -135,11 +135,13 @@ static AWSCredentials loadCredentials(Settings settings) {
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());
}

Expand Down
Expand Up @@ -111,7 +111,7 @@ public void testDeprecationLogger() throws IOException, UserException {

final int deprecatedIterations = randomIntBetween(0, 256);
for (int i = 0; i < deprecatedIterations; i++) {
deprecationLogger.deprecated("This is a deprecation message");
deprecationLogger.deprecatedAndMaybeLog("key" + i, "This is a deprecation message");
pugnascotia marked this conversation as resolved.
Show resolved Hide resolved
assertWarnings("This is a deprecation message");
}

Expand Down
Expand Up @@ -80,7 +80,7 @@ public String getWriteableName() {

@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();
}
Expand Down
Expand Up @@ -98,7 +98,7 @@ public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client
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 {
Expand Down
Expand Up @@ -182,7 +182,8 @@ public void validateDotIndex(String index, ClusterState state, @Nullable Boolean
.filter(descriptor -> descriptor.matchesIndexPattern(index))
.collect(toList());
if (matchingDescriptors.isEmpty() && (isHidden == null || isHidden == Boolean.FALSE)) {
deprecationLogger.deprecated("index name [{}] starts with a dot '.', in the next major version, index names " +
deprecationLogger.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.
Expand Down
Expand Up @@ -333,7 +333,7 @@ ClusterState addIndexTemplateV2(final ClusterState currentState, final boolean c
.collect(Collectors.joining(",")),
name);
logger.warn(warning);
deprecationLogger.deprecated(warning);
deprecationLogger.deprecatedAndMaybeLog("index_template_pattern_overlap", warning);
}

IndexTemplateV2 finalIndexTemplate = template;
Expand Down Expand Up @@ -558,7 +558,7 @@ static ClusterState innerPutTemplate(final ClusterState currentState, PutRequest
.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" +
Expand Down
Expand Up @@ -28,6 +28,7 @@
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;
Expand Down Expand Up @@ -110,15 +111,8 @@ public DeprecationLogger(Logger parentLogger) {
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<>() {
@Override
protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) {
return size() > 128;
Expand All @@ -135,8 +129,8 @@ protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) {
*/
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);
}

/*
Expand Down Expand Up @@ -234,7 +228,7 @@ void deprecated(final Set<ThreadContext> threadContexts, final String message, f
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);
Expand All @@ -251,12 +245,12 @@ void deprecated(final Set<ThreadContext> threadContexts, final String message, f
}
}

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);
Expand Down Expand Up @@ -360,7 +354,7 @@ static String escapeBackslashesAndQuotes(final String s) {
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.
Expand Down
Expand Up @@ -235,7 +235,8 @@ private static ByteSizeValue parse(final String initialInput, final String norma
} 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)));
Expand Down
Expand Up @@ -53,21 +53,21 @@ private LoggingDeprecationHandler() {
@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);
}
}
Expand Up @@ -51,7 +51,8 @@ public ShingleTokenFilterFactory(IndexSettings indexSettings, Environment enviro
+ " 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 + "]");
}
}
Expand Down
Expand Up @@ -423,7 +423,8 @@ private void checkCompletionContextsLimit(BuilderContext context) {
throw new IllegalArgumentException(
"Limit of completion field contexts [" + COMPLETION_CONTEXTS_LIMIT + "] has been exceeded");
} else {
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].");
Expand Down
Expand Up @@ -183,7 +183,8 @@ public Query termQuery(Object value, QueryShardContext context) {
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);
}
Expand Down
Expand Up @@ -170,8 +170,8 @@ private static void checkPrefixTreeSupport(String fieldName) {
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);
}
}

Expand Down
Expand Up @@ -200,7 +200,8 @@ protected static boolean parseObjectOrDocumentTypeProperties(String fieldName, O
}
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;
Expand Down
Expand Up @@ -163,7 +163,7 @@ protected ScoreFunction doToFunction(QueryShardContext context) {
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);
}
Expand Down
Expand Up @@ -115,7 +115,7 @@ private static BasicModel parseBasicModel(Version indexCreatedVersion, Settings
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;
Expand Down Expand Up @@ -146,7 +146,7 @@ private static AfterEffect parseAfterEffect(Version indexCreatedVersion, Setting
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;
Expand Down Expand Up @@ -236,7 +236,8 @@ static void assertSettingsIsSubsetOf(String type, Version version, Settings sett
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);
}
}
}
Expand Down
Expand Up @@ -124,7 +124,8 @@ public SimilarityService(IndexSettings indexSettings, ScriptService scriptServic
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");
}
}

Expand Down
Expand Up @@ -57,7 +57,7 @@ public DeprecationRestHandler(RestHandler handler, String deprecationMessage, De
*/
@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);
}
Expand Down