Remove the single argument Environment constructor (#27235)

Only tests should use the single argument Environment constructor.  To
enforce this the single arg Environment constructor has been replaced with
a test framework factory method.

Production code (beyond initial Bootstrap) should always use the same
Environment object that Node.getEnvironment() returns.  This Environment
is also available via dependency injection.
This commit is contained in:
David Roberts 2017-11-04 13:25:09 +00:00 committed by GitHub
parent 964016e228
commit 749c3ec716
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 129 additions and 72 deletions

View File

@ -85,10 +85,6 @@ public class Environment {
/** Path to the temporary file directory used by the JDK */
private final Path tmpFile = PathUtils.get(System.getProperty("java.io.tmpdir"));
public Environment(Settings settings) {
this(settings, null);
}
public Environment(final Settings settings, final Path configPath) {
final Path homeFile;
if (PATH_HOME_SETTING.exists(settings)) {

View File

@ -28,6 +28,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AbstractCharFilterFactory;
import org.elasticsearch.index.analysis.AbstractTokenFilterFactory;
@ -74,7 +75,7 @@ public class TransportAnalyzeActionTests extends ESTestCase {
.put("index.analysis.normalizer.my_normalizer.type", "custom")
.putList("index.analysis.normalizer.my_normalizer.filter", "lowercase").build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", indexSettings);
environment = new Environment(settings);
environment = TestEnvironment.newEnvironment(settings);
AnalysisPlugin plugin = new AnalysisPlugin() {
class MockFactory extends AbstractTokenFilterFactory {
MockFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) {

View File

@ -22,7 +22,6 @@ package org.elasticsearch.common.settings;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@ -35,6 +34,7 @@ import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.common.io.PathUtilsForTesting;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.junit.After;
import org.junit.Before;
@ -70,7 +70,7 @@ public abstract class KeyStoreCommandTestCase extends CommandTestCase {
PathUtilsForTesting.installMock(fs); // restored by restoreFileSystem in ESTestCase
Path home = fs.getPath("/", "test-home");
Files.createDirectories(home.resolve("config"));
return new Environment(Settings.builder().put("path.home", home).build());
return TestEnvironment.newEnvironment(Settings.builder().put("path.home", home).build());
}
KeyStoreWrapper createKeystore(String password, String... settings) throws Exception {

View File

@ -43,7 +43,7 @@ public class EnvironmentTests extends ESTestCase {
.put(settings)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath())
.putList(Environment.PATH_DATA_SETTING.getKey(), tmpPaths()).build();
return new Environment(build);
return new Environment(build, null);
}
public void testRepositoryResolution() throws IOException {
@ -76,21 +76,21 @@ public class EnvironmentTests extends ESTestCase {
public void testPathDataWhenNotSet() {
final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings);
final Environment environment = new Environment(settings, null);
assertThat(environment.dataFiles(), equalTo(new Path[]{pathHome.resolve("data")}));
}
public void testPathDataNotSetInEnvironmentIfNotSet() {
final Settings settings = Settings.builder().put("path.home", createTempDir().toAbsolutePath()).build();
assertFalse(Environment.PATH_DATA_SETTING.exists(settings));
final Environment environment = new Environment(settings);
final Environment environment = new Environment(settings, null);
assertFalse(Environment.PATH_DATA_SETTING.exists(environment.settings()));
}
public void testPathLogsWhenNotSet() {
final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings);
final Environment environment = new Environment(settings, null);
assertThat(environment.logsFile(), equalTo(pathHome.resolve("logs")));
}
@ -111,7 +111,7 @@ public class EnvironmentTests extends ESTestCase {
public void testConfigPathWhenNotSet() {
final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings);
final Environment environment = new Environment(settings, null);
assertThat(environment.configFile(), equalTo(pathHome.resolve("config")));
}

View File

@ -80,12 +80,12 @@ public class NodeEnvironmentTests extends ESTestCase {
// Reuse the same location and attempt to lock again
IllegalStateException ex =
expectThrows(IllegalStateException.class, () -> new NodeEnvironment(settings, new Environment(settings)));
expectThrows(IllegalStateException.class, () -> new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings)));
assertThat(ex.getMessage(), containsString("failed to obtain node lock"));
// Close the environment that holds the lock and make sure we can get the lock after release
env.close();
env = new NodeEnvironment(settings, new Environment(settings));
env = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
assertThat(env.nodeDataPaths(), arrayWithSize(dataPaths.size()));
for (int i = 0; i < dataPaths.size(); i++) {
@ -120,7 +120,7 @@ public class NodeEnvironmentTests extends ESTestCase {
final Settings settings = buildEnvSettings(Settings.builder().put("node.max_local_storage_nodes", 2).build());
final NodeEnvironment first = newNodeEnvironment(settings);
List<String> dataPaths = Environment.PATH_DATA_SETTING.get(settings);
NodeEnvironment second = new NodeEnvironment(settings, new Environment(settings));
NodeEnvironment second = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
assertEquals(first.nodeDataPaths().length, dataPaths.size());
assertEquals(second.nodeDataPaths().length, dataPaths.size());
for (int i = 0; i < dataPaths.size(); i++) {
@ -477,7 +477,7 @@ public class NodeEnvironmentTests extends ESTestCase {
@Override
public NodeEnvironment newNodeEnvironment(Settings settings) throws IOException {
Settings build = buildEnvSettings(settings);
return new NodeEnvironment(build, new Environment(build));
return new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
}
public Settings buildEnvSettings(Settings settings) {
@ -492,7 +492,7 @@ public class NodeEnvironmentTests extends ESTestCase {
.put(settings)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
.putList(Environment.PATH_DATA_SETTING.getKey(), dataPaths).build();
return new NodeEnvironment(build, new Environment(build));
return new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
}
public NodeEnvironment newNodeEnvironment(String[] dataPaths, String sharedDataPath, Settings settings) throws IOException {
@ -501,6 +501,6 @@ public class NodeEnvironmentTests extends ESTestCase {
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), sharedDataPath)
.putList(Environment.PATH_DATA_SETTING.getKey(), dataPaths).build();
return new NodeEnvironment(build, new Environment(build));
return new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
}
}

View File

@ -42,6 +42,7 @@ import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.analysis.AnalysisRegistry;
import org.elasticsearch.index.cache.query.DisabledQueryCache;
import org.elasticsearch.index.cache.query.IndexQueryCache;
@ -118,7 +119,7 @@ public class IndexModuleTests extends ESTestCase {
indicesQueryCache = new IndicesQueryCache(settings);
indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
index = indexSettings.getIndex();
environment = new Environment(settings);
environment = TestEnvironment.newEnvironment(settings);
emptyAnalysisRegistry = new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(),
emptyMap(), emptyMap(), emptyMap());
threadPool = new TestThreadPool("test");

View File

@ -30,6 +30,7 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.indices.analysis.AnalysisModule;
import org.elasticsearch.indices.analysis.AnalysisModule.AnalysisProvider;
@ -56,8 +57,8 @@ public class AnalysisRegistryTests extends ESTestCase {
}
private static AnalysisRegistry emptyAnalysisRegistry(Settings settings) {
return new AnalysisRegistry(new Environment(settings), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(),
emptyMap(), emptyMap());
return new AnalysisRegistry(TestEnvironment.newEnvironment(settings), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(),
emptyMap(), emptyMap(), emptyMap());
}
private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder settings) {
@ -157,8 +158,8 @@ public class AnalysisRegistryTests extends ESTestCase {
return singletonMap("mock", MockFactory::new);
}
};
IndexAnalyzers indexAnalyzers = new AnalysisModule(new Environment(settings), singletonList(plugin)).getAnalysisRegistry()
.build(idxSettings);
IndexAnalyzers indexAnalyzers = new AnalysisModule(TestEnvironment.newEnvironment(settings),
singletonList(plugin)).getAnalysisRegistry().build(idxSettings);
// This shouldn't contain English stopwords
try (NamedAnalyzer custom_analyser = indexAnalyzers.get("custom_analyzer_with_camel_case")) {

View File

@ -22,6 +22,7 @@ package org.elasticsearch.index.analysis;
import org.apache.lucene.analysis.CharArraySet;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import java.io.BufferedWriter;
@ -61,7 +62,7 @@ public class AnalysisTests extends ESTestCase {
Settings nodeSettings = Settings.builder()
.put("foo.bar_path", tempDir.resolve("foo.dict"))
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir).build();
Environment env = new Environment(nodeSettings);
Environment env = TestEnvironment.newEnvironment(nodeSettings);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class,
() -> Analysis.getWordList(env, nodeSettings, "foo.bar"));
assertEquals("IOException while reading foo.bar_path: " + tempDir.resolve("foo.dict").toString(), ex.getMessage());
@ -80,7 +81,7 @@ public class AnalysisTests extends ESTestCase {
writer.write(new byte[]{(byte) 0xff, 0x00, 0x00}); // some invalid UTF-8
writer.write('\n');
}
Environment env = new Environment(nodeSettings);
Environment env = TestEnvironment.newEnvironment(nodeSettings);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class,
() -> Analysis.getWordList(env, nodeSettings, "foo.bar"));
assertEquals("Unsupported character encoding detected while reading foo.bar_path: " + tempDir.resolve("foo.dict").toString()
@ -101,7 +102,7 @@ public class AnalysisTests extends ESTestCase {
writer.write("world");
writer.write('\n');
}
Environment env = new Environment(nodeSettings);
Environment env = TestEnvironment.newEnvironment(nodeSettings);
List<String> wordList = Analysis.getWordList(env, nodeSettings, "foo.bar");
assertEquals(Arrays.asList("hello", "world"), wordList);

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.NodeEnvironment.NodePath;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
@ -34,7 +35,6 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.Files;
@ -178,7 +178,7 @@ public class NewPathForShardTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), path)
.putList(Environment.PATH_DATA_SETTING.getKey(), paths).build();
NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings));
NodeEnvironment nodeEnv = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
// Make sure all our mocking above actually worked:
NodePath[] nodePaths = nodeEnv.nodePaths();
@ -233,7 +233,7 @@ public class NewPathForShardTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), path)
.putList(Environment.PATH_DATA_SETTING.getKey(), paths).build();
NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings));
NodeEnvironment nodeEnv = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
// Make sure all our mocking above actually worked:
NodePath[] nodePaths = nodeEnv.nodePaths();
@ -290,7 +290,7 @@ public class NewPathForShardTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), path)
.putList(Environment.PATH_DATA_SETTING.getKey(), paths).build();
NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings));
NodeEnvironment nodeEnv = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
aFileStore.usableSpace = 100000;
bFileStore.usableSpace = 1000;
@ -315,7 +315,7 @@ public class NewPathForShardTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), path)
.putList(Environment.PATH_DATA_SETTING.getKey(), paths).build();
NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings));
NodeEnvironment nodeEnv = new NodeEnvironment(settings, TestEnvironment.newEnvironment(settings));
// Make sure all our mocking above actually worked:
NodePath[] nodePaths = nodeEnv.nodePaths();

View File

@ -34,6 +34,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.Analysis;
import org.elasticsearch.index.analysis.AnalysisRegistry;
@ -91,7 +92,7 @@ public class AnalysisModuleTests extends ESTestCase {
public AnalysisRegistry getNewRegistry(Settings settings) {
try {
return new AnalysisModule(new Environment(settings), singletonList(new AnalysisPlugin() {
return new AnalysisModule(TestEnvironment.newEnvironment(settings), singletonList(new AnalysisPlugin() {
@Override
public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() {
return singletonMap("myfilter", MyFilterTokenFilterFactory::new);
@ -162,7 +163,8 @@ public class AnalysisModuleTests extends ESTestCase {
indexAnalyzers.get("thai").analyzer().getVersion());
assertThat(indexAnalyzers.get("custom7").analyzer(), is(instanceOf(StandardAnalyzer.class)));
assertEquals(org.apache.lucene.util.Version.fromBits(3,6,0), indexAnalyzers.get("custom7").analyzer().getVersion());
assertEquals(org.apache.lucene.util.Version.fromBits(3,6,0),
indexAnalyzers.get("custom7").analyzer().getVersion());
}
private void testSimpleConfiguration(Settings settings) throws IOException {
@ -194,7 +196,7 @@ public class AnalysisModuleTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
Environment env = new Environment(settings);
Environment env = TestEnvironment.newEnvironment(settings);
String[] words = new String[]{"donau", "dampf", "schiff", "spargel", "creme", "suppe"};
Path wordListFile = generateWordList(words);
@ -241,7 +243,8 @@ public class AnalysisModuleTests extends ESTestCase {
boolean noVersionSupportsMultiTerm = randomBoolean();
boolean luceneVersionSupportsMultiTerm = randomBoolean();
boolean elasticsearchVersionSupportsMultiTerm = randomBoolean();
AnalysisRegistry registry = new AnalysisModule(new Environment(emptyNodeSettings), singletonList(new AnalysisPlugin() {
AnalysisRegistry registry = new AnalysisModule(TestEnvironment.newEnvironment(emptyNodeSettings),
singletonList(new AnalysisPlugin() {
@Override
public List<PreConfiguredCharFilter> getPreConfiguredCharFilters() {
return Arrays.asList(
@ -285,7 +288,8 @@ public class AnalysisModuleTests extends ESTestCase {
boolean noVersionSupportsMultiTerm = randomBoolean();
boolean luceneVersionSupportsMultiTerm = randomBoolean();
boolean elasticsearchVersionSupportsMultiTerm = randomBoolean();
AnalysisRegistry registry = new AnalysisModule(new Environment(emptyNodeSettings), singletonList(new AnalysisPlugin() {
AnalysisRegistry registry = new AnalysisModule(TestEnvironment.newEnvironment(emptyNodeSettings),
singletonList(new AnalysisPlugin() {
@Override
public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() {
return Arrays.asList(
@ -359,7 +363,8 @@ public class AnalysisModuleTests extends ESTestCase {
read = false;
}
}
AnalysisRegistry registry = new AnalysisModule(new Environment(emptyNodeSettings), singletonList(new AnalysisPlugin() {
AnalysisRegistry registry = new AnalysisModule(TestEnvironment.newEnvironment(emptyNodeSettings),
singletonList(new AnalysisPlugin() {
@Override
public List<PreConfiguredTokenizer> getPreConfiguredTokenizers() {
return Arrays.asList(
@ -402,7 +407,7 @@ public class AnalysisModuleTests extends ESTestCase {
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.build();
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
InputStream aff = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.aff");
InputStream dic = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.dic");
Dictionary dictionary;

View File

@ -72,6 +72,7 @@ import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.shard.IndexEventListener;
@ -130,7 +131,7 @@ public class ClusterStateChanges extends AbstractComponent {
ActionFilters actionFilters = new ActionFilters(Collections.emptySet());
IndexNameExpressionResolver indexNameExpressionResolver = new IndexNameExpressionResolver(settings);
DestructiveOperations destructiveOperations = new DestructiveOperations(settings, clusterSettings);
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
Transport transport = null; // it's not used
// mocks

View File

@ -24,6 +24,7 @@ import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.test.ESTestCase;
@ -59,7 +60,7 @@ public class PluginsServiceTests extends ESTestCase {
public static class FilterablePlugin extends Plugin implements ScriptPlugin {}
static PluginsService newPluginsService(Settings settings, Class<? extends Plugin>... classpathPlugins) {
return new PluginsService(settings, null, null, new Environment(settings).pluginsFile(), Arrays.asList(classpathPlugins));
return new PluginsService(settings, null, null, TestEnvironment.newEnvironment(settings).pluginsFile(), Arrays.asList(classpathPlugins));
}
public void testAdditionalSettings() {

View File

@ -37,6 +37,7 @@ import org.elasticsearch.common.io.PathUtilsForTesting;
import org.elasticsearch.common.settings.KeyStoreWrapper;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.PosixPermissionsResetter;
import org.junit.After;
@ -176,7 +177,7 @@ public class InstallPluginCommandTests extends ESTestCase {
Settings settings = Settings.builder()
.put("path.home", home)
.build();
return Tuple.tuple(home, new Environment(settings));
return Tuple.tuple(home, TestEnvironment.newEnvironment(settings));
}
static Path createPluginDir(Function<String, Path> temp) throws IOException {
@ -236,7 +237,7 @@ public class InstallPluginCommandTests extends ESTestCase {
}
MockTerminal installPlugin(String pluginUrl, Path home, InstallPluginCommand command) throws Exception {
Environment env = new Environment(Settings.builder().put("path.home", home).build());
Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", home).build());
MockTerminal terminal = new MockTerminal();
command.execute(terminal, pluginUrl, true, env);
return terminal;

View File

@ -37,6 +37,7 @@ import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
@ -54,7 +55,7 @@ public class ListPluginsCommandTests extends ESTestCase {
Settings settings = Settings.builder()
.put("path.home", home)
.build();
env = new Environment(settings);
env = TestEnvironment.newEnvironment(settings);
}
static MockTerminal listPlugins(Path home) throws Exception {

View File

@ -26,6 +26,7 @@ import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
@ -73,11 +74,11 @@ public class RemovePluginCommandTests extends ESTestCase {
Settings settings = Settings.builder()
.put("path.home", home)
.build();
env = new Environment(settings);
env = TestEnvironment.newEnvironment(settings);
}
static MockTerminal removePlugin(String name, Path home, boolean purge) throws Exception {
Environment env = new Environment(Settings.builder().put("path.home", home).build());
Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", home).build());
MockTerminal terminal = new MockTerminal();
new MockRemovePluginCommand(env).execute(terminal, env, name, purge);
return terminal;

View File

@ -26,6 +26,7 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.IndexAnalyzers;
import org.elasticsearch.index.analysis.MyFilterTokenFilterFactory;
@ -87,7 +88,7 @@ public class CompoundAnalysisTests extends ESTestCase {
private AnalysisModule createAnalysisModule(Settings settings) throws IOException {
CommonAnalysisPlugin commonAnalysisPlugin = new CommonAnalysisPlugin();
return new AnalysisModule(new Environment(settings), Arrays.asList(commonAnalysisPlugin, new AnalysisPlugin() {
return new AnalysisModule(TestEnvironment.newEnvironment(settings), Arrays.asList(commonAnalysisPlugin, new AnalysisPlugin() {
@Override
public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() {
return singletonMap("myfilter", MyFilterTokenFilterFactory::new);

View File

@ -23,6 +23,7 @@ import org.elasticsearch.cluster.metadata.RepositoryMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.repositories.RepositoryException;
import org.elasticsearch.test.ESTestCase;
@ -40,7 +41,8 @@ public class URLRepositoryTests extends ESTestCase {
.put(URLRepository.REPOSITORIES_URL_SETTING.getKey(), repoPath)
.build();
RepositoryMetaData repositoryMetaData = new RepositoryMetaData("url", URLRepository.TYPE, baseSettings);
new URLRepository(repositoryMetaData, new Environment(baseSettings), new NamedXContentRegistry(Collections.emptyList()));
new URLRepository(repositoryMetaData, TestEnvironment.newEnvironment(baseSettings),
new NamedXContentRegistry(Collections.emptyList()));
}
public void testIfNotWhiteListedMustSetRepoURL() throws IOException {
@ -51,7 +53,8 @@ public class URLRepositoryTests extends ESTestCase {
.build();
RepositoryMetaData repositoryMetaData = new RepositoryMetaData("url", URLRepository.TYPE, baseSettings);
try {
new URLRepository(repositoryMetaData, new Environment(baseSettings), new NamedXContentRegistry(Collections.emptyList()));
new URLRepository(repositoryMetaData, TestEnvironment.newEnvironment(baseSettings),
new NamedXContentRegistry(Collections.emptyList()));
fail("RepositoryException should have been thrown.");
} catch (RepositoryException e) {
String msg = "[url] file url [" + repoPath
@ -71,7 +74,8 @@ public class URLRepositoryTests extends ESTestCase {
.build();
RepositoryMetaData repositoryMetaData = new RepositoryMetaData("url", URLRepository.TYPE, baseSettings);
try {
new URLRepository(repositoryMetaData, new Environment(baseSettings), new NamedXContentRegistry(Collections.emptyList()));
new URLRepository(repositoryMetaData, TestEnvironment.newEnvironment(baseSettings),
new NamedXContentRegistry(Collections.emptyList()));
fail("RepositoryException should have been thrown.");
} catch (RepositoryException e) {
assertEquals("[url] unsupported url protocol [file] from URL [" + repoPath +"]", e.getMessage());

View File

@ -28,6 +28,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.pl.PolishStemTokenFilterFactory;
import org.elasticsearch.indices.analysis.AnalysisFactoryTestCase;
@ -59,7 +60,7 @@ public class AnalysisPolishFactoryTests extends AnalysisFactoryTestCase {
.put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
IndexMetaData metaData = IndexMetaData.builder(IndexMetaData.INDEX_UUID_NA_VALUE).settings(settings).build();
IndexSettings indexSettings = new IndexSettings(metaData, Settings.EMPTY);
testThreadSafety(new PolishStemTokenFilterFactory(indexSettings, environment, "stempelpolishstem", settings));

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.transport.MockTransportService;
@ -126,7 +127,7 @@ public class FileBasedUnicastHostsProviderTests extends ESTestCase {
final Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.build();
final Environment environment = new Environment(settings);
final Environment environment = TestEnvironment.newEnvironment(settings);
final FileBasedUnicastHostsProvider provider = new FileBasedUnicastHostsProvider(environment, transportService, executorService);
final List<DiscoveryNode> nodes = provider.buildDynamicNodes();
assertEquals(0, nodes.size());

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
@ -42,8 +43,8 @@ public class AzureRepositorySettingsTests extends ESTestCase {
.putList(Environment.PATH_DATA_SETTING.getKey(), tmpPaths())
.put(settings)
.build();
return new AzureRepository(new RepositoryMetaData("foo", "azure", internalSettings), new Environment(internalSettings),
NamedXContentRegistry.EMPTY, null);
return new AzureRepository(new RepositoryMetaData("foo", "azure", internalSettings),
TestEnvironment.newEnvironment(internalSettings), NamedXContentRegistry.EMPTY, null);
}

View File

@ -21,19 +21,16 @@ package org.elasticsearch.repositories.gcs;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.repositories.gcs.GoogleCloudStorageService.InternalGoogleCloudStorageService;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.Matchers.containsString;
public class GoogleCloudStorageServiceTests extends ESTestCase {
private InputStream getDummyCredentialStream() throws IOException {
@ -41,7 +38,7 @@ public class GoogleCloudStorageServiceTests extends ESTestCase {
}
public void testDefaultCredential() throws Exception {
Environment env = new Environment(Settings.builder().put("path.home", createTempDir()).build());
Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
GoogleCredential cred = GoogleCredential.fromStream(getDummyCredentialStream());
InternalGoogleCloudStorageService service = new InternalGoogleCloudStorageService(env, Collections.emptyMap()) {
@Override
@ -55,7 +52,7 @@ public class GoogleCloudStorageServiceTests extends ESTestCase {
public void testClientCredential() throws Exception {
GoogleCredential cred = GoogleCredential.fromStream(getDummyCredentialStream());
Map<String, GoogleCredential> credentials = Collections.singletonMap("clientname", cred);
Environment env = new Environment(Settings.builder().put("path.home", createTempDir()).build());
Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
InternalGoogleCloudStorageService service = new InternalGoogleCloudStorageService(env, credentials);
assertSame(cred, service.getCredential("clientname"));
}

View File

@ -24,6 +24,7 @@ import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import java.io.FilePermission;
@ -54,7 +55,7 @@ public class EvilSecurityTests extends ESTestCase {
Permissions permissions;
try {
System.setProperty("java.io.tmpdir", fakeTmpDir.toString());
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
permissions = Security.createPermissions(environment);
} finally {
System.setProperty("java.io.tmpdir", realTmpDir);
@ -156,7 +157,7 @@ public class EvilSecurityTests extends ESTestCase {
.putList(Environment.PATH_DATA_SETTING.getKey(), data.toString(), duplicate.toString())
.build();
final Environment environment = new Environment(settings);
final Environment environment = TestEnvironment.newEnvironment(settings);
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> Security.createPermissions(environment));
assertThat(e, hasToString(containsString("path [" + duplicate.toRealPath() + "] is duplicated by [" + duplicate + "]")));
}

View File

@ -52,7 +52,7 @@ public class NodeEnvironmentEvilTests extends ESTestCase {
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
.putList(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build();
IOException ioException = expectThrows(IOException.class, () -> {
new NodeEnvironment(build, new Environment(build));
new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
});
assertTrue(ioException.getMessage(), ioException.getMessage().startsWith(path.toString()));
}
@ -72,7 +72,7 @@ public class NodeEnvironmentEvilTests extends ESTestCase {
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
.putList(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build();
IOException ioException = expectThrows(IOException.class, () -> {
new NodeEnvironment(build, new Environment(build));
new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
});
assertTrue(ioException.getMessage(), ioException.getMessage().startsWith("failed to test writes in data directory"));
}
@ -97,7 +97,7 @@ public class NodeEnvironmentEvilTests extends ESTestCase {
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
.putList(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build();
IOException ioException = expectThrows(IOException.class, () -> {
new NodeEnvironment(build, new Environment(build));
new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
});
assertTrue(ioException.getMessage(), ioException.getMessage().startsWith("failed to test writes in data directory"));
}

View File

@ -24,6 +24,7 @@ import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.plugins.PluginTestUtil;
import org.elasticsearch.plugins.Platforms;
@ -72,7 +73,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
settingsBuilder.put(Environment.PATH_HOME_SETTING.getKey(), esHome.toString());
Settings settings = settingsBuilder.build();
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
// This plugin will NOT have a controller daemon
Path plugin = environment.pluginsFile().resolve("a_plugin");
@ -108,7 +109,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
settingsBuilder.put(Environment.PATH_HOME_SETTING.getKey(), esHome.toString());
Settings settings = settingsBuilder.build();
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
// this plugin will have a controller daemon
Path plugin = environment.pluginsFile().resolve("test_plugin");
@ -169,7 +170,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
settingsBuilder.put(Environment.PATH_HOME_SETTING.getKey(), esHome.toString());
Settings settings = settingsBuilder.build();
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
Path plugin = environment.pluginsFile().resolve("test_plugin");
Files.createDirectories(plugin);
@ -198,7 +199,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
final Path esHome = createTempDir().resolve("home");
final Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), esHome.toString()).build();
final Environment environment = new Environment(settings);
final Environment environment = TestEnvironment.newEnvironment(settings);
Files.createDirectories(environment.pluginsFile());

View File

@ -0,0 +1,37 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.env;
import org.elasticsearch.common.settings.Settings;
/**
* Provides a convenience method for tests to construct an Environment when the config path does not matter.
* This is in the test framework to force people who construct an Environment in production code to think
* about what the config path needs to be set to.
*/
public class TestEnvironment {
private TestEnvironment() {
}
public static Environment newEnvironment(Settings settings) {
return new Environment(settings, null);
}
}

View File

@ -63,6 +63,7 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.IndexAnalyzers;
@ -1048,7 +1049,7 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
).flatMap(Function.identity()).collect(toList()));
IndexScopedSettings indexScopedSettings = settingsModule.getIndexScopedSettings();
idxSettings = IndexSettingsModule.newIndexSettings(index, indexSettings, indexScopedSettings);
AnalysisModule analysisModule = new AnalysisModule(new Environment(nodeSettings), emptyList());
AnalysisModule analysisModule = new AnalysisModule(TestEnvironment.newEnvironment(nodeSettings), emptyList());
IndexAnalyzers indexAnalyzers = analysisModule.getAnalysisRegistry().build(idxSettings);
scriptService = scriptModule.getScriptService();
similarityService = new SimilarityService(idxSettings, null, Collections.emptyMap());

View File

@ -110,6 +110,7 @@ import org.elasticsearch.discovery.zen.ElectMasterService;
import org.elasticsearch.discovery.zen.ZenDiscovery;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.index.IndexService;
@ -1971,7 +1972,7 @@ public abstract class ESIntegTestCase extends ESTestCase {
* Returns path to a random directory that can be used to create a temporary file system repo
*/
public static Path randomRepoPath(Settings settings) {
Environment environment = new Environment(settings);
Environment environment = TestEnvironment.newEnvironment(settings);
Path[] repoFiles = environment.repoFiles();
assert repoFiles.length > 0;
Path path;

View File

@ -77,6 +77,7 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AnalysisRegistry;
@ -811,7 +812,7 @@ public abstract class ESTestCase extends LuceneTestCase {
.put(settings)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath())
.putList(Environment.PATH_DATA_SETTING.getKey(), tmpPaths()).build();
return new NodeEnvironment(build, new Environment(build));
return new NodeEnvironment(build, TestEnvironment.newEnvironment(build));
}
/** Return consistent index settings for the provided index version. */
@ -1205,7 +1206,7 @@ public abstract class ESTestCase extends LuceneTestCase {
*/
public static TestAnalysis createTestAnalysis(IndexSettings indexSettings, Settings nodeSettings,
AnalysisPlugin... analysisPlugins) throws IOException {
Environment env = new Environment(nodeSettings);
Environment env = TestEnvironment.newEnvironment(nodeSettings);
AnalysisModule analysisModule = new AnalysisModule(env, Arrays.asList(analysisPlugins));
AnalysisRegistry analysisRegistry = analysisModule.getAnalysisRegistry();
return new TestAnalysis(analysisRegistry.build(indexSettings),