Rename environment dir accessors (#121803)

The node environment has many paths. The accessors for these currently
use a "file" suffix, but they are always directories. This commit
renames the accessors to make it clear these paths are directories.
This commit is contained in:
Ryan Ernst 2025-02-05 14:03:28 -08:00 committed by GitHub
parent 1e12b547ca
commit 0cf42f2388
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
128 changed files with 520 additions and 528 deletions

View file

@ -74,7 +74,7 @@ class AddFileKeyStoreCommand extends BaseKeyStoreCommand {
keyStore.setFile(setting, Files.readAllBytes(file)); keyStore.setFile(setting, Files.readAllBytes(file));
} }
keyStore.save(env.configFile(), getKeyStorePassword().getChars()); keyStore.save(env.configDir(), getKeyStorePassword().getChars());
} }
@SuppressForbidden(reason = "file arg for cli") @SuppressForbidden(reason = "file arg for cli")

View file

@ -100,7 +100,7 @@ class AddStringKeyStoreCommand extends BaseKeyStoreCommand {
} }
} }
keyStore.save(env.configFile(), getKeyStorePassword().getChars()); keyStore.save(env.configDir(), getKeyStorePassword().getChars());
} }
} }

View file

@ -39,14 +39,14 @@ public abstract class BaseKeyStoreCommand extends KeyStoreAwareCommand {
@Override @Override
public final void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public final void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
try { try {
final Path configFile = env.configFile(); final Path configFile = env.configDir();
keyStore = KeyStoreWrapper.load(configFile); keyStore = KeyStoreWrapper.load(configFile);
if (keyStore == null) { if (keyStore == null) {
if (keyStoreMustExist) { if (keyStoreMustExist) {
throw new UserException( throw new UserException(
ExitCodes.DATA_ERROR, ExitCodes.DATA_ERROR,
"Elasticsearch keystore not found at [" "Elasticsearch keystore not found at ["
+ KeyStoreWrapper.keystorePath(env.configFile()) + KeyStoreWrapper.keystorePath(env.configDir())
+ "]. Use 'create' command to create one." + "]. Use 'create' command to create one."
); );
} else if (options.has(forceOption) == false) { } else if (options.has(forceOption) == false) {

View file

@ -31,7 +31,7 @@ class ChangeKeyStorePasswordCommand extends BaseKeyStoreCommand {
protected void executeCommand(Terminal terminal, OptionSet options, Environment env) throws Exception { protected void executeCommand(Terminal terminal, OptionSet options, Environment env) throws Exception {
try (SecureString newPassword = readPassword(terminal, true)) { try (SecureString newPassword = readPassword(terminal, true)) {
final KeyStoreWrapper keyStore = getKeyStore(); final KeyStoreWrapper keyStore = getKeyStore();
keyStore.save(env.configFile(), newPassword.getChars()); keyStore.save(env.configDir(), newPassword.getChars());
terminal.println("Elasticsearch keystore password changed successfully."); terminal.println("Elasticsearch keystore password changed successfully.");
} catch (SecurityException e) { } catch (SecurityException e) {
throw new UserException(ExitCodes.DATA_ERROR, e.getMessage()); throw new UserException(ExitCodes.DATA_ERROR, e.getMessage());

View file

@ -40,7 +40,7 @@ class CreateKeyStoreCommand extends KeyStoreAwareCommand {
@Override @Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
try (SecureString password = options.has(passwordOption) ? readPassword(terminal, true) : new SecureString(new char[0])) { try (SecureString password = options.has(passwordOption) ? readPassword(terminal, true) : new SecureString(new char[0])) {
Path keystoreFile = KeyStoreWrapper.keystorePath(env.configFile()); Path keystoreFile = KeyStoreWrapper.keystorePath(env.configDir());
if (Files.exists(keystoreFile)) { if (Files.exists(keystoreFile)) {
if (terminal.promptYesNo("An elasticsearch keystore already exists. Overwrite?", false) == false) { if (terminal.promptYesNo("An elasticsearch keystore already exists. Overwrite?", false) == false) {
terminal.println("Exiting without creating keystore."); terminal.println("Exiting without creating keystore.");
@ -48,8 +48,8 @@ class CreateKeyStoreCommand extends KeyStoreAwareCommand {
} }
} }
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
keystore.save(env.configFile(), password.getChars()); keystore.save(env.configDir(), password.getChars());
terminal.println("Created elasticsearch keystore in " + KeyStoreWrapper.keystorePath(env.configFile())); terminal.println("Created elasticsearch keystore in " + KeyStoreWrapper.keystorePath(env.configDir()));
} catch (SecurityException e) { } catch (SecurityException e) {
throw new UserException(ExitCodes.IO_ERROR, "Error creating the elasticsearch keystore."); throw new UserException(ExitCodes.IO_ERROR, "Error creating the elasticsearch keystore.");
} }

View file

@ -32,7 +32,7 @@ public class HasPasswordKeyStoreCommand extends KeyStoreAwareCommand {
@Override @Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
final Path configFile = env.configFile(); final Path configFile = env.configDir();
final KeyStoreWrapper keyStore = KeyStoreWrapper.load(configFile); final KeyStoreWrapper keyStore = KeyStoreWrapper.load(configFile);
// We handle error printing here so we can respect the "--silent" flag // We handle error printing here so we can respect the "--silent" flag

View file

@ -45,6 +45,6 @@ class RemoveSettingKeyStoreCommand extends BaseKeyStoreCommand {
} }
keyStore.remove(setting); keyStore.remove(setting);
} }
keyStore.save(env.configFile(), getKeyStorePassword().getChars()); keyStore.save(env.configDir(), getKeyStorePassword().getChars());
} }
} }

View file

@ -26,7 +26,7 @@ public class UpgradeKeyStoreCommand extends BaseKeyStoreCommand {
@Override @Override
protected void executeCommand(final Terminal terminal, final OptionSet options, final Environment env) throws Exception { protected void executeCommand(final Terminal terminal, final OptionSet options, final Environment env) throws Exception {
KeyStoreWrapper.upgrade(getKeyStore(), env.configFile(), getKeyStorePassword().getChars()); KeyStoreWrapper.upgrade(getKeyStore(), env.configDir(), getKeyStorePassword().getChars());
} }
} }

View file

@ -46,14 +46,14 @@ public class AddFileKeyStoreCommandTests extends KeyStoreCommandTestCase {
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
bytes[i] = randomByte(); bytes[i] = randomByte();
} }
Path file = env.configFile().resolve(randomAlphaOfLength(16)); Path file = env.configDir().resolve(randomAlphaOfLength(16));
Files.write(file, bytes); Files.write(file, bytes);
return file; return file;
} }
private void addFile(KeyStoreWrapper keystore, String setting, Path file, String password) throws Exception { private void addFile(KeyStoreWrapper keystore, String setting, Path file, String password) throws Exception {
keystore.setFile(setting, Files.readAllBytes(file)); keystore.setFile(setting, Files.readAllBytes(file));
keystore.save(env.configFile(), password.toCharArray()); keystore.save(env.configDir(), password.toCharArray());
} }
public void testMissingCreateWithEmptyPasswordWhenPrompted() throws Exception { public void testMissingCreateWithEmptyPasswordWhenPrompted() throws Exception {
@ -77,7 +77,7 @@ public class AddFileKeyStoreCommandTests extends KeyStoreCommandTestCase {
terminal.addSecretInput(randomFrom("", "keystorepassword")); terminal.addSecretInput(randomFrom("", "keystorepassword"));
terminal.addTextInput("n"); // explicit no terminal.addTextInput("n"); // explicit no
execute("foo"); execute("foo");
assertNull(KeyStoreWrapper.load(env.configFile())); assertNull(KeyStoreWrapper.load(env.configDir()));
} }
public void testOverwritePromptDefault() throws Exception { public void testOverwritePromptDefault() throws Exception {

View file

@ -83,7 +83,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testMissingNoCreate() throws Exception { public void testMissingNoCreate() throws Exception {
terminal.addTextInput("n"); // explicit no terminal.addTextInput("n"); // explicit no
execute("foo"); execute("foo");
assertNull(KeyStoreWrapper.load(env.configFile())); assertNull(KeyStoreWrapper.load(env.configDir()));
} }
public void testOverwritePromptDefault() throws Exception { public void testOverwritePromptDefault() throws Exception {
@ -143,7 +143,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testPromptForValue() throws Exception { public void testPromptForValue() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
terminal.addSecretInput("secret value"); terminal.addSecretInput("secret value");
execute("foo"); execute("foo");
@ -152,7 +152,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testPromptForMultipleValues() throws Exception { public void testPromptForMultipleValues() throws Exception {
final String password = "keystorepassword"; final String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
terminal.addSecretInput("bar1"); terminal.addSecretInput("bar1");
terminal.addSecretInput("bar2"); terminal.addSecretInput("bar2");
@ -165,7 +165,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinShort() throws Exception { public void testStdinShort() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput("secret value 1"); setInput("secret value 1");
execute("-x", "foo"); execute("-x", "foo");
@ -174,7 +174,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinLong() throws Exception { public void testStdinLong() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput("secret value 2"); setInput("secret value 2");
execute("--stdin", "foo"); execute("--stdin", "foo");
@ -183,7 +183,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinNoInput() throws Exception { public void testStdinNoInput() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput(""); setInput("");
execute("-x", "foo"); execute("-x", "foo");
@ -192,7 +192,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinInputWithLineBreaks() throws Exception { public void testStdinInputWithLineBreaks() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput("Typedthisandhitenter\n"); setInput("Typedthisandhitenter\n");
execute("-x", "foo"); execute("-x", "foo");
@ -201,7 +201,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinInputWithCarriageReturn() throws Exception { public void testStdinInputWithCarriageReturn() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput("Typedthisandhitenter\r"); setInput("Typedthisandhitenter\r");
execute("-x", "foo"); execute("-x", "foo");
@ -210,7 +210,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testStdinWithMultipleValues() throws Exception { public void testStdinWithMultipleValues() throws Exception {
final String password = "keystorepassword"; final String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
setInput("bar1\nbar2\nbar3"); setInput("bar1\nbar2\nbar3");
execute(randomFrom("-x", "--stdin"), "foo1", "foo2", "foo3"); execute(randomFrom("-x", "--stdin"), "foo1", "foo2", "foo3");
@ -221,7 +221,7 @@ public class AddStringKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testAddUtf8String() throws Exception { public void testAddUtf8String() throws Exception {
String password = "keystorepassword"; String password = "keystorepassword";
KeyStoreWrapper.create().save(env.configFile(), password.toCharArray()); KeyStoreWrapper.create().save(env.configDir(), password.toCharArray());
terminal.addSecretInput(password); terminal.addSecretInput(password);
final int stringSize = randomIntBetween(8, 16); final int stringSize = randomIntBetween(8, 16);
try (CharArrayWriter secretChars = new CharArrayWriter(stringSize)) { try (CharArrayWriter secretChars = new CharArrayWriter(stringSize)) {

View file

@ -42,7 +42,7 @@ public class BootstrapTests extends ESTestCase {
public void testLoadSecureSettings() throws Exception { public void testLoadSecureSettings() throws Exception {
final char[] password = KeyStoreWrapperTests.getPossibleKeystorePassword(); final char[] password = KeyStoreWrapperTests.getPossibleKeystorePassword();
final Path configPath = env.configFile(); final Path configPath = env.configDir();
final SecureString seed; final SecureString seed;
try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) { try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) {
seed = KeyStoreWrapper.SEED_SETTING.get(Settings.builder().setSecureSettings(keyStoreWrapper).build()); seed = KeyStoreWrapper.SEED_SETTING.get(Settings.builder().setSecureSettings(keyStoreWrapper).build());

View file

@ -48,7 +48,7 @@ public class CreateKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testDefaultNotPromptForPassword() throws Exception { public void testDefaultNotPromptForPassword() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm()); assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
execute(); execute();
Path configDir = env.configFile(); Path configDir = env.configDir();
assertNotNull(KeyStoreWrapper.load(configDir)); assertNotNull(KeyStoreWrapper.load(configDir));
} }
@ -63,7 +63,7 @@ public class CreateKeyStoreCommandTests extends KeyStoreCommandTestCase {
} else { } else {
execute(); execute();
} }
Path configDir = env.configFile(); Path configDir = env.configDir();
assertNotNull(KeyStoreWrapper.load(configDir)); assertNotNull(KeyStoreWrapper.load(configDir));
} }
@ -79,13 +79,13 @@ public class CreateKeyStoreCommandTests extends KeyStoreCommandTestCase {
} else { } else {
execute(); execute();
} }
Path configDir = env.configFile(); Path configDir = env.configDir();
assertNotNull(KeyStoreWrapper.load(configDir)); assertNotNull(KeyStoreWrapper.load(configDir));
} }
public void testOverwrite() throws Exception { public void testOverwrite() throws Exception {
String password = getPossibleKeystorePassword(); String password = getPossibleKeystorePassword();
Path keystoreFile = KeyStoreWrapper.keystorePath(env.configFile()); Path keystoreFile = KeyStoreWrapper.keystorePath(env.configDir());
byte[] content = "not a keystore".getBytes(StandardCharsets.UTF_8); byte[] content = "not a keystore".getBytes(StandardCharsets.UTF_8);
Files.write(keystoreFile, content); Files.write(keystoreFile, content);
@ -110,6 +110,6 @@ public class CreateKeyStoreCommandTests extends KeyStoreCommandTestCase {
} else { } else {
execute(); execute();
} }
assertNotNull(KeyStoreWrapper.load(env.configFile())); assertNotNull(KeyStoreWrapper.load(env.configDir()));
} }
} }

View file

@ -77,11 +77,11 @@ public abstract class KeyStoreCommandTestCase extends CommandTestCase {
} }
void saveKeystore(KeyStoreWrapper keystore, String password) throws Exception { void saveKeystore(KeyStoreWrapper keystore, String password) throws Exception {
keystore.save(env.configFile(), password.toCharArray()); keystore.save(env.configDir(), password.toCharArray());
} }
KeyStoreWrapper loadKeystore(String password) throws Exception { KeyStoreWrapper loadKeystore(String password) throws Exception {
KeyStoreWrapper keystore = KeyStoreWrapper.load(env.configFile()); KeyStoreWrapper keystore = KeyStoreWrapper.load(env.configDir());
keystore.decrypt(password.toCharArray()); keystore.decrypt(password.toCharArray());
return keystore; return keystore;
} }

View file

@ -84,8 +84,8 @@ public class KeyStoreWrapperTests extends ESTestCase {
bytes[i] = (byte) i; bytes[i] = (byte) i;
} }
keystore.setFile("foo", bytes); keystore.setFile("foo", bytes);
keystore.save(env.configFile(), password); keystore.save(env.configDir(), password);
keystore = KeyStoreWrapper.load(env.configFile()); keystore = KeyStoreWrapper.load(env.configDir());
keystore.decrypt(password); keystore.decrypt(password);
try (InputStream stream = keystore.getFile("foo")) { try (InputStream stream = keystore.getFile("foo")) {
for (int i = 0; i < 256; ++i) { for (int i = 0; i < 256; ++i) {
@ -114,8 +114,8 @@ public class KeyStoreWrapperTests extends ESTestCase {
invalidPassword[realPassword.length] = '#'; invalidPassword[realPassword.length] = '#';
} }
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
keystore.save(env.configFile(), realPassword); keystore.save(env.configDir(), realPassword);
final KeyStoreWrapper loadedkeystore = KeyStoreWrapper.load(env.configFile()); final KeyStoreWrapper loadedkeystore = KeyStoreWrapper.load(env.configDir());
final SecurityException exception = expectThrows(SecurityException.class, () -> loadedkeystore.decrypt(invalidPassword)); final SecurityException exception = expectThrows(SecurityException.class, () -> loadedkeystore.decrypt(invalidPassword));
if (inFipsJvm()) { if (inFipsJvm()) {
assertThat( assertThat(
@ -133,8 +133,8 @@ public class KeyStoreWrapperTests extends ESTestCase {
public void testDecryptKeyStoreWithShortPasswordInFips() throws Exception { public void testDecryptKeyStoreWithShortPasswordInFips() throws Exception {
assumeTrue("This should run only in FIPS mode", inFipsJvm()); assumeTrue("This should run only in FIPS mode", inFipsJvm());
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
keystore.save(env.configFile(), "alongenoughpassword".toCharArray()); keystore.save(env.configDir(), "alongenoughpassword".toCharArray());
final KeyStoreWrapper loadedkeystore = KeyStoreWrapper.load(env.configFile()); final KeyStoreWrapper loadedkeystore = KeyStoreWrapper.load(env.configDir());
final GeneralSecurityException exception = expectThrows( final GeneralSecurityException exception = expectThrows(
GeneralSecurityException.class, GeneralSecurityException.class,
() -> loadedkeystore.decrypt("shortpwd".toCharArray()) // shorter than 14 characters () -> loadedkeystore.decrypt("shortpwd".toCharArray()) // shorter than 14 characters
@ -147,7 +147,7 @@ public class KeyStoreWrapperTests extends ESTestCase {
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
final GeneralSecurityException exception = expectThrows( final GeneralSecurityException exception = expectThrows(
GeneralSecurityException.class, GeneralSecurityException.class,
() -> keystore.save(env.configFile(), "shortpwd".toCharArray()) // shorter than 14 characters () -> keystore.save(env.configDir(), "shortpwd".toCharArray()) // shorter than 14 characters
); );
assertThat(exception.getMessage(), containsString("Error generating an encryption key from the provided password")); assertThat(exception.getMessage(), containsString("Error generating an encryption key from the provided password"));
} }
@ -192,18 +192,18 @@ public class KeyStoreWrapperTests extends ESTestCase {
final char[] password = getPossibleKeystorePassword(); final char[] password = getPossibleKeystorePassword();
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
SecureString seed = keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()); SecureString seed = keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey());
keystore.save(env.configFile(), password); keystore.save(env.configDir(), password);
// upgrade does not overwrite seed // upgrade does not overwrite seed
KeyStoreWrapper.upgrade(keystore, env.configFile(), password); KeyStoreWrapper.upgrade(keystore, env.configDir(), password);
assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString()); assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString());
keystore = KeyStoreWrapper.load(env.configFile()); keystore = KeyStoreWrapper.load(env.configDir());
keystore.decrypt(password); keystore.decrypt(password);
assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString()); assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString());
} }
public void testFailWhenCannotConsumeSecretStream() throws Exception { public void testFailWhenCannotConsumeSecretStream() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm()); assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
Path configDir = env.configFile(); Path configDir = env.configDir();
try ( try (
Directory directory = newFSDirectory(configDir); Directory directory = newFSDirectory(configDir);
IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT) IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT)
@ -234,7 +234,7 @@ public class KeyStoreWrapperTests extends ESTestCase {
public void testFailWhenCannotConsumeEncryptedBytesStream() throws Exception { public void testFailWhenCannotConsumeEncryptedBytesStream() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm()); assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
Path configDir = env.configFile(); Path configDir = env.configDir();
try ( try (
Directory directory = newFSDirectory(configDir); Directory directory = newFSDirectory(configDir);
IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT) IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT)
@ -266,7 +266,7 @@ public class KeyStoreWrapperTests extends ESTestCase {
public void testFailWhenSecretStreamNotConsumed() throws Exception { public void testFailWhenSecretStreamNotConsumed() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm()); assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
Path configDir = env.configFile(); Path configDir = env.configDir();
try ( try (
Directory directory = newFSDirectory(configDir); Directory directory = newFSDirectory(configDir);
IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT) IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT)
@ -296,7 +296,7 @@ public class KeyStoreWrapperTests extends ESTestCase {
public void testFailWhenEncryptedBytesStreamIsNotConsumed() throws Exception { public void testFailWhenEncryptedBytesStreamIsNotConsumed() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm()); assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
Path configDir = env.configFile(); Path configDir = env.configDir();
try ( try (
Directory directory = newFSDirectory(configDir); Directory directory = newFSDirectory(configDir);
IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT) IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT)
@ -359,11 +359,11 @@ public class KeyStoreWrapperTests extends ESTestCase {
final char[] password = getPossibleKeystorePassword(); final char[] password = getPossibleKeystorePassword();
KeyStoreWrapper keystore = KeyStoreWrapper.create(); KeyStoreWrapper keystore = KeyStoreWrapper.create();
keystore.remove(KeyStoreWrapper.SEED_SETTING.getKey()); keystore.remove(KeyStoreWrapper.SEED_SETTING.getKey());
keystore.save(env.configFile(), password); keystore.save(env.configDir(), password);
KeyStoreWrapper.upgrade(keystore, env.configFile(), password); KeyStoreWrapper.upgrade(keystore, env.configDir(), password);
SecureString seed = keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()); SecureString seed = keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey());
assertNotNull(seed); assertNotNull(seed);
keystore = KeyStoreWrapper.load(env.configFile()); keystore = KeyStoreWrapper.load(env.configDir());
keystore.decrypt(password); keystore.decrypt(password);
assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString()); assertEquals(seed.toString(), keystore.getString(KeyStoreWrapper.SEED_SETTING.getKey()).toString());
} }
@ -380,7 +380,7 @@ public class KeyStoreWrapperTests extends ESTestCase {
public void testBackcompatV4() throws Exception { public void testBackcompatV4() throws Exception {
assumeFalse("Can't run in a FIPS JVM as PBE is not available", inFipsJvm()); assumeFalse("Can't run in a FIPS JVM as PBE is not available", inFipsJvm());
Path configDir = env.configFile(); Path configDir = env.configDir();
try ( try (
Directory directory = newFSDirectory(configDir); Directory directory = newFSDirectory(configDir);
IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT) IndexOutput indexOutput = EndiannessReverserUtil.createOutput(directory, "elasticsearch.keystore", IOContext.DEFAULT)
@ -421,10 +421,10 @@ public class KeyStoreWrapperTests extends ESTestCase {
final Path temp = createTempDir(); final Path temp = createTempDir();
Files.writeString(temp.resolve("file_setting"), "file_value", StandardCharsets.UTF_8); Files.writeString(temp.resolve("file_setting"), "file_value", StandardCharsets.UTF_8);
wrapper.setFile("file_setting", Files.readAllBytes(temp.resolve("file_setting"))); wrapper.setFile("file_setting", Files.readAllBytes(temp.resolve("file_setting")));
wrapper.save(env.configFile(), password); wrapper.save(env.configDir(), password);
wrapper.close(); wrapper.close();
final KeyStoreWrapper afterSave = KeyStoreWrapper.load(env.configFile()); final KeyStoreWrapper afterSave = KeyStoreWrapper.load(env.configDir());
assertNotNull(afterSave); assertNotNull(afterSave);
afterSave.decrypt(password); afterSave.decrypt(password);
assertThat(afterSave.getSettingNames(), equalTo(Set.of("keystore.seed", "string_setting", "file_setting"))); assertThat(afterSave.getSettingNames(), equalTo(Set.of("keystore.seed", "string_setting", "file_setting")));
@ -510,8 +510,8 @@ public class KeyStoreWrapperTests extends ESTestCase {
// testing with password and raw dataBytes[] // testing with password and raw dataBytes[]
final char[] password = getPossibleKeystorePassword(); final char[] password = getPossibleKeystorePassword();
wrapper.save(env.configFile(), password); wrapper.save(env.configDir(), password);
final KeyStoreWrapper fromFile = KeyStoreWrapper.load(env.configFile()); final KeyStoreWrapper fromFile = KeyStoreWrapper.load(env.configDir());
fromFile.decrypt(password); fromFile.decrypt(password);
assertThat(fromFile.getSettingNames(), hasSize(2)); assertThat(fromFile.getSettingNames(), hasSize(2));

View file

@ -62,11 +62,11 @@ public class UpgradeKeyStoreCommandTests extends KeyStoreCommandTestCase {
} }
private void assertKeystoreUpgrade(String file, int version, @Nullable String password) throws Exception { private void assertKeystoreUpgrade(String file, int version, @Nullable String password) throws Exception {
final Path keystore = KeyStoreWrapper.keystorePath(env.configFile()); final Path keystore = KeyStoreWrapper.keystorePath(env.configDir());
try (InputStream is = KeyStoreWrapperTests.class.getResourceAsStream(file); OutputStream os = Files.newOutputStream(keystore)) { try (InputStream is = KeyStoreWrapperTests.class.getResourceAsStream(file); OutputStream os = Files.newOutputStream(keystore)) {
is.transferTo(os); is.transferTo(os);
} }
try (KeyStoreWrapper beforeUpgrade = KeyStoreWrapper.load(env.configFile())) { try (KeyStoreWrapper beforeUpgrade = KeyStoreWrapper.load(env.configDir())) {
assertNotNull(beforeUpgrade); assertNotNull(beforeUpgrade);
assertThat(beforeUpgrade.getFormatVersion(), equalTo(version)); assertThat(beforeUpgrade.getFormatVersion(), equalTo(version));
} }
@ -77,7 +77,7 @@ public class UpgradeKeyStoreCommandTests extends KeyStoreCommandTestCase {
execute(); execute();
terminal.reset(); terminal.reset();
try (KeyStoreWrapper afterUpgrade = KeyStoreWrapper.load(env.configFile())) { try (KeyStoreWrapper afterUpgrade = KeyStoreWrapper.load(env.configDir())) {
assertNotNull(afterUpgrade); assertNotNull(afterUpgrade);
assertThat(afterUpgrade.getFormatVersion(), equalTo(KeyStoreWrapper.CURRENT_VERSION)); assertThat(afterUpgrade.getFormatVersion(), equalTo(KeyStoreWrapper.CURRENT_VERSION));
afterUpgrade.decrypt(password != null ? password.toCharArray() : new char[0]); afterUpgrade.decrypt(password != null ? password.toCharArray() : new char[0]);
@ -87,6 +87,6 @@ public class UpgradeKeyStoreCommandTests extends KeyStoreCommandTestCase {
public void testKeystoreDoesNotExist() { public void testKeystoreDoesNotExist() {
final UserException e = expectThrows(UserException.class, this::execute); final UserException e = expectThrows(UserException.class, this::execute);
assertThat(e, hasToString(containsString("keystore not found at [" + KeyStoreWrapper.keystorePath(env.configFile()) + "]"))); assertThat(e, hasToString(containsString("keystore not found at [" + KeyStoreWrapper.keystorePath(env.configDir()) + "]")));
} }
} }

View file

@ -249,8 +249,8 @@ public class InstallPluginAction implements Closeable {
final List<Path> deleteOnFailure = new ArrayList<>(); final List<Path> deleteOnFailure = new ArrayList<>();
deleteOnFailures.put(pluginId, deleteOnFailure); deleteOnFailures.put(pluginId, deleteOnFailure);
final Path pluginZip = download(plugin, env.tmpFile()); final Path pluginZip = download(plugin, env.tmpDir());
final Path extractedZip = unzip(pluginZip, env.pluginsFile()); final Path extractedZip = unzip(pluginZip, env.pluginsDir());
deleteOnFailure.add(extractedZip); deleteOnFailure.add(extractedZip);
final PluginDescriptor pluginDescriptor = installPlugin(plugin, extractedZip, deleteOnFailure); final PluginDescriptor pluginDescriptor = installPlugin(plugin, extractedZip, deleteOnFailure);
terminal.println(logPrefix + "Installed " + pluginDescriptor.getName()); terminal.println(logPrefix + "Installed " + pluginDescriptor.getName());
@ -868,14 +868,14 @@ public class InstallPluginAction implements Closeable {
PluginsUtils.verifyCompatibility(info); PluginsUtils.verifyCompatibility(info);
// checking for existing version of the plugin // checking for existing version of the plugin
verifyPluginName(env.pluginsFile(), info.getName()); verifyPluginName(env.pluginsDir(), info.getName());
PluginsUtils.checkForFailedPluginRemovals(env.pluginsFile()); PluginsUtils.checkForFailedPluginRemovals(env.pluginsDir());
terminal.println(VERBOSE, info.toString()); terminal.println(VERBOSE, info.toString());
// check for jar hell before any copying // check for jar hell before any copying
jarHellCheck(info, pluginRoot, env.pluginsFile(), env.modulesFile()); jarHellCheck(info, pluginRoot, env.pluginsDir(), env.modulesDir());
if (info.isStable() && hasNamedComponentFile(pluginRoot) == false) { if (info.isStable() && hasNamedComponentFile(pluginRoot) == false) {
generateNameComponentFile(pluginRoot); generateNameComponentFile(pluginRoot);
@ -922,9 +922,9 @@ public class InstallPluginAction implements Closeable {
*/ */
private PluginDescriptor installPlugin(InstallablePlugin descriptor, Path tmpRoot, List<Path> deleteOnFailure) throws Exception { private PluginDescriptor installPlugin(InstallablePlugin descriptor, Path tmpRoot, List<Path> deleteOnFailure) throws Exception {
final PluginDescriptor info = loadPluginInfo(tmpRoot); final PluginDescriptor info = loadPluginInfo(tmpRoot);
PluginPolicyInfo pluginPolicy = PolicyUtil.getPluginPolicyInfo(tmpRoot, env.tmpFile()); PluginPolicyInfo pluginPolicy = PolicyUtil.getPluginPolicyInfo(tmpRoot, env.tmpDir());
if (pluginPolicy != null) { if (pluginPolicy != null) {
Set<String> permissions = PluginSecurity.getPermissionDescriptions(pluginPolicy, env.tmpFile()); Set<String> permissions = PluginSecurity.getPermissionDescriptions(pluginPolicy, env.tmpDir());
PluginSecurity.confirmPolicyExceptions(terminal, permissions, batch); PluginSecurity.confirmPolicyExceptions(terminal, permissions, batch);
} }
@ -938,14 +938,14 @@ public class InstallPluginAction implements Closeable {
); );
} }
final Path destination = env.pluginsFile().resolve(info.getName()); final Path destination = env.pluginsDir().resolve(info.getName());
deleteOnFailure.add(destination); deleteOnFailure.add(destination);
installPluginSupportFiles( installPluginSupportFiles(
info, info,
tmpRoot, tmpRoot,
env.binFile().resolve(info.getName()), env.binDir().resolve(info.getName()),
env.configFile().resolve(info.getName()), env.configDir().resolve(info.getName()),
deleteOnFailure deleteOnFailure
); );
movePlugin(tmpRoot, destination); movePlugin(tmpRoot, destination);

View file

@ -40,13 +40,13 @@ class ListPluginsCommand extends EnvironmentAwareCommand {
@Override @Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
if (Files.exists(env.pluginsFile()) == false) { if (Files.exists(env.pluginsDir()) == false) {
throw new IOException("Plugins directory missing: " + env.pluginsFile()); throw new IOException("Plugins directory missing: " + env.pluginsDir());
} }
terminal.println(Terminal.Verbosity.VERBOSE, "Plugins directory: " + env.pluginsFile()); terminal.println(Terminal.Verbosity.VERBOSE, "Plugins directory: " + env.pluginsDir());
final List<Path> plugins = new ArrayList<>(); final List<Path> plugins = new ArrayList<>();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(env.pluginsFile())) { try (DirectoryStream<Path> paths = Files.newDirectoryStream(env.pluginsDir())) {
for (Path path : paths) { for (Path path : paths) {
if (path.getFileName().toString().equals(ELASTICSEARCH_PLUGINS_YML_CACHE) == false) { if (path.getFileName().toString().equals(ELASTICSEARCH_PLUGINS_YML_CACHE) == false) {
plugins.add(path); plugins.add(path);
@ -61,7 +61,7 @@ class ListPluginsCommand extends EnvironmentAwareCommand {
private static void printPlugin(Environment env, Terminal terminal, Path plugin, String prefix) throws IOException { private static void printPlugin(Environment env, Terminal terminal, Path plugin, String prefix) throws IOException {
terminal.println(Terminal.Verbosity.SILENT, prefix + plugin.getFileName().toString()); terminal.println(Terminal.Verbosity.SILENT, prefix + plugin.getFileName().toString());
PluginDescriptor info = PluginDescriptor.readFromProperties(env.pluginsFile().resolve(plugin)); PluginDescriptor info = PluginDescriptor.readFromProperties(env.pluginsDir().resolve(plugin));
terminal.println(Terminal.Verbosity.VERBOSE, info.toString(prefix)); terminal.println(Terminal.Verbosity.VERBOSE, info.toString(prefix));
// When PluginDescriptor#getElasticsearchVersion returns a string, we can revisit the need // When PluginDescriptor#getElasticsearchVersion returns a string, we can revisit the need

View file

@ -93,7 +93,7 @@ public class RemovePluginAction {
// We build a new map where the keys are plugins that extend plugins // We build a new map where the keys are plugins that extend plugins
// we want to remove and the values are the plugins we can't remove // we want to remove and the values are the plugins we can't remove
// because of this dependency // because of this dependency
Map<String, List<String>> pluginDependencyMap = PluginsUtils.getDependencyMapView(env.pluginsFile()); Map<String, List<String>> pluginDependencyMap = PluginsUtils.getDependencyMapView(env.pluginsDir());
for (Map.Entry<String, List<String>> entry : pluginDependencyMap.entrySet()) { for (Map.Entry<String, List<String>> entry : pluginDependencyMap.entrySet()) {
for (String extendedPlugin : entry.getValue()) { for (String extendedPlugin : entry.getValue()) {
for (InstallablePlugin plugin : plugins) { for (InstallablePlugin plugin : plugins) {
@ -121,9 +121,9 @@ public class RemovePluginAction {
private void checkCanRemove(InstallablePlugin plugin) throws UserException { private void checkCanRemove(InstallablePlugin plugin) throws UserException {
String pluginId = plugin.getId(); String pluginId = plugin.getId();
final Path pluginDir = env.pluginsFile().resolve(pluginId); final Path pluginDir = env.pluginsDir().resolve(pluginId);
final Path pluginConfigDir = env.configFile().resolve(pluginId); final Path pluginConfigDir = env.configDir().resolve(pluginId);
final Path removing = env.pluginsFile().resolve(".removing-" + pluginId); final Path removing = env.pluginsDir().resolve(".removing-" + pluginId);
/* /*
* If the plugin does not exist and the plugin config does not exist, fail to the user that the plugin is not found, unless there's * If the plugin does not exist and the plugin config does not exist, fail to the user that the plugin is not found, unless there's
@ -147,7 +147,7 @@ public class RemovePluginAction {
} }
} }
final Path pluginBinDir = env.binFile().resolve(pluginId); final Path pluginBinDir = env.binDir().resolve(pluginId);
if (Files.exists(pluginBinDir)) { if (Files.exists(pluginBinDir)) {
if (Files.isDirectory(pluginBinDir) == false) { if (Files.isDirectory(pluginBinDir) == false) {
throw new UserException(ExitCodes.IO_ERROR, "bin dir for " + pluginId + " is not a directory"); throw new UserException(ExitCodes.IO_ERROR, "bin dir for " + pluginId + " is not a directory");
@ -157,9 +157,9 @@ public class RemovePluginAction {
private void removePlugin(InstallablePlugin plugin) throws IOException { private void removePlugin(InstallablePlugin plugin) throws IOException {
final String pluginId = plugin.getId(); final String pluginId = plugin.getId();
final Path pluginDir = env.pluginsFile().resolve(pluginId); final Path pluginDir = env.pluginsDir().resolve(pluginId);
final Path pluginConfigDir = env.configFile().resolve(pluginId); final Path pluginConfigDir = env.configDir().resolve(pluginId);
final Path removing = env.pluginsFile().resolve(".removing-" + pluginId); final Path removing = env.pluginsDir().resolve(".removing-" + pluginId);
terminal.println("-> removing [" + pluginId + "]..."); terminal.println("-> removing [" + pluginId + "]...");
@ -176,7 +176,7 @@ public class RemovePluginAction {
terminal.println(VERBOSE, "removing [" + pluginDir + "]"); terminal.println(VERBOSE, "removing [" + pluginDir + "]");
} }
final Path pluginBinDir = env.binFile().resolve(pluginId); final Path pluginBinDir = env.binDir().resolve(pluginId);
if (Files.exists(pluginBinDir)) { if (Files.exists(pluginBinDir)) {
try (Stream<Path> paths = Files.list(pluginBinDir)) { try (Stream<Path> paths = Files.list(pluginBinDir)) {
pluginPaths.addAll(paths.toList()); pluginPaths.addAll(paths.toList());

View file

@ -61,7 +61,7 @@ public class SyncPluginsAction {
* @throws UserException if a plugins config file is found. * @throws UserException if a plugins config file is found.
*/ */
public static void ensureNoConfigFile(Environment env) throws UserException { public static void ensureNoConfigFile(Environment env) throws UserException {
final Path pluginsConfig = env.configFile().resolve(ELASTICSEARCH_PLUGINS_YML); final Path pluginsConfig = env.configDir().resolve(ELASTICSEARCH_PLUGINS_YML);
if (Files.exists(pluginsConfig)) { if (Files.exists(pluginsConfig)) {
throw new UserException( throw new UserException(
ExitCodes.USAGE, ExitCodes.USAGE,
@ -79,16 +79,16 @@ public class SyncPluginsAction {
* @throws Exception if anything goes wrong * @throws Exception if anything goes wrong
*/ */
public void execute() throws Exception { public void execute() throws Exception {
final Path configPath = this.env.configFile().resolve(ELASTICSEARCH_PLUGINS_YML); final Path configPath = this.env.configDir().resolve(ELASTICSEARCH_PLUGINS_YML);
final Path previousConfigPath = this.env.pluginsFile().resolve(ELASTICSEARCH_PLUGINS_YML_CACHE); final Path previousConfigPath = this.env.pluginsDir().resolve(ELASTICSEARCH_PLUGINS_YML_CACHE);
if (Files.exists(configPath) == false) { if (Files.exists(configPath) == false) {
// The `PluginsManager` will have checked that this file exists before invoking the action. // The `PluginsManager` will have checked that this file exists before invoking the action.
throw new PluginSyncException("Plugins config does not exist: " + configPath.toAbsolutePath()); throw new PluginSyncException("Plugins config does not exist: " + configPath.toAbsolutePath());
} }
if (Files.exists(env.pluginsFile()) == false) { if (Files.exists(env.pluginsDir()) == false) {
throw new PluginSyncException("Plugins directory missing: " + env.pluginsFile()); throw new PluginSyncException("Plugins directory missing: " + env.pluginsDir());
} }
// Parse descriptor file // Parse descriptor file
@ -267,14 +267,14 @@ public class SyncPluginsAction {
final List<PluginDescriptor> plugins = new ArrayList<>(); final List<PluginDescriptor> plugins = new ArrayList<>();
try { try {
try (DirectoryStream<Path> paths = Files.newDirectoryStream(env.pluginsFile())) { try (DirectoryStream<Path> paths = Files.newDirectoryStream(env.pluginsDir())) {
for (Path pluginPath : paths) { for (Path pluginPath : paths) {
String filename = pluginPath.getFileName().toString(); String filename = pluginPath.getFileName().toString();
if (filename.startsWith(".")) { if (filename.startsWith(".")) {
continue; continue;
} }
PluginDescriptor info = PluginDescriptor.readFromProperties(env.pluginsFile().resolve(pluginPath)); PluginDescriptor info = PluginDescriptor.readFromProperties(env.pluginsDir().resolve(pluginPath));
plugins.add(info); plugins.add(info);
// Check for a version mismatch, unless it's an official plugin since we can upgrade them. // Check for a version mismatch, unless it's an official plugin since we can upgrade them.

View file

@ -37,7 +37,7 @@ public class SyncPluginsCliProvider implements CliToolProvider {
@Override @Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
var action = new SyncPluginsAction(terminal, env); var action = new SyncPluginsAction(terminal, env);
if (Files.exists(env.configFile().resolve(ELASTICSEARCH_PLUGINS_YML)) == false) { if (Files.exists(env.configDir().resolve(ELASTICSEARCH_PLUGINS_YML)) == false) {
return; return;
} }
if (Build.current().type() != Build.Type.DOCKER) { if (Build.current().type() != Build.Type.DOCKER) {

View file

@ -354,7 +354,7 @@ public class InstallPluginActionTests extends ESTestCase {
} }
void assertPlugin(String name, Path original, Environment environment) throws IOException { void assertPlugin(String name, Path original, Environment environment) throws IOException {
assertPluginInternal(name, environment.pluginsFile(), original); assertPluginInternal(name, environment.pluginsDir(), original);
assertConfigAndBin(name, original, environment); assertConfigAndBin(name, original, environment);
assertInstallCleaned(environment); assertInstallCleaned(environment);
} }
@ -395,7 +395,7 @@ public class InstallPluginActionTests extends ESTestCase {
void assertConfigAndBin(String name, Path original, Environment environment) throws IOException { void assertConfigAndBin(String name, Path original, Environment environment) throws IOException {
if (Files.exists(original.resolve("bin"))) { if (Files.exists(original.resolve("bin"))) {
Path binDir = environment.binFile().resolve(name); Path binDir = environment.binDir().resolve(name);
assertTrue("bin dir exists", Files.exists(binDir)); assertTrue("bin dir exists", Files.exists(binDir));
assertTrue("bin is a dir", Files.isDirectory(binDir)); assertTrue("bin is a dir", Files.isDirectory(binDir));
try (DirectoryStream<Path> stream = Files.newDirectoryStream(binDir)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(binDir)) {
@ -409,7 +409,7 @@ public class InstallPluginActionTests extends ESTestCase {
} }
} }
if (Files.exists(original.resolve("config"))) { if (Files.exists(original.resolve("config"))) {
Path configDir = environment.configFile().resolve(name); Path configDir = environment.configDir().resolve(name);
assertTrue("config dir exists", Files.exists(configDir)); assertTrue("config dir exists", Files.exists(configDir));
assertTrue("config is a dir", Files.isDirectory(configDir)); assertTrue("config is a dir", Files.isDirectory(configDir));
@ -417,7 +417,7 @@ public class InstallPluginActionTests extends ESTestCase {
GroupPrincipal group = null; GroupPrincipal group = null;
if (isPosix) { if (isPosix) {
PosixFileAttributes configAttributes = Files.getFileAttributeView(environment.configFile(), PosixFileAttributeView.class) PosixFileAttributes configAttributes = Files.getFileAttributeView(environment.configDir(), PosixFileAttributeView.class)
.readAttributes(); .readAttributes();
user = configAttributes.owner(); user = configAttributes.owner();
group = configAttributes.group(); group = configAttributes.group();
@ -446,7 +446,7 @@ public class InstallPluginActionTests extends ESTestCase {
} }
void assertInstallCleaned(Environment environment) throws IOException { void assertInstallCleaned(Environment environment) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(environment.pluginsFile())) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(environment.pluginsDir())) {
for (Path file : stream) { for (Path file : stream) {
if (file.getFileName().toString().startsWith(".installing")) { if (file.getFileName().toString().startsWith(".installing")) {
fail("Installation dir still exists, " + file); fail("Installation dir still exists, " + file);
@ -549,7 +549,7 @@ public class InstallPluginActionTests extends ESTestCase {
() -> installPlugins(List.of(pluginZip, nonexistentPluginZip), env.v1()) () -> installPlugins(List.of(pluginZip, nonexistentPluginZip), env.v1())
); );
assertThat(e.getMessage(), containsString("does-not-exist")); assertThat(e.getMessage(), containsString("does-not-exist"));
final Path fakeInstallPath = env.v2().pluginsFile().resolve("fake"); final Path fakeInstallPath = env.v2().pluginsDir().resolve("fake");
// fake should have been removed when the file not found exception occurred // fake should have been removed when the file not found exception occurred
assertFalse(Files.exists(fakeInstallPath)); assertFalse(Files.exists(fakeInstallPath));
assertInstallCleaned(env.v2()); assertInstallCleaned(env.v2());
@ -557,7 +557,7 @@ public class InstallPluginActionTests extends ESTestCase {
public void testInstallFailsIfPreviouslyRemovedPluginFailed() throws Exception { public void testInstallFailsIfPreviouslyRemovedPluginFailed() throws Exception {
InstallablePlugin pluginZip = createPluginZip("fake", pluginDir); InstallablePlugin pluginZip = createPluginZip("fake", pluginDir);
final Path removing = env.v2().pluginsFile().resolve(".removing-failed"); final Path removing = env.v2().pluginsDir().resolve(".removing-failed");
Files.createDirectory(removing); Files.createDirectory(removing);
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> installPlugin(pluginZip)); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> installPlugin(pluginZip));
final String expected = Strings.format( final String expected = Strings.format(
@ -603,11 +603,11 @@ public class InstallPluginActionTests extends ESTestCase {
public void testPluginsDirReadOnly() throws Exception { public void testPluginsDirReadOnly() throws Exception {
assumeTrue("posix and filesystem", isPosix && isReal); assumeTrue("posix and filesystem", isPosix && isReal);
try (PosixPermissionsResetter pluginsAttrs = new PosixPermissionsResetter(env.v2().pluginsFile())) { try (PosixPermissionsResetter pluginsAttrs = new PosixPermissionsResetter(env.v2().pluginsDir())) {
pluginsAttrs.setPermissions(new HashSet<>()); pluginsAttrs.setPermissions(new HashSet<>());
InstallablePlugin pluginZip = createPluginZip("fake", pluginDir); InstallablePlugin pluginZip = createPluginZip("fake", pluginDir);
IOException e = expectThrows(IOException.class, () -> installPlugin(pluginZip)); IOException e = expectThrows(IOException.class, () -> installPlugin(pluginZip));
assertThat(e.getMessage(), containsString(env.v2().pluginsFile().toString())); assertThat(e.getMessage(), containsString(env.v2().pluginsDir().toString()));
} }
assertInstallCleaned(env.v2()); assertInstallCleaned(env.v2());
} }
@ -694,7 +694,7 @@ public class InstallPluginActionTests extends ESTestCase {
Files.createFile(binDir.resolve("somescript")); Files.createFile(binDir.resolve("somescript"));
InstallablePlugin pluginZip = createPluginZip("elasticsearch", pluginDir); InstallablePlugin pluginZip = createPluginZip("elasticsearch", pluginDir);
FileAlreadyExistsException e = expectThrows(FileAlreadyExistsException.class, () -> installPlugin(pluginZip)); FileAlreadyExistsException e = expectThrows(FileAlreadyExistsException.class, () -> installPlugin(pluginZip));
assertThat(e.getMessage(), containsString(env.v2().binFile().resolve("elasticsearch").toString())); assertThat(e.getMessage(), containsString(env.v2().binDir().resolve("elasticsearch").toString()));
assertInstallCleaned(env.v2()); assertInstallCleaned(env.v2());
} }
@ -704,7 +704,7 @@ public class InstallPluginActionTests extends ESTestCase {
Files.createDirectory(binDir); Files.createDirectory(binDir);
Files.createFile(binDir.resolve("somescript")); Files.createFile(binDir.resolve("somescript"));
InstallablePlugin pluginZip = createPluginZip("fake", pluginDir); InstallablePlugin pluginZip = createPluginZip("fake", pluginDir);
try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binFile())) { try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binDir())) {
Set<PosixFilePermission> perms = binAttrs.getCopyPermissions(); Set<PosixFilePermission> perms = binAttrs.getCopyPermissions();
// make sure at least one execute perm is missing, so we know we forced it during installation // make sure at least one execute perm is missing, so we know we forced it during installation
perms.remove(PosixFilePermission.GROUP_EXECUTE); perms.remove(PosixFilePermission.GROUP_EXECUTE);
@ -734,7 +734,7 @@ public class InstallPluginActionTests extends ESTestCase {
installPlugin(pluginZip); installPlugin(pluginZip);
assertPlugin("fake", tempPluginDir, env.v2()); assertPlugin("fake", tempPluginDir, env.v2());
final Path fake = env.v2().pluginsFile().resolve("fake"); final Path fake = env.v2().pluginsDir().resolve("fake");
final Path resources = fake.resolve("resources"); final Path resources = fake.resolve("resources");
final Path platform = fake.resolve("platform"); final Path platform = fake.resolve("platform");
final Path platformName = platform.resolve("linux-x86_64"); final Path platformName = platform.resolve("linux-x86_64");
@ -784,7 +784,7 @@ public class InstallPluginActionTests extends ESTestCase {
} }
public void testExistingConfig() throws Exception { public void testExistingConfig() throws Exception {
Path envConfigDir = env.v2().configFile().resolve("fake"); Path envConfigDir = env.v2().configDir().resolve("fake");
Files.createDirectories(envConfigDir); Files.createDirectories(envConfigDir);
Files.write(envConfigDir.resolve("custom.yml"), "existing config".getBytes(StandardCharsets.UTF_8)); Files.write(envConfigDir.resolve("custom.yml"), "existing config".getBytes(StandardCharsets.UTF_8));
Path configDir = pluginDir.resolve("config"); Path configDir = pluginDir.resolve("config");
@ -921,7 +921,7 @@ public class InstallPluginActionTests extends ESTestCase {
e.getMessage(), e.getMessage(),
equalTo( equalTo(
"plugin directory [" "plugin directory ["
+ env.v2().pluginsFile().resolve("fake") + env.v2().pluginsDir().resolve("fake")
+ "] already exists; " + "] already exists; "
+ "if you need to update the plugin, uninstall it first using command 'remove fake'" + "if you need to update the plugin, uninstall it first using command 'remove fake'"
) )
@ -1499,7 +1499,7 @@ public class InstallPluginActionTests extends ESTestCase {
assertThat(e.getMessage(), containsString("installation aborted by user")); assertThat(e.getMessage(), containsString("installation aborted by user"));
assertThat(terminal.getErrorOutput(), containsString("WARNING: " + warning)); assertThat(terminal.getErrorOutput(), containsString("WARNING: " + warning));
try (Stream<Path> fileStream = Files.list(pathEnvironmentTuple.v2().pluginsFile())) { try (Stream<Path> fileStream = Files.list(pathEnvironmentTuple.v2().pluginsDir())) {
assertThat(fileStream.collect(Collectors.toList()), empty()); assertThat(fileStream.collect(Collectors.toList()), empty());
} }
@ -1512,7 +1512,7 @@ public class InstallPluginActionTests extends ESTestCase {
e = expectThrows(UserException.class, () -> installPlugin(pluginZip)); e = expectThrows(UserException.class, () -> installPlugin(pluginZip));
assertThat(e.getMessage(), containsString("installation aborted by user")); assertThat(e.getMessage(), containsString("installation aborted by user"));
assertThat(terminal.getErrorOutput(), containsString("WARNING: " + warning)); assertThat(terminal.getErrorOutput(), containsString("WARNING: " + warning));
try (Stream<Path> fileStream = Files.list(pathEnvironmentTuple.v2().pluginsFile())) { try (Stream<Path> fileStream = Files.list(pathEnvironmentTuple.v2().pluginsDir())) {
assertThat(fileStream.collect(Collectors.toList()), empty()); assertThat(fileStream.collect(Collectors.toList()), empty());
} }
} }
@ -1566,7 +1566,7 @@ public class InstallPluginActionTests extends ESTestCase {
InstallablePlugin stablePluginZip = createStablePlugin("stable1", pluginDir, true); InstallablePlugin stablePluginZip = createStablePlugin("stable1", pluginDir, true);
installPlugins(List.of(stablePluginZip), env.v1()); installPlugins(List.of(stablePluginZip), env.v1());
assertPlugin("stable1", pluginDir, env.v2()); assertPlugin("stable1", pluginDir, env.v2());
assertNamedComponentFile("stable1", env.v2().pluginsFile(), namedComponentsJSON()); assertNamedComponentFile("stable1", env.v2().pluginsDir(), namedComponentsJSON());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -1577,7 +1577,7 @@ public class InstallPluginActionTests extends ESTestCase {
installPlugins(List.of(stablePluginZip), env.v1()); installPlugins(List.of(stablePluginZip), env.v1());
assertPlugin("stable1", pluginDir, env.v2()); assertPlugin("stable1", pluginDir, env.v2());
assertNamedComponentFile("stable1", env.v2().pluginsFile(), namedComponentsJSON()); assertNamedComponentFile("stable1", env.v2().pluginsDir(), namedComponentsJSON());
} }
public void testGetSemanticVersion() { public void testGetSemanticVersion() {

View file

@ -65,7 +65,7 @@ public class ListPluginsCommandTests extends CommandTestCase {
final boolean hasNativeController final boolean hasNativeController
) throws IOException { ) throws IOException {
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
env.pluginsFile().resolve(name), env.pluginsDir().resolve(name),
"description", "description",
description, description,
"name", "name",
@ -84,9 +84,9 @@ public class ListPluginsCommandTests extends CommandTestCase {
} }
public void testPluginsDirMissing() throws Exception { public void testPluginsDirMissing() throws Exception {
Files.delete(env.pluginsFile()); Files.delete(env.pluginsDir());
IOException e = expectThrows(IOException.class, () -> execute()); IOException e = expectThrows(IOException.class, () -> execute());
assertEquals("Plugins directory missing: " + env.pluginsFile(), e.getMessage()); assertEquals("Plugins directory missing: " + env.pluginsDir(), e.getMessage());
} }
public void testNoPlugins() throws Exception { public void testNoPlugins() throws Exception {
@ -112,7 +112,7 @@ public class ListPluginsCommandTests extends CommandTestCase {
execute("-v"); execute("-v");
assertEquals( assertEquals(
buildMultiline( buildMultiline(
"Plugins directory: " + env.pluginsFile(), "Plugins directory: " + env.pluginsDir(),
"fake_plugin", "fake_plugin",
"- Plugin information:", "- Plugin information:",
"Name: fake_plugin", "Name: fake_plugin",
@ -134,7 +134,7 @@ public class ListPluginsCommandTests extends CommandTestCase {
execute("-v"); execute("-v");
assertEquals( assertEquals(
buildMultiline( buildMultiline(
"Plugins directory: " + env.pluginsFile(), "Plugins directory: " + env.pluginsDir(),
"fake_plugin1", "fake_plugin1",
"- Plugin information:", "- Plugin information:",
"Name: fake_plugin1", "Name: fake_plugin1",
@ -157,7 +157,7 @@ public class ListPluginsCommandTests extends CommandTestCase {
execute("-v"); execute("-v");
assertEquals( assertEquals(
buildMultiline( buildMultiline(
"Plugins directory: " + env.pluginsFile(), "Plugins directory: " + env.pluginsDir(),
"fake_plugin1", "fake_plugin1",
"- Plugin information:", "- Plugin information:",
"Name: fake_plugin1", "Name: fake_plugin1",
@ -193,14 +193,14 @@ public class ListPluginsCommandTests extends CommandTestCase {
} }
public void testPluginWithoutDescriptorFile() throws Exception { public void testPluginWithoutDescriptorFile() throws Exception {
final Path pluginDir = env.pluginsFile().resolve("fake1"); final Path pluginDir = env.pluginsDir().resolve("fake1");
Files.createDirectories(pluginDir); Files.createDirectories(pluginDir);
var e = expectThrows(IllegalStateException.class, () -> execute()); var e = expectThrows(IllegalStateException.class, () -> execute());
assertThat(e.getMessage(), equalTo("Plugin [fake1] is missing a descriptor properties file.")); assertThat(e.getMessage(), equalTo("Plugin [fake1] is missing a descriptor properties file."));
} }
public void testPluginWithWrongDescriptorFile() throws Exception { public void testPluginWithWrongDescriptorFile() throws Exception {
final Path pluginDir = env.pluginsFile().resolve("fake1"); final Path pluginDir = env.pluginsDir().resolve("fake1");
PluginTestUtil.writePluginProperties(pluginDir, "description", "fake desc"); PluginTestUtil.writePluginProperties(pluginDir, "description", "fake desc");
var e = expectThrows(IllegalArgumentException.class, () -> execute()); var e = expectThrows(IllegalArgumentException.class, () -> execute());
assertThat(e.getMessage(), startsWith("property [name] is missing for plugin")); assertThat(e.getMessage(), startsWith("property [name] is missing for plugin"));
@ -208,7 +208,7 @@ public class ListPluginsCommandTests extends CommandTestCase {
public void testExistingIncompatiblePlugin() throws Exception { public void testExistingIncompatiblePlugin() throws Exception {
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
env.pluginsFile().resolve("fake_plugin1"), env.pluginsDir().resolve("fake_plugin1"),
"description", "description",
"fake desc 1", "fake desc 1",
"name", "name",

View file

@ -58,11 +58,11 @@ public class RemovePluginActionTests extends ESTestCase {
} }
void createPlugin(String name) throws IOException { void createPlugin(String name) throws IOException {
createPlugin(env.pluginsFile(), name, Version.CURRENT); createPlugin(env.pluginsDir(), name, Version.CURRENT);
} }
void createPlugin(String name, Version version) throws IOException { void createPlugin(String name, Version version) throws IOException {
createPlugin(env.pluginsFile(), name, version); createPlugin(env.pluginsDir(), name, version);
} }
void createPlugin(Path path, String name, Version version) throws IOException { void createPlugin(Path path, String name, Version version) throws IOException {
@ -98,7 +98,7 @@ public class RemovePluginActionTests extends ESTestCase {
} }
static void assertRemoveCleaned(Environment env) throws IOException { static void assertRemoveCleaned(Environment env) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(env.pluginsFile())) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(env.pluginsDir())) {
for (Path file : stream) { for (Path file : stream) {
if (file.getFileName().toString().startsWith(".removing")) { if (file.getFileName().toString().startsWith(".removing")) {
fail("Removal dir still exists, " + file); fail("Removal dir still exists, " + file);
@ -115,84 +115,84 @@ public class RemovePluginActionTests extends ESTestCase {
public void testBasic() throws Exception { public void testBasic() throws Exception {
createPlugin("fake"); createPlugin("fake");
Files.createFile(env.pluginsFile().resolve("fake").resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve("fake").resolve("plugin.jar"));
Files.createDirectory(env.pluginsFile().resolve("fake").resolve("subdir")); Files.createDirectory(env.pluginsDir().resolve("fake").resolve("subdir"));
createPlugin("other"); createPlugin("other");
removePlugin("fake", home, randomBoolean()); removePlugin("fake", home, randomBoolean());
assertFalse(Files.exists(env.pluginsFile().resolve("fake"))); assertFalse(Files.exists(env.pluginsDir().resolve("fake")));
assertTrue(Files.exists(env.pluginsFile().resolve("other"))); assertTrue(Files.exists(env.pluginsDir().resolve("other")));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
/** Check that multiple plugins can be removed at the same time. */ /** Check that multiple plugins can be removed at the same time. */
public void testRemoveMultiple() throws Exception { public void testRemoveMultiple() throws Exception {
createPlugin("fake"); createPlugin("fake");
Files.createFile(env.pluginsFile().resolve("fake").resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve("fake").resolve("plugin.jar"));
Files.createDirectory(env.pluginsFile().resolve("fake").resolve("subdir")); Files.createDirectory(env.pluginsDir().resolve("fake").resolve("subdir"));
createPlugin("other"); createPlugin("other");
Files.createFile(env.pluginsFile().resolve("other").resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve("other").resolve("plugin.jar"));
Files.createDirectory(env.pluginsFile().resolve("other").resolve("subdir")); Files.createDirectory(env.pluginsDir().resolve("other").resolve("subdir"));
removePlugin("fake", home, randomBoolean()); removePlugin("fake", home, randomBoolean());
removePlugin("other", home, randomBoolean()); removePlugin("other", home, randomBoolean());
assertFalse(Files.exists(env.pluginsFile().resolve("fake"))); assertFalse(Files.exists(env.pluginsDir().resolve("fake")));
assertFalse(Files.exists(env.pluginsFile().resolve("other"))); assertFalse(Files.exists(env.pluginsDir().resolve("other")));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
public void testBin() throws Exception { public void testBin() throws Exception {
createPlugin("fake"); createPlugin("fake");
Path binDir = env.binFile().resolve("fake"); Path binDir = env.binDir().resolve("fake");
Files.createDirectories(binDir); Files.createDirectories(binDir);
Files.createFile(binDir.resolve("somescript")); Files.createFile(binDir.resolve("somescript"));
removePlugin("fake", home, randomBoolean()); removePlugin("fake", home, randomBoolean());
assertFalse(Files.exists(env.pluginsFile().resolve("fake"))); assertFalse(Files.exists(env.pluginsDir().resolve("fake")));
assertTrue(Files.exists(env.binFile().resolve("elasticsearch"))); assertTrue(Files.exists(env.binDir().resolve("elasticsearch")));
assertFalse(Files.exists(binDir)); assertFalse(Files.exists(binDir));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
public void testBinNotDir() throws Exception { public void testBinNotDir() throws Exception {
createPlugin("fake"); createPlugin("fake");
Files.createFile(env.binFile().resolve("fake")); Files.createFile(env.binDir().resolve("fake"));
UserException e = expectThrows(UserException.class, () -> removePlugin("fake", home, randomBoolean())); UserException e = expectThrows(UserException.class, () -> removePlugin("fake", home, randomBoolean()));
assertThat(e.getMessage(), containsString("not a directory")); assertThat(e.getMessage(), containsString("not a directory"));
assertTrue(Files.exists(env.pluginsFile().resolve("fake"))); // did not remove assertTrue(Files.exists(env.pluginsDir().resolve("fake"))); // did not remove
assertTrue(Files.exists(env.binFile().resolve("fake"))); assertTrue(Files.exists(env.binDir().resolve("fake")));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
public void testConfigDirPreserved() throws Exception { public void testConfigDirPreserved() throws Exception {
createPlugin("fake"); createPlugin("fake");
final Path configDir = env.configFile().resolve("fake"); final Path configDir = env.configDir().resolve("fake");
Files.createDirectories(configDir); Files.createDirectories(configDir);
Files.createFile(configDir.resolve("fake.yml")); Files.createFile(configDir.resolve("fake.yml"));
final MockTerminal terminal = removePlugin("fake", home, false); final MockTerminal terminal = removePlugin("fake", home, false);
assertTrue(Files.exists(env.configFile().resolve("fake"))); assertTrue(Files.exists(env.configDir().resolve("fake")));
assertThat(terminal.getOutput(), containsString(expectedConfigDirPreservedMessage(configDir))); assertThat(terminal.getOutput(), containsString(expectedConfigDirPreservedMessage(configDir)));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
public void testPurgePluginExists() throws Exception { public void testPurgePluginExists() throws Exception {
createPlugin("fake"); createPlugin("fake");
final Path configDir = env.configFile().resolve("fake"); final Path configDir = env.configDir().resolve("fake");
if (randomBoolean()) { if (randomBoolean()) {
Files.createDirectories(configDir); Files.createDirectories(configDir);
Files.createFile(configDir.resolve("fake.yml")); Files.createFile(configDir.resolve("fake.yml"));
} }
final MockTerminal terminal = removePlugin("fake", home, true); final MockTerminal terminal = removePlugin("fake", home, true);
assertFalse(Files.exists(env.configFile().resolve("fake"))); assertFalse(Files.exists(env.configDir().resolve("fake")));
assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir)))); assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir))));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
public void testPurgePluginDoesNotExist() throws Exception { public void testPurgePluginDoesNotExist() throws Exception {
final Path configDir = env.configFile().resolve("fake"); final Path configDir = env.configDir().resolve("fake");
Files.createDirectories(configDir); Files.createDirectories(configDir);
Files.createFile(configDir.resolve("fake.yml")); Files.createFile(configDir.resolve("fake.yml"));
final MockTerminal terminal = removePlugin("fake", home, true); final MockTerminal terminal = removePlugin("fake", home, true);
assertFalse(Files.exists(env.configFile().resolve("fake"))); assertFalse(Files.exists(env.configDir().resolve("fake")));
assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir)))); assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir))));
assertRemoveCleaned(env); assertRemoveCleaned(env);
} }
@ -203,8 +203,8 @@ public class RemovePluginActionTests extends ESTestCase {
} }
public void testPurgeOnlyMarkerFileExists() throws Exception { public void testPurgeOnlyMarkerFileExists() throws Exception {
final Path configDir = env.configFile().resolve("fake"); final Path configDir = env.configDir().resolve("fake");
final Path removing = env.pluginsFile().resolve(".removing-fake"); final Path removing = env.pluginsDir().resolve(".removing-fake");
Files.createFile(removing); Files.createFile(removing);
final MockTerminal terminal = removePlugin("fake", home, randomBoolean()); final MockTerminal terminal = removePlugin("fake", home, randomBoolean());
assertFalse(Files.exists(removing)); assertFalse(Files.exists(removing));
@ -213,7 +213,7 @@ public class RemovePluginActionTests extends ESTestCase {
public void testNoConfigDirPreserved() throws Exception { public void testNoConfigDirPreserved() throws Exception {
createPlugin("fake"); createPlugin("fake");
final Path configDir = env.configFile().resolve("fake"); final Path configDir = env.configDir().resolve("fake");
final MockTerminal terminal = removePlugin("fake", home, randomBoolean()); final MockTerminal terminal = removePlugin("fake", home, randomBoolean());
assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir)))); assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir))));
} }
@ -250,8 +250,8 @@ public class RemovePluginActionTests extends ESTestCase {
public void testRemoveWhenRemovingMarker() throws Exception { public void testRemoveWhenRemovingMarker() throws Exception {
createPlugin("fake"); createPlugin("fake");
Files.createFile(env.pluginsFile().resolve("fake").resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve("fake").resolve("plugin.jar"));
Files.createFile(env.pluginsFile().resolve(".removing-fake")); Files.createFile(env.pluginsDir().resolve(".removing-fake"));
removePlugin("fake", home, randomBoolean()); removePlugin("fake", home, randomBoolean());
} }
@ -262,10 +262,10 @@ public class RemovePluginActionTests extends ESTestCase {
public void testRemoveMigratedPluginsWhenInstalled() throws Exception { public void testRemoveMigratedPluginsWhenInstalled() throws Exception {
for (String id : List.of("repository-azure", "repository-gcs", "repository-s3")) { for (String id : List.of("repository-azure", "repository-gcs", "repository-s3")) {
createPlugin(id); createPlugin(id);
Files.createFile(env.pluginsFile().resolve(id).resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve(id).resolve("plugin.jar"));
final MockTerminal terminal = removePlugin(id, home, randomBoolean()); final MockTerminal terminal = removePlugin(id, home, randomBoolean());
assertThat(Files.exists(env.pluginsFile().resolve(id)), is(false)); assertThat(Files.exists(env.pluginsDir().resolve(id)), is(false));
// This message shouldn't be printed if plugin was actually installed. // This message shouldn't be printed if plugin was actually installed.
assertThat(terminal.getErrorOutput(), not(containsString("plugin [" + id + "] is no longer a plugin"))); assertThat(terminal.getErrorOutput(), not(containsString("plugin [" + id + "] is no longer a plugin")));
} }
@ -288,11 +288,11 @@ public class RemovePluginActionTests extends ESTestCase {
*/ */
public void testRemoveRegularInstalledPluginAndMigratedUninstalledPlugin() throws Exception { public void testRemoveRegularInstalledPluginAndMigratedUninstalledPlugin() throws Exception {
createPlugin("fake"); createPlugin("fake");
Files.createFile(env.pluginsFile().resolve("fake").resolve("plugin.jar")); Files.createFile(env.pluginsDir().resolve("fake").resolve("plugin.jar"));
final MockTerminal terminal = removePlugin(List.of("fake", "repository-s3"), home, randomBoolean()); final MockTerminal terminal = removePlugin(List.of("fake", "repository-s3"), home, randomBoolean());
assertThat(Files.exists(env.pluginsFile().resolve("fake")), is(false)); assertThat(Files.exists(env.pluginsDir().resolve("fake")), is(false));
assertThat(terminal.getErrorOutput(), containsString("plugin [repository-s3] is no longer a plugin")); assertThat(terminal.getErrorOutput(), containsString("plugin [repository-s3] is no longer a plugin"));
} }

View file

@ -55,10 +55,10 @@ public class SyncPluginsActionTests extends ESTestCase {
Path home = createTempDir(); Path home = createTempDir();
Settings settings = Settings.builder().put("path.home", home).build(); Settings settings = Settings.builder().put("path.home", home).build();
env = TestEnvironment.newEnvironment(settings); env = TestEnvironment.newEnvironment(settings);
Files.createDirectories(env.binFile()); Files.createDirectories(env.binDir());
Files.createFile(env.binFile().resolve("elasticsearch")); Files.createFile(env.binDir().resolve("elasticsearch"));
Files.createDirectories(env.configFile()); Files.createDirectories(env.configDir());
Files.createDirectories(env.pluginsFile()); Files.createDirectories(env.pluginsDir());
terminal = MockTerminal.create(); terminal = MockTerminal.create();
action = new SyncPluginsAction(terminal, env); action = new SyncPluginsAction(terminal, env);
@ -78,7 +78,7 @@ public class SyncPluginsActionTests extends ESTestCase {
* then an exception is thrown. * then an exception is thrown.
*/ */
public void test_ensureNoConfigFile_withConfig_throwsException() throws Exception { public void test_ensureNoConfigFile_withConfig_throwsException() throws Exception {
Files.createFile(env.configFile().resolve("elasticsearch-plugins.yml")); Files.createFile(env.configDir().resolve("elasticsearch-plugins.yml"));
final UserException e = expectThrows(UserException.class, () -> SyncPluginsAction.ensureNoConfigFile(env)); final UserException e = expectThrows(UserException.class, () -> SyncPluginsAction.ensureNoConfigFile(env));
assertThat(e.getMessage(), Matchers.matchesPattern("^Plugins config \\[.*] exists.*$")); assertThat(e.getMessage(), Matchers.matchesPattern("^Plugins config \\[.*] exists.*$"));
@ -354,7 +354,7 @@ public class SyncPluginsActionTests extends ESTestCase {
private void createPlugin(String name, String version) throws IOException { private void createPlugin(String name, String version) throws IOException {
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
env.pluginsFile().resolve(name), env.pluginsDir().resolve(name),
"description", "description",
"dummy", "dummy",
"name", "name",

View file

@ -24,7 +24,7 @@ public class KeyStoreLoader implements SecureSettingsLoader {
@Override @Override
public LoadedSecrets load(Environment environment, Terminal terminal) throws Exception { public LoadedSecrets load(Environment environment, Terminal terminal) throws Exception {
// See if we have a keystore already present // See if we have a keystore already present
KeyStoreWrapper secureSettings = KeyStoreWrapper.load(environment.configFile()); KeyStoreWrapper secureSettings = KeyStoreWrapper.load(environment.configDir());
// If there's no keystore or the keystore has no password, set an empty password // If there's no keystore or the keystore has no password, set an empty password
var password = (secureSettings == null || secureSettings.hasPassword() == false) var password = (secureSettings == null || secureSettings.hasPassword() == false)
? new SecureString(new char[0]) ? new SecureString(new char[0])
@ -35,7 +35,7 @@ public class KeyStoreLoader implements SecureSettingsLoader {
@Override @Override
public SecureSettings bootstrap(Environment environment, SecureString password) throws Exception { public SecureSettings bootstrap(Environment environment, SecureString password) throws Exception {
return KeyStoreWrapper.bootstrap(environment.configFile(), () -> password); return KeyStoreWrapper.bootstrap(environment.configDir(), () -> password);
} }
@Override @Override

View file

@ -150,7 +150,7 @@ class ServerCli extends EnvironmentAwareCommand {
throw new UserException(ExitCodes.USAGE, "Multiple --enrollment-token parameters are not allowed"); throw new UserException(ExitCodes.USAGE, "Multiple --enrollment-token parameters are not allowed");
} }
Path log4jConfig = env.configFile().resolve("log4j2.properties"); Path log4jConfig = env.configDir().resolve("log4j2.properties");
if (Files.exists(log4jConfig) == false) { if (Files.exists(log4jConfig) == false) {
throw new UserException(ExitCodes.CONFIG, "Missing logging config file at " + log4jConfig); throw new UserException(ExitCodes.CONFIG, "Missing logging config file at " + log4jConfig);
} }
@ -239,7 +239,7 @@ class ServerCli extends EnvironmentAwareCommand {
} }
validatePidFile(pidFile); validatePidFile(pidFile);
} }
return new ServerArgs(daemonize, quiet, pidFile, secrets, env.settings(), env.configFile(), env.logsFile()); return new ServerArgs(daemonize, quiet, pidFile, secrets, env.settings(), env.configDir(), env.logsDir());
} }
@Override @Override

View file

@ -43,8 +43,8 @@ class WindowsServiceDaemon extends EnvironmentAwareCommand {
@Override @Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception { public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
// the Windows service daemon doesn't support secure settings implementations other than the keystore // the Windows service daemon doesn't support secure settings implementations other than the keystore
try (var loadedSecrets = KeyStoreWrapper.bootstrap(env.configFile(), () -> new SecureString(new char[0]))) { try (var loadedSecrets = KeyStoreWrapper.bootstrap(env.configDir(), () -> new SecureString(new char[0]))) {
var args = new ServerArgs(false, true, null, loadedSecrets, env.settings(), env.configFile(), env.logsFile()); var args = new ServerArgs(false, true, null, loadedSecrets, env.settings(), env.configDir(), env.logsDir());
var tempDir = ServerProcessUtils.setupTempDir(processInfo); var tempDir = ServerProcessUtils.setupTempDir(processInfo);
var jvmOptions = JvmOptionsParser.determineJvmOptions(args, processInfo, tempDir, new MachineDependentHeap()); var jvmOptions = JvmOptionsParser.determineJvmOptions(args, processInfo, tempDir, new MachineDependentHeap());
var serverProcessBuilder = new ServerProcessBuilder().withTerminal(terminal) var serverProcessBuilder = new ServerProcessBuilder().withTerminal(terminal)

View file

@ -207,7 +207,7 @@ public class ReloadAnalyzerTests extends ESSingleNodeTestCase {
public void testUpdateableSynonymsRejectedAtIndexTime() throws FileNotFoundException, IOException { public void testUpdateableSynonymsRejectedAtIndexTime() throws FileNotFoundException, IOException {
String synonymsFileName = "synonyms.txt"; String synonymsFileName = "synonyms.txt";
setupResourceFile(synonymsFileName, "foo, baz"); setupResourceFile(synonymsFileName, "foo, baz");
Path configDir = node().getEnvironment().configFile(); Path configDir = node().getEnvironment().configDir();
if (Files.exists(configDir) == false) { if (Files.exists(configDir) == false) {
Files.createDirectory(configDir); Files.createDirectory(configDir);
} }
@ -319,7 +319,7 @@ public class ReloadAnalyzerTests extends ESSingleNodeTestCase {
} }
private Path setupResourceFile(String fileName, String... content) throws IOException { private Path setupResourceFile(String fileName, String... content) throws IOException {
Path configDir = node().getEnvironment().configFile(); Path configDir = node().getEnvironment().configDir();
if (Files.exists(configDir) == false) { if (Files.exists(configDir) == false) {
Files.createDirectory(configDir); Files.createDirectory(configDir);
} }

View file

@ -57,7 +57,7 @@ public class ReloadSynonymAnalyzerIT extends ESIntegTestCase {
} }
private void testSynonymsUpdate(boolean preview) throws FileNotFoundException, IOException, InterruptedException { private void testSynonymsUpdate(boolean preview) throws FileNotFoundException, IOException, InterruptedException {
Path config = internalCluster().getInstance(Environment.class).configFile(); Path config = internalCluster().getInstance(Environment.class).configDir();
String synonymsFileName = "synonyms.txt"; String synonymsFileName = "synonyms.txt";
Path synonymsFile = config.resolve(synonymsFileName); Path synonymsFile = config.resolve(synonymsFileName);
writeFile(synonymsFile, "foo, baz"); writeFile(synonymsFile, "foo, baz");
@ -106,7 +106,7 @@ public class ReloadSynonymAnalyzerIT extends ESIntegTestCase {
final String synonymsFileName = "synonyms.txt"; final String synonymsFileName = "synonyms.txt";
final String fieldName = "field"; final String fieldName = "field";
Path config = internalCluster().getInstance(Environment.class).configFile(); Path config = internalCluster().getInstance(Environment.class).configDir();
Path synonymsFile = config.resolve(synonymsFileName); Path synonymsFile = config.resolve(synonymsFileName);
writeFile(synonymsFile, "foo, baz"); writeFile(synonymsFile, "foo, baz");

View file

@ -40,7 +40,7 @@ public class HyphenationCompoundWordTokenFilterFactory extends AbstractCompoundW
throw new IllegalArgumentException("hyphenation_patterns_path is a required setting."); throw new IllegalArgumentException("hyphenation_patterns_path is a required setting.");
} }
Path hyphenationPatternsFile = env.configFile().resolve(hyphenationPatternsPath); Path hyphenationPatternsFile = env.configDir().resolve(hyphenationPatternsPath);
try { try {
InputStream in = Files.newInputStream(hyphenationPatternsFile); InputStream in = Files.newInputStream(hyphenationPatternsFile);

View file

@ -248,7 +248,7 @@ public class DataStreamGetWriteIndexTests extends ESTestCase {
MetadataCreateIndexService createIndexService; MetadataCreateIndexService createIndexService;
{ {
Environment env = mock(Environment.class); Environment env = mock(Environment.class);
when(env.sharedDataFile()).thenReturn(null); when(env.sharedDataDir()).thenReturn(null);
AllocationService allocationService = mock(AllocationService.class); AllocationService allocationService = mock(AllocationService.class);
when(allocationService.reroute(any(ClusterState.class), any(String.class), any())).then(i -> i.getArguments()[0]); when(allocationService.reroute(any(ClusterState.class), any(String.class), any())).then(i -> i.getArguments()[0]);
when(allocationService.getShardRoutingRoleStrategy()).thenReturn(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY); when(allocationService.getShardRoutingRoleStrategy()).thenReturn(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY);

View file

@ -664,7 +664,7 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
.map(DiscoveryNode::getId) .map(DiscoveryNode::getId)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
// All nodes share the same geoip base dir in the shared tmp dir: // All nodes share the same geoip base dir in the shared tmp dir:
Path geoipBaseTmpDir = internalCluster().getDataNodeInstance(Environment.class).tmpFile().resolve("geoip-databases"); Path geoipBaseTmpDir = internalCluster().getDataNodeInstance(Environment.class).tmpDir().resolve("geoip-databases");
assertThat(Files.exists(geoipBaseTmpDir), is(true)); assertThat(Files.exists(geoipBaseTmpDir), is(true));
final List<Path> geoipTmpDirs; final List<Path> geoipTmpDirs;
try (Stream<Path> files = Files.list(geoipBaseTmpDir)) { try (Stream<Path> files = Files.list(geoipBaseTmpDir)) {
@ -676,7 +676,7 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
private void setupDatabasesInConfigDirectory() throws Exception { private void setupDatabasesInConfigDirectory() throws Exception {
StreamSupport.stream(internalCluster().getInstances(Environment.class).spliterator(), false) StreamSupport.stream(internalCluster().getInstances(Environment.class).spliterator(), false)
.map(Environment::configFile) .map(Environment::configDir)
.map(path -> path.resolve("ingest-geoip")) .map(path -> path.resolve("ingest-geoip"))
.distinct() .distinct()
.forEach(path -> { .forEach(path -> {
@ -704,7 +704,7 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT {
private void deleteDatabasesInConfigDirectory() throws Exception { private void deleteDatabasesInConfigDirectory() throws Exception {
StreamSupport.stream(internalCluster().getInstances(Environment.class).spliterator(), false) StreamSupport.stream(internalCluster().getInstances(Environment.class).spliterator(), false)
.map(Environment::configFile) .map(Environment::configDir)
.map(path -> path.resolve("ingest-geoip")) .map(path -> path.resolve("ingest-geoip"))
.distinct() .distinct()
.forEach(path -> { .forEach(path -> {

View file

@ -42,7 +42,7 @@ final class ConfigDatabases implements Closeable {
private final ConcurrentMap<String, DatabaseReaderLazyLoader> configDatabases; private final ConcurrentMap<String, DatabaseReaderLazyLoader> configDatabases;
ConfigDatabases(Environment environment, GeoIpCache cache) { ConfigDatabases(Environment environment, GeoIpCache cache) {
this(environment.configFile().resolve("ingest-geoip"), cache); this(environment.configDir().resolve("ingest-geoip"), cache);
} }
ConfigDatabases(Path geoipConfigDir, GeoIpCache cache) { ConfigDatabases(Path geoipConfigDir, GeoIpCache cache) {

View file

@ -114,7 +114,7 @@ public final class DatabaseNodeService implements IpDatabaseProvider {
ClusterService clusterService ClusterService clusterService
) { ) {
this( this(
environment.tmpFile(), environment.tmpDir(),
new OriginSettingClient(client, IngestService.INGEST_ORIGIN), new OriginSettingClient(client, IngestService.INGEST_ORIGIN),
cache, cache,
new ConfigDatabases(environment, cache), new ConfigDatabases(environment, cache),

View file

@ -41,7 +41,7 @@ public class IngestUserAgentPlugin extends Plugin implements IngestPlugin {
@Override @Override
public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) { public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
Path userAgentConfigDirectory = parameters.env.configFile().resolve("ingest-user-agent"); Path userAgentConfigDirectory = parameters.env.configDir().resolve("ingest-user-agent");
if (Files.exists(userAgentConfigDirectory) == false && Files.isDirectory(userAgentConfigDirectory)) { if (Files.exists(userAgentConfigDirectory) == false && Files.isDirectory(userAgentConfigDirectory)) {
throw new IllegalStateException( throw new IllegalStateException(

View file

@ -106,7 +106,7 @@ public class ReindexSslConfig {
return settings.getAsList(key); return settings.getAsList(key);
} }
}; };
configuration = loader.load(environment.configFile()); configuration = loader.load(environment.configDir());
reload(); reload();
final FileChangesListener listener = new FileChangesListener() { final FileChangesListener listener = new FileChangesListener() {

View file

@ -369,7 +369,7 @@ class S3Service implements Closeable {
} }
// Make sure that a readable symlink to the token file exists in the plugin config directory // Make sure that a readable symlink to the token file exists in the plugin config directory
// AWS_WEB_IDENTITY_TOKEN_FILE exists but we only use Web Identity Tokens if a corresponding symlink exists and is readable // AWS_WEB_IDENTITY_TOKEN_FILE exists but we only use Web Identity Tokens if a corresponding symlink exists and is readable
Path webIdentityTokenFileSymlink = environment.configFile().resolve(WEB_IDENTITY_TOKEN_FILE_LOCATION); Path webIdentityTokenFileSymlink = environment.configDir().resolve(WEB_IDENTITY_TOKEN_FILE_LOCATION);
if (Files.exists(webIdentityTokenFileSymlink) == false) { if (Files.exists(webIdentityTokenFileSymlink) == false) {
LOGGER.warn( LOGGER.warn(
"Cannot use AWS Web Identity Tokens: AWS_WEB_IDENTITY_TOKEN_FILE is defined but no corresponding symlink exists " "Cannot use AWS Web Identity Tokens: AWS_WEB_IDENTITY_TOKEN_FILE is defined but no corresponding symlink exists "

View file

@ -65,7 +65,7 @@ public class CustomWebIdentityTokenCredentialsProviderTests extends ESTestCase {
Files.createDirectory(configDirectory.resolve("repository-s3")); Files.createDirectory(configDirectory.resolve("repository-s3"));
Files.writeString(configDirectory.resolve("repository-s3/aws-web-identity-token-file"), "YXdzLXdlYi1pZGVudGl0eS10b2tlbi1maWxl"); Files.writeString(configDirectory.resolve("repository-s3/aws-web-identity-token-file"), "YXdzLXdlYi1pZGVudGl0eS10b2tlbi1maWxl");
Environment environment = Mockito.mock(Environment.class); Environment environment = Mockito.mock(Environment.class);
Mockito.when(environment.configFile()).thenReturn(configDirectory); Mockito.when(environment.configDir()).thenReturn(configDirectory);
return environment; return environment;
} }
@ -212,7 +212,7 @@ public class CustomWebIdentityTokenCredentialsProviderTests extends ESTestCase {
latch.countDown(); latch.countDown();
} }
}); });
Files.writeString(environment.configFile().resolve("repository-s3/aws-web-identity-token-file"), newWebIdentityToken); Files.writeString(environment.configDir().resolve("repository-s3/aws-web-identity-token-file"), newWebIdentityToken);
safeAwait(latch); safeAwait(latch);
assertCredentials(awsCredentialsProvider.getCredentials()); assertCredentials(awsCredentialsProvider.getCredentials());

View file

@ -158,7 +158,7 @@ public class URLRepository extends BlobStoreRepository {
if (normalizedUrl == null) { if (normalizedUrl == null) {
String logMessage = "The specified url [{}] doesn't start with any repository paths specified by the " String logMessage = "The specified url [{}] doesn't start with any repository paths specified by the "
+ "path.repo setting or by {} setting: [{}] "; + "path.repo setting or by {} setting: [{}] ";
logger.warn(logMessage, urlToCheck, ALLOWED_URLS_SETTING.getKey(), environment.repoFiles()); logger.warn(logMessage, urlToCheck, ALLOWED_URLS_SETTING.getKey(), environment.repoDirs());
String exceptionMessage = "file url [" String exceptionMessage = "file url ["
+ urlToCheck + urlToCheck
+ "] doesn't match any of the locations specified by path.repo or " + "] doesn't match any of the locations specified by path.repo or "

View file

@ -51,7 +51,7 @@ public class IcuCollationTokenFilterFactory extends AbstractTokenFilterFactory {
if (rules != null) { if (rules != null) {
Exception failureToResolve = null; Exception failureToResolve = null;
try { try {
rules = Streams.copyToString(Files.newBufferedReader(environment.configFile().resolve(rules), Charset.forName("UTF-8"))); rules = Streams.copyToString(Files.newBufferedReader(environment.configDir().resolve(rules), Charset.forName("UTF-8")));
} catch (IOException | SecurityException | InvalidPathException e) { } catch (IOException | SecurityException | InvalidPathException e) {
failureToResolve = e; failureToResolve = e;
} }

View file

@ -99,7 +99,7 @@ public class IcuTokenizerFactory extends AbstractTokenizerFactory {
// parse a single RBBi rule file // parse a single RBBi rule file
private static BreakIterator parseRules(String filename, Environment env) throws IOException { private static BreakIterator parseRules(String filename, Environment env) throws IOException {
final Path path = env.configFile().resolve(filename); final Path path = env.configDir().resolve(filename);
String rules = Files.readAllLines(path).stream().filter((v) -> v.startsWith("#") == false).collect(Collectors.joining("\n")); String rules = Files.readAllLines(path).stream().filter((v) -> v.startsWith("#") == false).collect(Collectors.joining("\n"));
return new RuleBasedBreakIterator(rules.toString()); return new RuleBasedBreakIterator(rules.toString());

View file

@ -81,7 +81,7 @@ class HdfsSecurityContext {
* Expects keytab file to exist at {@code $CONFIG_DIR$/repository-hdfs/krb5.keytab} * Expects keytab file to exist at {@code $CONFIG_DIR$/repository-hdfs/krb5.keytab}
*/ */
static Path locateKeytabFile(Environment environment) { static Path locateKeytabFile(Environment environment) {
Path keytabPath = environment.configFile().resolve("repository-hdfs").resolve("krb5.keytab"); Path keytabPath = environment.configDir().resolve("repository-hdfs").resolve("krb5.keytab");
try { try {
if (Files.exists(keytabPath) == false) { if (Files.exists(keytabPath) == false) {
throw new RuntimeException("Could not locate keytab at [" + keytabPath + "]."); throw new RuntimeException("Could not locate keytab at [" + keytabPath + "].");

View file

@ -103,23 +103,23 @@ public class EvilSecurityTests extends ESTestCase {
// check that all directories got permissions: // check that all directories got permissions:
// bin file: ro // bin file: ro
assertExactPermissions(new FilePermission(environment.binFile().toString(), "read,readlink"), permissions); assertExactPermissions(new FilePermission(environment.binDir().toString(), "read,readlink"), permissions);
// lib file: ro // lib file: ro
assertExactPermissions(new FilePermission(environment.libFile().toString(), "read,readlink"), permissions); assertExactPermissions(new FilePermission(environment.libDir().toString(), "read,readlink"), permissions);
// modules file: ro // modules file: ro
assertExactPermissions(new FilePermission(environment.modulesFile().toString(), "read,readlink"), permissions); assertExactPermissions(new FilePermission(environment.modulesDir().toString(), "read,readlink"), permissions);
// config file: ro // config file: ro
assertExactPermissions(new FilePermission(environment.configFile().toString(), "read,readlink"), permissions); assertExactPermissions(new FilePermission(environment.configDir().toString(), "read,readlink"), permissions);
// plugins: ro // plugins: ro
assertExactPermissions(new FilePermission(environment.pluginsFile().toString(), "read,readlink"), permissions); assertExactPermissions(new FilePermission(environment.pluginsDir().toString(), "read,readlink"), permissions);
// data paths: r/w // data paths: r/w
for (Path dataPath : environment.dataFiles()) { for (Path dataPath : environment.dataDirs()) {
assertExactPermissions(new FilePermission(dataPath.toString(), "read,readlink,write,delete"), permissions); assertExactPermissions(new FilePermission(dataPath.toString(), "read,readlink,write,delete"), permissions);
} }
assertExactPermissions(new FilePermission(environment.sharedDataFile().toString(), "read,readlink,write,delete"), permissions); assertExactPermissions(new FilePermission(environment.sharedDataDir().toString(), "read,readlink,write,delete"), permissions);
// logs: r/w // logs: r/w
assertExactPermissions(new FilePermission(environment.logsFile().toString(), "read,readlink,write,delete"), permissions); assertExactPermissions(new FilePermission(environment.logsDir().toString(), "read,readlink,write,delete"), permissions);
// temp dir: r/w // temp dir: r/w
assertExactPermissions(new FilePermission(fakeTmpDir.toString(), "read,readlink,write,delete"), permissions); assertExactPermissions(new FilePermission(fakeTmpDir.toString(), "read,readlink,write,delete"), permissions);
} }

View file

@ -80,8 +80,8 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
Environment environment = TestEnvironment.newEnvironment(settings); Environment environment = TestEnvironment.newEnvironment(settings);
// This plugin will NOT have a controller daemon // This plugin will NOT have a controller daemon
Path plugin = environment.modulesFile().resolve("a_plugin"); Path plugin = environment.modulesDir().resolve("a_plugin");
Files.createDirectories(environment.modulesFile()); Files.createDirectories(environment.modulesDir());
Files.createDirectories(plugin); Files.createDirectories(plugin);
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
plugin, plugin,
@ -111,8 +111,8 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
* Two plugins - one with a controller daemon and one without. * Two plugins - one with a controller daemon and one without.
*/ */
public void testControllerSpawn() throws Exception { public void testControllerSpawn() throws Exception {
assertControllerSpawns(Environment::pluginsFile, false); assertControllerSpawns(Environment::pluginsDir, false);
assertControllerSpawns(Environment::modulesFile, true); assertControllerSpawns(Environment::modulesDir, true);
} }
private void assertControllerSpawns(final Function<Environment, Path> pluginsDirFinder, boolean expectSpawn) throws Exception { private void assertControllerSpawns(final Function<Environment, Path> pluginsDirFinder, boolean expectSpawn) throws Exception {
@ -131,8 +131,8 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
// this plugin will have a controller daemon // this plugin will have a controller daemon
Path plugin = pluginsDirFinder.apply(environment).resolve("test_plugin"); Path plugin = pluginsDirFinder.apply(environment).resolve("test_plugin");
Files.createDirectories(environment.modulesFile()); Files.createDirectories(environment.modulesDir());
Files.createDirectories(environment.pluginsFile()); Files.createDirectories(environment.pluginsDir());
Files.createDirectories(plugin); Files.createDirectories(plugin);
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
plugin, plugin,
@ -217,7 +217,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
Environment environment = TestEnvironment.newEnvironment(settings); Environment environment = TestEnvironment.newEnvironment(settings);
Path plugin = environment.modulesFile().resolve("test_plugin"); Path plugin = environment.modulesDir().resolve("test_plugin");
Files.createDirectories(plugin); Files.createDirectories(plugin);
PluginTestUtil.writePluginProperties( PluginTestUtil.writePluginProperties(
plugin, plugin,
@ -250,10 +250,10 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
final Environment environment = TestEnvironment.newEnvironment(settings); final Environment environment = TestEnvironment.newEnvironment(settings);
Files.createDirectories(environment.modulesFile()); Files.createDirectories(environment.modulesDir());
Files.createDirectories(environment.pluginsFile()); Files.createDirectories(environment.pluginsDir());
final Path desktopServicesStore = environment.modulesFile().resolve(".DS_Store"); final Path desktopServicesStore = environment.modulesDir().resolve(".DS_Store");
Files.createFile(desktopServicesStore); Files.createFile(desktopServicesStore);
final Spawner spawner = new Spawner(); final Spawner spawner = new Spawner();

View file

@ -85,7 +85,7 @@ public class ReloadSecureSettingsIT extends ESIntegTestCase {
final Environment environment = internalCluster().getInstance(Environment.class); final Environment environment = internalCluster().getInstance(Environment.class);
final AtomicReference<AssertionError> reloadSettingsError = new AtomicReference<>(); final AtomicReference<AssertionError> reloadSettingsError = new AtomicReference<>();
// keystore file should be missing for this test case // keystore file should be missing for this test case
Files.deleteIfExists(KeyStoreWrapper.keystorePath(environment.configFile())); Files.deleteIfExists(KeyStoreWrapper.keystorePath(environment.configDir()));
final int initialReloadCount = mockReloadablePlugin.getReloadCount(); final int initialReloadCount = mockReloadablePlugin.getReloadCount();
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
executeReloadSecureSettings(Strings.EMPTY_ARRAY, emptyPassword(), new ActionListener<>() { executeReloadSecureSettings(Strings.EMPTY_ARRAY, emptyPassword(), new ActionListener<>() {
@ -129,10 +129,10 @@ public class ReloadSecureSettingsIT extends ESIntegTestCase {
final int initialReloadCount = mockReloadablePlugin.getReloadCount(); final int initialReloadCount = mockReloadablePlugin.getReloadCount();
// invalid "keystore" file should be present in the config dir // invalid "keystore" file should be present in the config dir
try (InputStream keystore = ReloadSecureSettingsIT.class.getResourceAsStream("invalid.txt.keystore")) { try (InputStream keystore = ReloadSecureSettingsIT.class.getResourceAsStream("invalid.txt.keystore")) {
if (Files.exists(environment.configFile()) == false) { if (Files.exists(environment.configDir()) == false) {
Files.createDirectory(environment.configFile()); Files.createDirectory(environment.configDir());
} }
Files.copy(keystore, KeyStoreWrapper.keystorePath(environment.configFile()), StandardCopyOption.REPLACE_EXISTING); Files.copy(keystore, KeyStoreWrapper.keystorePath(environment.configDir()), StandardCopyOption.REPLACE_EXISTING);
} }
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
executeReloadSecureSettings(Strings.EMPTY_ARRAY, emptyPassword(), new ActionListener<>() { executeReloadSecureSettings(Strings.EMPTY_ARRAY, emptyPassword(), new ActionListener<>() {
@ -363,7 +363,7 @@ public class ReloadSecureSettingsIT extends ESIntegTestCase {
try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) { try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) {
keyStoreWrapper.setString(VALID_SECURE_SETTING_NAME, new char[0]); keyStoreWrapper.setString(VALID_SECURE_SETTING_NAME, new char[0]);
keyStoreWrapper.save(environment.configFile(), new char[0], false); keyStoreWrapper.save(environment.configDir(), new char[0], false);
} }
PlainActionFuture<NodesReloadSecureSettingsResponse> actionFuture = new PlainActionFuture<>(); PlainActionFuture<NodesReloadSecureSettingsResponse> actionFuture = new PlainActionFuture<>();
@ -374,7 +374,7 @@ public class ReloadSecureSettingsIT extends ESIntegTestCase {
try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) { try (KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create()) {
assertThat(keyStoreWrapper, notNullValue()); assertThat(keyStoreWrapper, notNullValue());
keyStoreWrapper.setString("some.setting.that.does.not.exist", new char[0]); keyStoreWrapper.setString("some.setting.that.does.not.exist", new char[0]);
keyStoreWrapper.save(environment.configFile(), new char[0], false); keyStoreWrapper.save(environment.configDir(), new char[0], false);
} }
actionFuture = new PlainActionFuture<>(); actionFuture = new PlainActionFuture<>();
@ -432,7 +432,7 @@ public class ReloadSecureSettingsIT extends ESIntegTestCase {
private SecureSettings writeEmptyKeystore(Environment environment, char[] password) throws Exception { private SecureSettings writeEmptyKeystore(Environment environment, char[] password) throws Exception {
final KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create(); final KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.create();
keyStoreWrapper.save(environment.configFile(), password, false); keyStoreWrapper.save(environment.configDir(), password, false);
return keyStoreWrapper; return keyStoreWrapper;
} }

View file

@ -220,7 +220,7 @@ public class IndexShardIT extends ESSingleNodeTestCase {
public void testIndexDirIsDeletedWhenShardRemoved() throws Exception { public void testIndexDirIsDeletedWhenShardRemoved() throws Exception {
Environment env = getInstanceFromNode(Environment.class); Environment env = getInstanceFromNode(Environment.class);
Path idxPath = env.sharedDataFile().resolve(randomAlphaOfLength(10)); Path idxPath = env.sharedDataDir().resolve(randomAlphaOfLength(10));
logger.info("--> idxPath: [{}]", idxPath); logger.info("--> idxPath: [{}]", idxPath);
Settings idxSettings = Settings.builder().put(IndexMetadata.SETTING_DATA_PATH, idxPath).build(); Settings idxSettings = Settings.builder().put(IndexMetadata.SETTING_DATA_PATH, idxPath).build();
createIndex("test", idxSettings); createIndex("test", idxSettings);
@ -254,7 +254,7 @@ public class IndexShardIT extends ESSingleNodeTestCase {
public void testIndexCanChangeCustomDataPath() throws Exception { public void testIndexCanChangeCustomDataPath() throws Exception {
final String index = "test-custom-data-path"; final String index = "test-custom-data-path";
final Path sharedDataPath = getInstanceFromNode(Environment.class).sharedDataFile().resolve(randomAsciiLettersOfLength(10)); final Path sharedDataPath = getInstanceFromNode(Environment.class).sharedDataDir().resolve(randomAsciiLettersOfLength(10));
final Path indexDataPath = sharedDataPath.resolve("start-" + randomAsciiLettersOfLength(10)); final Path indexDataPath = sharedDataPath.resolve("start-" + randomAsciiLettersOfLength(10));
logger.info("--> creating index [{}] with data_path [{}]", index, indexDataPath); logger.info("--> creating index [{}] with data_path [{}]", index, indexDataPath);

View file

@ -560,7 +560,7 @@ public class RemoveCorruptedShardDataCommandIT extends ESIntegTestCase {
command.findAndProcessShardPath( command.findAndProcessShardPath(
options, options,
environmentByNodeName.get(nodeName), environmentByNodeName.get(nodeName),
environmentByNodeName.get(nodeName).dataFiles(), environmentByNodeName.get(nodeName).dataDirs(),
state, state,
shardPath -> assertThat(shardPath.resolveIndex(), equalTo(indexPath)) shardPath -> assertThat(shardPath.resolveIndex(), equalTo(indexPath))
); );

View file

@ -195,7 +195,7 @@ public class MultiClusterRepoAccessIT extends AbstractSnapshotIntegTestCase {
); );
assertAcked(clusterAdmin().prepareDeleteRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repoName)); assertAcked(clusterAdmin().prepareDeleteRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repoName));
IOUtils.rm(internalCluster().getCurrentMasterNodeInstance(Environment.class).resolveRepoFile(repoPath.toString())); IOUtils.rm(internalCluster().getCurrentMasterNodeInstance(Environment.class).resolveRepoDir(repoPath.toString()));
createRepository(repoName, "fs", repoPath); createRepository(repoName, "fs", repoPath);
createFullSnapshot(repoName, "snap-1"); createFullSnapshot(repoName, "snap-1");

View file

@ -108,7 +108,7 @@ public class TransportNodesReloadSecureSettingsAction extends TransportNodesActi
Task task Task task
) { ) {
// We default to using an empty string as the keystore password so that we mimic pre 7.3 API behavior // We default to using an empty string as the keystore password so that we mimic pre 7.3 API behavior
try (KeyStoreWrapper keystore = KeyStoreWrapper.load(environment.configFile())) { try (KeyStoreWrapper keystore = KeyStoreWrapper.load(environment.configDir())) {
// reread keystore from config file // reread keystore from config file
if (keystore == null) { if (keystore == null) {
return new NodesReloadSecureSettingsResponse.NodeResponse( return new NodesReloadSecureSettingsResponse.NodeResponse(

View file

@ -24,7 +24,7 @@ public class BootstrapUtil {
public static SecureSettings loadSecureSettings(Environment initialEnv, SecureString keystorePassword) throws BootstrapException { public static SecureSettings loadSecureSettings(Environment initialEnv, SecureString keystorePassword) throws BootstrapException {
try { try {
return KeyStoreWrapper.bootstrap(initialEnv.configFile(), () -> keystorePassword); return KeyStoreWrapper.bootstrap(initialEnv.configDir(), () -> keystorePassword);
} catch (Exception e) { } catch (Exception e) {
throw new BootstrapException(e); throw new BootstrapException(e);
} }

View file

@ -52,7 +52,7 @@ public class ConsoleLoader {
} }
private static ClassLoader buildClassLoader(Environment env) { private static ClassLoader buildClassLoader(Environment env) {
final Path libDir = env.libFile().resolve("tools").resolve("ansi-console"); final Path libDir = env.libDir().resolve("tools").resolve("ansi-console");
try (var libDirFilesStream = Files.list(libDir)) { try (var libDirFilesStream = Files.list(libDir)) {
final URL[] urls = libDirFilesStream.filter(each -> each.getFileName().toString().endsWith(".jar")) final URL[] urls = libDirFilesStream.filter(each -> each.getFileName().toString().endsWith(".jar"))

View file

@ -187,7 +187,7 @@ class Elasticsearch {
nodeEnv.validateNativesConfig(); // temporary directories are important for JNA nodeEnv.validateNativesConfig(); // temporary directories are important for JNA
initializeNatives( initializeNatives(
nodeEnv.tmpFile(), nodeEnv.tmpDir(),
BootstrapSettings.MEMORY_LOCK_SETTING.get(args.nodeSettings()), BootstrapSettings.MEMORY_LOCK_SETTING.get(args.nodeSettings()),
true, // always install system call filters, not user-configurable since 8.0.0 true, // always install system call filters, not user-configurable since 8.0.0
BootstrapSettings.CTRLHANDLER_SETTING.get(args.nodeSettings()) BootstrapSettings.CTRLHANDLER_SETTING.get(args.nodeSettings())
@ -223,8 +223,8 @@ class Elasticsearch {
); );
// load the plugin Java modules and layers now for use in entitlements // load the plugin Java modules and layers now for use in entitlements
var modulesBundles = PluginsLoader.loadModulesBundles(nodeEnv.modulesFile()); var modulesBundles = PluginsLoader.loadModulesBundles(nodeEnv.modulesDir());
var pluginsBundles = PluginsLoader.loadPluginsBundles(nodeEnv.pluginsFile()); var pluginsBundles = PluginsLoader.loadPluginsBundles(nodeEnv.pluginsDir());
final PluginsLoader pluginsLoader; final PluginsLoader pluginsLoader;
@ -245,9 +245,9 @@ class Elasticsearch {
EntitlementBootstrap.bootstrap( EntitlementBootstrap.bootstrap(
pluginPolicies, pluginPolicies,
pluginsResolver::resolveClassToPluginName, pluginsResolver::resolveClassToPluginName,
nodeEnv.dataFiles(), nodeEnv.dataDirs(),
nodeEnv.configFile(), nodeEnv.configDir(),
nodeEnv.tmpFile() nodeEnv.tmpDir()
); );
} else if (RuntimeVersionFeature.isSecurityManagerAvailable()) { } else if (RuntimeVersionFeature.isSecurityManagerAvailable()) {
// no need to explicitly enable native access for legacy code // no need to explicitly enable native access for legacy code

View file

@ -178,11 +178,11 @@ final class Security {
} }
}; };
for (Path plugin : PluginsUtils.findPluginDirs(environment.pluginsFile())) { for (Path plugin : PluginsUtils.findPluginDirs(environment.pluginsDir())) {
addPolicy.accept(PolicyUtil.getPluginPolicyInfo(plugin, environment.tmpFile())); addPolicy.accept(PolicyUtil.getPluginPolicyInfo(plugin, environment.tmpDir()));
} }
for (Path plugin : PluginsUtils.findPluginDirs(environment.modulesFile())) { for (Path plugin : PluginsUtils.findPluginDirs(environment.modulesDir())) {
addPolicy.accept(PolicyUtil.getModulePolicyInfo(plugin, environment.tmpFile())); addPolicy.accept(PolicyUtil.getModulePolicyInfo(plugin, environment.tmpDir()));
} }
return Collections.unmodifiableMap(map); return Collections.unmodifiableMap(map);
@ -199,7 +199,7 @@ final class Security {
private static List<FilePermission> createRecursiveDataPathPermission(Environment environment) throws IOException { private static List<FilePermission> createRecursiveDataPathPermission(Environment environment) throws IOException {
Permissions policy = new Permissions(); Permissions policy = new Permissions();
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete", true); addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete", true);
} }
return toFilePermissions(policy); return toFilePermissions(policy);
@ -215,13 +215,13 @@ final class Security {
Map<String, Set<URL>> securedSettingKeys = new HashMap<>(); Map<String, Set<URL>> securedSettingKeys = new HashMap<>();
for (URL url : mainCodebases) { for (URL url : mainCodebases) {
for (Permission p : PolicyUtil.getPolicyPermissions(url, template, environment.tmpFile())) { for (Permission p : PolicyUtil.getPolicyPermissions(url, template, environment.tmpDir())) {
readSecuredConfigFilePermissions(environment, url, p, securedConfigFiles, securedSettingKeys); readSecuredConfigFilePermissions(environment, url, p, securedConfigFiles, securedSettingKeys);
} }
} }
for (var pp : pluginPolicies.entrySet()) { for (var pp : pluginPolicies.entrySet()) {
for (Permission p : PolicyUtil.getPolicyPermissions(pp.getKey(), pp.getValue(), environment.tmpFile())) { for (Permission p : PolicyUtil.getPolicyPermissions(pp.getKey(), pp.getValue(), environment.tmpDir())) {
readSecuredConfigFilePermissions(environment, pp.getKey(), p, securedConfigFiles, securedSettingKeys); readSecuredConfigFilePermissions(environment, pp.getKey(), p, securedConfigFiles, securedSettingKeys);
} }
} }
@ -242,8 +242,8 @@ final class Security {
// If the setting shouldn't be an HTTPS URL, that'll be caught by that setting's validation later in the process. // If the setting shouldn't be an HTTPS URL, that'll be caught by that setting's validation later in the process.
// HTTP (no S) URLs are not supported. // HTTP (no S) URLs are not supported.
if (settingValue.toLowerCase(Locale.ROOT).startsWith("https://") == false) { if (settingValue.toLowerCase(Locale.ROOT).startsWith("https://") == false) {
Path file = environment.configFile().resolve(settingValue); Path file = environment.configDir().resolve(settingValue);
if (file.startsWith(environment.configFile()) == false) { if (file.startsWith(environment.configDir()) == false) {
throw new IllegalStateException( throw new IllegalStateException(
ps.getValue() + " tried to grant access to file outside config directory " + file ps.getValue() + " tried to grant access to file outside config directory " + file
); );
@ -263,9 +263,9 @@ final class Security {
// always add some config files as exclusive files that no one can access // always add some config files as exclusive files that no one can access
// there's no reason for anyone to read these once the security manager is initialized // there's no reason for anyone to read these once the security manager is initialized
// so if something has tried to grant itself access, crash out with an error // so if something has tried to grant itself access, crash out with an error
addSpeciallySecuredConfigFile(securedConfigFiles, environment.configFile().resolve("elasticsearch.yml").toString()); addSpeciallySecuredConfigFile(securedConfigFiles, environment.configDir().resolve("elasticsearch.yml").toString());
addSpeciallySecuredConfigFile(securedConfigFiles, environment.configFile().resolve("jvm.options").toString()); addSpeciallySecuredConfigFile(securedConfigFiles, environment.configDir().resolve("jvm.options").toString());
addSpeciallySecuredConfigFile(securedConfigFiles, environment.configFile().resolve("jvm.options.d/-").toString()); addSpeciallySecuredConfigFile(securedConfigFiles, environment.configDir().resolve("jvm.options.d/-").toString());
return Collections.unmodifiableMap(securedConfigFiles); return Collections.unmodifiableMap(securedConfigFiles);
} }
@ -279,8 +279,8 @@ final class Security {
) { ) {
String securedFileName = extractSecuredName(p, SecuredConfigFileAccessPermission.class); String securedFileName = extractSecuredName(p, SecuredConfigFileAccessPermission.class);
if (securedFileName != null) { if (securedFileName != null) {
Path securedFile = environment.configFile().resolve(securedFileName); Path securedFile = environment.configDir().resolve(securedFileName);
if (securedFile.startsWith(environment.configFile()) == false) { if (securedFile.startsWith(environment.configDir()) == false) {
throw new IllegalStateException("[" + url + "] tried to grant access to file outside config directory " + securedFile); throw new IllegalStateException("[" + url + "] tried to grant access to file outside config directory " + securedFile);
} }
logger.debug("Jar {} securing access to config file {}", url, securedFile); logger.debug("Jar {} securing access to config file {}", url, securedFile);
@ -336,26 +336,26 @@ final class Security {
*/ */
static void addFilePermissions(Permissions policy, Environment environment, Path pidFile) throws IOException { static void addFilePermissions(Permissions policy, Environment environment, Path pidFile) throws IOException {
// read-only dirs // read-only dirs
addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.binFile(), "read,readlink", false); addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.binDir(), "read,readlink", false);
addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.libFile(), "read,readlink", false); addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.libDir(), "read,readlink", false);
addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.modulesFile(), "read,readlink", false); addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.modulesDir(), "read,readlink", false);
addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.pluginsFile(), "read,readlink", false); addDirectoryPath(policy, Environment.PATH_HOME_SETTING.getKey(), environment.pluginsDir(), "read,readlink", false);
addDirectoryPath(policy, "path.conf", environment.configFile(), "read,readlink", false); addDirectoryPath(policy, "path.conf", environment.configDir(), "read,readlink", false);
// read-write dirs // read-write dirs
addDirectoryPath(policy, "java.io.tmpdir", environment.tmpFile(), "read,readlink,write,delete", false); addDirectoryPath(policy, "java.io.tmpdir", environment.tmpDir(), "read,readlink,write,delete", false);
addDirectoryPath(policy, Environment.PATH_LOGS_SETTING.getKey(), environment.logsFile(), "read,readlink,write,delete", false); addDirectoryPath(policy, Environment.PATH_LOGS_SETTING.getKey(), environment.logsDir(), "read,readlink,write,delete", false);
if (environment.sharedDataFile() != null) { if (environment.sharedDataDir() != null) {
addDirectoryPath( addDirectoryPath(
policy, policy,
Environment.PATH_SHARED_DATA_SETTING.getKey(), Environment.PATH_SHARED_DATA_SETTING.getKey(),
environment.sharedDataFile(), environment.sharedDataDir(),
"read,readlink,write,delete", "read,readlink,write,delete",
false false
); );
} }
final Set<Path> dataFilesPaths = new HashSet<>(); final Set<Path> dataFilesPaths = new HashSet<>();
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete", false); addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete", false);
/* /*
* We have to do this after adding the path because a side effect of that is that the directory is created; the Path#toRealPath * We have to do this after adding the path because a side effect of that is that the directory is created; the Path#toRealPath
@ -371,7 +371,7 @@ final class Security {
throw new IllegalStateException("unable to access [" + path + "]", e); throw new IllegalStateException("unable to access [" + path + "]", e);
} }
} }
for (Path path : environment.repoFiles()) { for (Path path : environment.repoDirs()) {
addDirectoryPath(policy, Environment.PATH_REPO_SETTING.getKey(), path, "read,readlink,write,delete", false); addDirectoryPath(policy, Environment.PATH_REPO_SETTING.getKey(), path, "read,readlink,write,delete", false);
} }
@ -380,7 +380,7 @@ final class Security {
addSingleFilePath(policy, pidFile, "delete"); addSingleFilePath(policy, pidFile, "delete");
} }
// we need to touch the operator/settings.json file when restoring from snapshots, on some OSs it needs file write permission // we need to touch the operator/settings.json file when restoring from snapshots, on some OSs it needs file write permission
addSingleFilePath(policy, environment.configFile().resolve(OPERATOR_DIRECTORY).resolve(SETTINGS_FILE_NAME), "read,readlink,write"); addSingleFilePath(policy, environment.configDir().resolve(OPERATOR_DIRECTORY).resolve(SETTINGS_FILE_NAME), "read,readlink,write");
} }
/** /**

View file

@ -69,14 +69,14 @@ final class Spawner implements Closeable {
if (spawned.compareAndSet(false, true) == false) { if (spawned.compareAndSet(false, true) == false) {
throw new IllegalStateException("native controllers already spawned"); throw new IllegalStateException("native controllers already spawned");
} }
if (Files.exists(environment.modulesFile()) == false) { if (Files.exists(environment.modulesDir()) == false) {
throw new IllegalStateException("modules directory [" + environment.modulesFile() + "] not found"); throw new IllegalStateException("modules directory [" + environment.modulesDir() + "] not found");
} }
/* /*
* For each module, attempt to spawn the controller daemon. Silently ignore any module that doesn't include a controller for the * For each module, attempt to spawn the controller daemon. Silently ignore any module that doesn't include a controller for the
* correct platform. * correct platform.
*/ */
List<Path> paths = PluginsUtils.findPluginDirs(environment.modulesFile()); List<Path> paths = PluginsUtils.findPluginDirs(environment.modulesDir());
for (final Path modules : paths) { for (final Path modules : paths) {
final PluginDescriptor info = PluginDescriptor.readFromProperties(modules); final PluginDescriptor info = PluginDescriptor.readFromProperties(modules);
final Path spawnPath = Platforms.nativeControllerPath(modules); final Path spawnPath = Platforms.nativeControllerPath(modules);
@ -91,7 +91,7 @@ final class Spawner implements Closeable {
); );
throw new IllegalArgumentException(message); throw new IllegalArgumentException(message);
} }
final Process process = spawnNativeController(spawnPath, environment.tmpFile()); final Process process = spawnNativeController(spawnPath, environment.tmpDir());
// The process _shouldn't_ write any output via its stdout or stderr, but if it does then // The process _shouldn't_ write any output via its stdout or stderr, but if it does then
// it will block if nothing is reading that output. To avoid this we can pipe the // it will block if nothing is reading that output. To avoid this we can pipe the
// outputs and create pump threads to write any messages there to the ES log. // outputs and create pump threads to write any messages there to the ES log.

View file

@ -1457,7 +1457,7 @@ public class MetadataCreateIndexService {
} }
List<String> getIndexSettingsValidationErrors(final Settings settings, final boolean forbidPrivateIndexSettings) { List<String> getIndexSettingsValidationErrors(final Settings settings, final boolean forbidPrivateIndexSettings) {
List<String> validationErrors = validateIndexCustomPath(settings, env.sharedDataFile()); List<String> validationErrors = validateIndexCustomPath(settings, env.sharedDataDir());
if (forbidPrivateIndexSettings) { if (forbidPrivateIndexSettings) {
validationErrors.addAll(validatePrivateSettingsNotExplicitlySet(settings, indexScopedSettings)); validationErrors.addAll(validatePrivateSettingsNotExplicitlySet(settings, indexScopedSettings));
} }

View file

@ -127,7 +127,7 @@ public class LogConfigurator {
StatusLogger.getLogger().removeListener(ERROR_LISTENER); StatusLogger.getLogger().removeListener(ERROR_LISTENER);
} }
configureESLogging(); configureESLogging();
configure(environment.settings(), environment.configFile(), environment.logsFile(), useConsole); configure(environment.settings(), environment.configDir(), environment.logsDir(), useConsole);
initializeStatics(); initializeStatics();
// creates a permanent status logger that can watch for StatusLogger events and forward to a real logger // creates a permanent status logger that can watch for StatusLogger events and forward to a real logger
configureStatusLoggerForwarder(); configureStatusLoggerForwarder();

View file

@ -142,7 +142,7 @@ public final class LocallyMountedSecrets implements SecureSettings {
* @return Secrets directory within an Elasticsearch environment * @return Secrets directory within an Elasticsearch environment
*/ */
public static Path resolveSecretsDir(Environment environment) { public static Path resolveSecretsDir(Environment environment) {
return environment.configFile().toAbsolutePath().resolve(SECRETS_DIRECTORY); return environment.configDir().toAbsolutePath().resolve(SECRETS_DIRECTORY);
} }
/** /**

View file

@ -46,28 +46,28 @@ public class Environment {
private final Settings settings; private final Settings settings;
private final Path[] dataFiles; private final Path[] dataDirs;
private final Path[] repoFiles; private final Path[] repoDirs;
private final Path configFile; private final Path configDir;
private final Path pluginsFile; private final Path pluginsDir;
private final Path modulesFile; private final Path modulesDir;
private final Path sharedDataFile; private final Path sharedDataDir;
/** location of bin/, used by plugin manager */ /** location of bin/, used by plugin manager */
private final Path binFile; private final Path binDir;
/** location of lib/, */ /** location of lib/, */
private final Path libFile; private final Path libDir;
private final Path logsFile; private final Path logsDir;
/** Path to the temporary file directory used by the JDK */ /** Path to the temporary file directory used by the JDK */
private final Path tmpFile; private final Path tmpDir;
public Environment(final Settings settings, final Path configPath) { public Environment(final Settings settings, final Path configPath) {
this(settings, configPath, PathUtils.get(System.getProperty("java.io.tmpdir"))); this(settings, configPath, PathUtils.get(System.getProperty("java.io.tmpdir")));
@ -83,67 +83,67 @@ public class Environment {
} }
if (configPath != null) { if (configPath != null) {
configFile = configPath.toAbsolutePath().normalize(); configDir = configPath.toAbsolutePath().normalize();
} else { } else {
configFile = homeFile.resolve("config"); configDir = homeFile.resolve("config");
} }
tmpFile = Objects.requireNonNull(tmpPath); tmpDir = Objects.requireNonNull(tmpPath);
pluginsFile = homeFile.resolve("plugins"); pluginsDir = homeFile.resolve("plugins");
List<String> dataPaths = PATH_DATA_SETTING.get(settings); List<String> dataPaths = PATH_DATA_SETTING.get(settings);
if (dataPaths.isEmpty() == false) { if (dataPaths.isEmpty() == false) {
dataFiles = new Path[dataPaths.size()]; dataDirs = new Path[dataPaths.size()];
for (int i = 0; i < dataPaths.size(); i++) { for (int i = 0; i < dataPaths.size(); i++) {
dataFiles[i] = PathUtils.get(dataPaths.get(i)).toAbsolutePath().normalize(); dataDirs[i] = PathUtils.get(dataPaths.get(i)).toAbsolutePath().normalize();
} }
} else { } else {
dataFiles = new Path[] { homeFile.resolve("data") }; dataDirs = new Path[] { homeFile.resolve("data") };
} }
if (PATH_SHARED_DATA_SETTING.exists(settings)) { if (PATH_SHARED_DATA_SETTING.exists(settings)) {
sharedDataFile = PathUtils.get(PATH_SHARED_DATA_SETTING.get(settings)).toAbsolutePath().normalize(); sharedDataDir = PathUtils.get(PATH_SHARED_DATA_SETTING.get(settings)).toAbsolutePath().normalize();
} else { } else {
sharedDataFile = null; sharedDataDir = null;
} }
List<String> repoPaths = PATH_REPO_SETTING.get(settings); List<String> repoPaths = PATH_REPO_SETTING.get(settings);
if (repoPaths.isEmpty()) { if (repoPaths.isEmpty()) {
repoFiles = EMPTY_PATH_ARRAY; repoDirs = EMPTY_PATH_ARRAY;
} else { } else {
repoFiles = new Path[repoPaths.size()]; repoDirs = new Path[repoPaths.size()];
for (int i = 0; i < repoPaths.size(); i++) { for (int i = 0; i < repoPaths.size(); i++) {
repoFiles[i] = PathUtils.get(repoPaths.get(i)).toAbsolutePath().normalize(); repoDirs[i] = PathUtils.get(repoPaths.get(i)).toAbsolutePath().normalize();
} }
} }
// this is trappy, Setting#get(Settings) will get a fallback setting yet return false for Settings#exists(Settings) // this is trappy, Setting#get(Settings) will get a fallback setting yet return false for Settings#exists(Settings)
if (PATH_LOGS_SETTING.exists(settings)) { if (PATH_LOGS_SETTING.exists(settings)) {
logsFile = PathUtils.get(PATH_LOGS_SETTING.get(settings)).toAbsolutePath().normalize(); logsDir = PathUtils.get(PATH_LOGS_SETTING.get(settings)).toAbsolutePath().normalize();
} else { } else {
logsFile = homeFile.resolve("logs"); logsDir = homeFile.resolve("logs");
} }
binFile = homeFile.resolve("bin"); binDir = homeFile.resolve("bin");
libFile = homeFile.resolve("lib"); libDir = homeFile.resolve("lib");
modulesFile = homeFile.resolve("modules"); modulesDir = homeFile.resolve("modules");
final Settings.Builder finalSettings = Settings.builder().put(settings); final Settings.Builder finalSettings = Settings.builder().put(settings);
if (PATH_DATA_SETTING.exists(settings)) { if (PATH_DATA_SETTING.exists(settings)) {
if (dataPathUsesList(settings)) { if (dataPathUsesList(settings)) {
finalSettings.putList(PATH_DATA_SETTING.getKey(), Arrays.stream(dataFiles).map(Path::toString).toList()); finalSettings.putList(PATH_DATA_SETTING.getKey(), Arrays.stream(dataDirs).map(Path::toString).toList());
} else { } else {
assert dataFiles.length == 1; assert dataDirs.length == 1;
finalSettings.put(PATH_DATA_SETTING.getKey(), dataFiles[0]); finalSettings.put(PATH_DATA_SETTING.getKey(), dataDirs[0]);
} }
} }
finalSettings.put(PATH_HOME_SETTING.getKey(), homeFile); finalSettings.put(PATH_HOME_SETTING.getKey(), homeFile);
finalSettings.put(PATH_LOGS_SETTING.getKey(), logsFile.toString()); finalSettings.put(PATH_LOGS_SETTING.getKey(), logsDir.toString());
if (PATH_REPO_SETTING.exists(settings)) { if (PATH_REPO_SETTING.exists(settings)) {
finalSettings.putList(Environment.PATH_REPO_SETTING.getKey(), Arrays.stream(repoFiles).map(Path::toString).toList()); finalSettings.putList(Environment.PATH_REPO_SETTING.getKey(), Arrays.stream(repoDirs).map(Path::toString).toList());
} }
if (PATH_SHARED_DATA_SETTING.exists(settings)) { if (PATH_SHARED_DATA_SETTING.exists(settings)) {
assert sharedDataFile != null; assert sharedDataDir != null;
finalSettings.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), sharedDataFile.toString()); finalSettings.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), sharedDataDir.toString());
} }
this.settings = finalSettings.build(); this.settings = finalSettings.build();
@ -159,22 +159,22 @@ public class Environment {
/** /**
* The data location. * The data location.
*/ */
public Path[] dataFiles() { public Path[] dataDirs() {
return dataFiles; return dataDirs;
} }
/** /**
* The shared data location * The shared data location
*/ */
public Path sharedDataFile() { public Path sharedDataDir() {
return sharedDataFile; return sharedDataDir;
} }
/** /**
* The shared filesystem repo locations. * The shared filesystem repo locations.
*/ */
public Path[] repoFiles() { public Path[] repoDirs() {
return repoFiles; return repoDirs;
} }
/** /**
@ -182,8 +182,8 @@ public class Environment {
* *
* If the specified location doesn't match any of the roots, returns null. * If the specified location doesn't match any of the roots, returns null.
*/ */
public Path resolveRepoFile(String location) { public Path resolveRepoDir(String location) {
return PathUtils.get(repoFiles, location); return PathUtils.get(repoDirs, location);
} }
/** /**
@ -197,7 +197,7 @@ public class Environment {
if ("file".equalsIgnoreCase(url.getProtocol())) { if ("file".equalsIgnoreCase(url.getProtocol())) {
if (url.getHost() == null || "".equals(url.getHost())) { if (url.getHost() == null || "".equals(url.getHost())) {
// only local file urls are supported // only local file urls are supported
Path path = PathUtils.get(repoFiles, url.toURI()); Path path = PathUtils.get(repoDirs, url.toURI());
if (path == null) { if (path == null) {
// Couldn't resolve against known repo locations // Couldn't resolve against known repo locations
return null; return null;
@ -232,49 +232,48 @@ public class Environment {
} }
} }
// TODO: rename all these "file" methods to "dir"
/** /**
* The config directory. * The config directory.
*/ */
public Path configFile() { public Path configDir() {
return configFile; return configDir;
} }
public Path pluginsFile() { public Path pluginsDir() {
return pluginsFile; return pluginsDir;
} }
public Path binFile() { public Path binDir() {
return binFile; return binDir;
} }
public Path libFile() { public Path libDir() {
return libFile; return libDir;
} }
public Path modulesFile() { public Path modulesDir() {
return modulesFile; return modulesDir;
} }
public Path logsFile() { public Path logsDir() {
return logsFile; return logsDir;
} }
/** Path to the default temp directory used by the JDK */ /** Path to the default temp directory used by the JDK */
public Path tmpFile() { public Path tmpDir() {
return tmpFile; return tmpDir;
} }
/** Ensure the configured temp directory is a valid directory */ /** Ensure the configured temp directory is a valid directory */
public void validateTmpFile() throws IOException { public void validateTmpDir() throws IOException {
validateTemporaryDirectory("Temporary directory", tmpFile); validateTemporaryDirectory("Temporary directory", tmpDir);
} }
/** /**
* Ensure the temp directories needed for JNA are set up correctly. * Ensure the temp directories needed for JNA are set up correctly.
*/ */
public void validateNativesConfig() throws IOException { public void validateNativesConfig() throws IOException {
validateTmpFile(); validateTmpDir();
if (Constants.LINUX) { if (Constants.LINUX) {
validateTemporaryDirectory(LIBFFI_TMPDIR_ENVIRONMENT_VARIABLE + " environment variable", getLibffiTemporaryDirectory()); validateTemporaryDirectory(LIBFFI_TMPDIR_ENVIRONMENT_VARIABLE + " environment variable", getLibffiTemporaryDirectory());
} }
@ -335,15 +334,15 @@ public class Environment {
* object which may contain different setting) * object which may contain different setting)
*/ */
public static void assertEquivalent(Environment actual, Environment expected) { public static void assertEquivalent(Environment actual, Environment expected) {
assertEquals(actual.dataFiles(), expected.dataFiles(), "dataFiles"); assertEquals(actual.dataDirs(), expected.dataDirs(), "dataDirs");
assertEquals(actual.repoFiles(), expected.repoFiles(), "repoFiles"); assertEquals(actual.repoDirs(), expected.repoDirs(), "repoDirs");
assertEquals(actual.configFile(), expected.configFile(), "configFile"); assertEquals(actual.configDir(), expected.configDir(), "configDir");
assertEquals(actual.pluginsFile(), expected.pluginsFile(), "pluginsFile"); assertEquals(actual.pluginsDir(), expected.pluginsDir(), "pluginsDir");
assertEquals(actual.binFile(), expected.binFile(), "binFile"); assertEquals(actual.binDir(), expected.binDir(), "binDir");
assertEquals(actual.libFile(), expected.libFile(), "libFile"); assertEquals(actual.libDir(), expected.libDir(), "libDir");
assertEquals(actual.modulesFile(), expected.modulesFile(), "modulesFile"); assertEquals(actual.modulesDir(), expected.modulesDir(), "modulesDir");
assertEquals(actual.logsFile(), expected.logsFile(), "logsFile"); assertEquals(actual.logsDir(), expected.logsDir(), "logsDir");
assertEquals(actual.tmpFile(), expected.tmpFile(), "tmpFile"); assertEquals(actual.tmpDir(), expected.tmpDir(), "tmpDir");
} }
private static void assertEquals(Object actual, Object expected, String name) { private static void assertEquals(Object actual, Object expected, String name) {

View file

@ -215,10 +215,10 @@ public final class NodeEnvironment implements Closeable {
final CheckedFunction<Path, Boolean, IOException> pathFunction, final CheckedFunction<Path, Boolean, IOException> pathFunction,
final Function<Path, Path> subPathMapping final Function<Path, Path> subPathMapping
) throws IOException { ) throws IOException {
dataPaths = new DataPath[environment.dataFiles().length]; dataPaths = new DataPath[environment.dataDirs().length];
locks = new Lock[dataPaths.length]; locks = new Lock[dataPaths.length];
try { try {
final Path[] dataPaths = environment.dataFiles(); final Path[] dataPaths = environment.dataDirs();
for (int dirIndex = 0; dirIndex < dataPaths.length; dirIndex++) { for (int dirIndex = 0; dirIndex < dataPaths.length; dirIndex++) {
Path dataDir = dataPaths[dirIndex]; Path dataDir = dataPaths[dirIndex];
Path dir = subPathMapping.apply(dataDir); Path dir = subPathMapping.apply(dataDir);
@ -267,9 +267,9 @@ public final class NodeEnvironment implements Closeable {
boolean success = false; boolean success = false;
try { try {
sharedDataPath = environment.sharedDataFile(); sharedDataPath = environment.sharedDataDir();
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
if (Files.exists(path)) { if (Files.exists(path)) {
// Call to toRealPath required to resolve symlinks. // Call to toRealPath required to resolve symlinks.
// We let it fall through to create directories to ensure the symlink // We let it fall through to create directories to ensure the symlink
@ -287,7 +287,7 @@ public final class NodeEnvironment implements Closeable {
Locale.ROOT, Locale.ROOT,
"failed to obtain node locks, tried %s;" "failed to obtain node locks, tried %s;"
+ " maybe these locations are not writable or multiple nodes were started on the same data path?", + " maybe these locations are not writable or multiple nodes were started on the same data path?",
Arrays.toString(environment.dataFiles()) Arrays.toString(environment.dataDirs())
); );
throw new IllegalStateException(message, e); throw new IllegalStateException(message, e);
} }
@ -310,7 +310,7 @@ public final class NodeEnvironment implements Closeable {
} }
// versions 7.x and earlier put their data under ${path.data}/nodes/; leave a file at that location to prevent downgrades // versions 7.x and earlier put their data under ${path.data}/nodes/; leave a file at that location to prevent downgrades
for (Path dataPath : environment.dataFiles()) { for (Path dataPath : environment.dataDirs()) {
final Path legacyNodesPath = dataPath.resolve("nodes"); final Path legacyNodesPath = dataPath.resolve("nodes");
if (Files.isRegularFile(legacyNodesPath) == false) { if (Files.isRegularFile(legacyNodesPath) == false) {
final String content = "written by Elasticsearch " final String content = "written by Elasticsearch "
@ -349,7 +349,7 @@ public final class NodeEnvironment implements Closeable {
boolean upgradeNeeded = false; boolean upgradeNeeded = false;
// check if we can do an auto-upgrade // check if we can do an auto-upgrade
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
final Path nodesFolderPath = path.resolve("nodes"); final Path nodesFolderPath = path.resolve("nodes");
if (Files.isDirectory(nodesFolderPath)) { if (Files.isDirectory(nodesFolderPath)) {
final List<Integer> nodeLockIds = new ArrayList<>(); final List<Integer> nodeLockIds = new ArrayList<>();
@ -392,7 +392,7 @@ public final class NodeEnvironment implements Closeable {
return false; return false;
} }
logger.info("upgrading legacy data folders: {}", Arrays.toString(environment.dataFiles())); logger.info("upgrading legacy data folders: {}", Arrays.toString(environment.dataDirs()));
// acquire locks on legacy path for duration of upgrade (to ensure there is no older ES version running on this path) // acquire locks on legacy path for duration of upgrade (to ensure there is no older ES version running on this path)
final NodeLock legacyNodeLock; final NodeLock legacyNodeLock;
@ -403,7 +403,7 @@ public final class NodeEnvironment implements Closeable {
Locale.ROOT, Locale.ROOT,
"failed to obtain legacy node locks, tried %s;" "failed to obtain legacy node locks, tried %s;"
+ " maybe these locations are not writable or multiple nodes were started on the same data path?", + " maybe these locations are not writable or multiple nodes were started on the same data path?",
Arrays.toString(environment.dataFiles()) Arrays.toString(environment.dataDirs())
); );
throw new IllegalStateException(message, e); throw new IllegalStateException(message, e);
} }
@ -494,7 +494,7 @@ public final class NodeEnvironment implements Closeable {
} }
// upgrade successfully completed, remove legacy nodes folders // upgrade successfully completed, remove legacy nodes folders
IOUtils.rm(Stream.of(environment.dataFiles()).map(path -> path.resolve("nodes")).toArray(Path[]::new)); IOUtils.rm(Stream.of(environment.dataDirs()).map(path -> path.resolve("nodes")).toArray(Path[]::new));
return true; return true;
} }

View file

@ -233,7 +233,7 @@ public class Analysis {
} }
} }
final Path path = env.configFile().resolve(wordListPath); final Path path = env.configDir().resolve(wordListPath);
try { try {
return loadWordList(path, removeComments); return loadWordList(path, removeComments);
@ -337,7 +337,7 @@ public class Analysis {
if (filePath == null) { if (filePath == null) {
return null; return null;
} }
final Path path = env.configFile().resolve(filePath); final Path path = env.configDir().resolve(filePath);
try { try {
return Files.newBufferedReader(path, StandardCharsets.UTF_8); return Files.newBufferedReader(path, StandardCharsets.UTF_8);
} catch (CharacterCodingException ex) { } catch (CharacterCodingException ex) {

View file

@ -122,7 +122,7 @@ public final class HunspellService {
} }
private static Path resolveHunspellDirectory(Environment env) { private static Path resolveHunspellDirectory(Environment env) {
return env.configFile().resolve("hunspell"); return env.configDir().resolve("hunspell");
} }
/** /**
@ -193,7 +193,7 @@ public final class HunspellService {
affixStream = Files.newInputStream(affixFiles[0]); affixStream = Files.newInputStream(affixFiles[0]);
try (Directory tmp = new NIOFSDirectory(env.tmpFile())) { try (Directory tmp = new NIOFSDirectory(env.tmpDir())) {
return new Dictionary(tmp, "hunspell", affixStream, dicStreams, ignoreCase); return new Dictionary(tmp, "hunspell", affixStream, dicStreams, ignoreCase);
} }

View file

@ -652,7 +652,7 @@ public class Node implements Closeable {
* Writes a file to the logs dir containing the ports for the given transport type * Writes a file to the logs dir containing the ports for the given transport type
*/ */
private void writePortsFile(String type, BoundTransportAddress boundAddress) { private void writePortsFile(String type, BoundTransportAddress boundAddress) {
Path tmpPortsFile = environment.logsFile().resolve(type + ".ports.tmp"); Path tmpPortsFile = environment.logsDir().resolve(type + ".ports.tmp");
try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, Charset.forName("UTF-8"))) { try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, Charset.forName("UTF-8"))) {
for (TransportAddress address : boundAddress.boundAddresses()) { for (TransportAddress address : boundAddress.boundAddresses()) {
InetAddress inetAddress = InetAddress.getByName(address.getAddress()); InetAddress inetAddress = InetAddress.getByName(address.getAddress());
@ -661,7 +661,7 @@ public class Node implements Closeable {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to write ports file", e); throw new RuntimeException("Failed to write ports file", e);
} }
Path portsFile = environment.logsFile().resolve(type + ".ports"); Path portsFile = environment.logsDir().resolve(type + ".ports");
try { try {
Files.move(tmpPortsFile, portsFile, StandardCopyOption.ATOMIC_MOVE); Files.move(tmpPortsFile, portsFile, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) { } catch (IOException e) {

View file

@ -446,7 +446,7 @@ class NodeConstruction {
); );
} }
if (initialEnvironment.dataFiles().length > 1) { if (initialEnvironment.dataDirs().length > 1) {
// NOTE: we use initialEnvironment here, but assertEquivalent below ensures the data paths do not change // NOTE: we use initialEnvironment here, but assertEquivalent below ensures the data paths do not change
deprecationLogger.warn( deprecationLogger.warn(
DeprecationCategory.SETTINGS, DeprecationCategory.SETTINGS,
@ -467,10 +467,10 @@ class NodeConstruction {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug( logger.debug(
"using config [{}], data [{}], logs [{}], plugins [{}]", "using config [{}], data [{}], logs [{}], plugins [{}]",
initialEnvironment.configFile(), initialEnvironment.configDir(),
Arrays.toString(initialEnvironment.dataFiles()), Arrays.toString(initialEnvironment.dataDirs()),
initialEnvironment.logsFile(), initialEnvironment.logsDir(),
initialEnvironment.pluginsFile() initialEnvironment.pluginsDir()
); );
} }
@ -487,7 +487,7 @@ class NodeConstruction {
* Create the environment based on the finalized view of the settings. This is to ensure that components get the same setting * Create the environment based on the finalized view of the settings. This is to ensure that components get the same setting
* values, no matter they ask for them from. * values, no matter they ask for them from.
*/ */
environment = new Environment(settings, initialEnvironment.configFile()); environment = new Environment(settings, initialEnvironment.configDir());
Environment.assertEquivalent(initialEnvironment, environment); Environment.assertEquivalent(initialEnvironment, environment);
modules.bindToInstance(Environment.class, environment); modules.bindToInstance(Environment.class, environment);
@ -1622,7 +1622,7 @@ class NodeConstruction {
pluginsService.filterPlugins(DiscoveryPlugin.class).toList(), pluginsService.filterPlugins(DiscoveryPlugin.class).toList(),
pluginsService.filterPlugins(ClusterCoordinationPlugin.class).toList(), pluginsService.filterPlugins(ClusterCoordinationPlugin.class).toList(),
allocationService, allocationService,
environment.configFile(), environment.configDir(),
gatewayMetaState, gatewayMetaState,
rerouteService, rerouteService,
fsHealthService, fsHealthService,

View file

@ -53,7 +53,7 @@ class NodeServiceProvider {
PluginsService newPluginService(Environment initialEnvironment, PluginsLoader pluginsLoader) { PluginsService newPluginService(Environment initialEnvironment, PluginsLoader pluginsLoader) {
// this creates a PluginsService with an empty list of classpath plugins // this creates a PluginsService with an empty list of classpath plugins
return new PluginsService(initialEnvironment.settings(), initialEnvironment.configFile(), pluginsLoader); return new PluginsService(initialEnvironment.settings(), initialEnvironment.configDir(), pluginsLoader);
} }
ScriptService newScriptService( ScriptService newScriptService(

View file

@ -92,13 +92,13 @@ public class FsRepository extends BlobStoreRepository {
); );
throw new RepositoryException(metadata.name(), "missing location"); throw new RepositoryException(metadata.name(), "missing location");
} }
Path locationFile = environment.resolveRepoFile(location); Path locationFile = environment.resolveRepoDir(location);
if (locationFile == null) { if (locationFile == null) {
if (environment.repoFiles().length > 0) { if (environment.repoDirs().length > 0) {
logger.warn( logger.warn(
"The specified location [{}] doesn't start with any " + "repository paths specified by the path.repo setting: [{}] ", "The specified location [{}] doesn't start with any " + "repository paths specified by the path.repo setting: [{}] ",
location, location,
environment.repoFiles() environment.repoDirs()
); );
throw new RepositoryException( throw new RepositoryException(
metadata.name(), metadata.name(),
@ -127,7 +127,7 @@ public class FsRepository extends BlobStoreRepository {
@Override @Override
protected BlobStore createBlobStore() throws Exception { protected BlobStore createBlobStore() throws Exception {
final String location = REPOSITORIES_LOCATION_SETTING.get(getMetadata().settings()); final String location = REPOSITORIES_LOCATION_SETTING.get(getMetadata().settings());
final Path locationFile = environment.resolveRepoFile(location); final Path locationFile = environment.resolveRepoDir(location);
return new FsBlobStore(bufferSize, locationFile, isReadOnly()); return new FsBlobStore(bufferSize, locationFile, isReadOnly());
} }

View file

@ -82,7 +82,7 @@ public class FileSettingsService extends MasterNodeFileWatchingService implement
Environment environment, Environment environment,
FileSettingsHealthIndicatorService healthIndicatorService FileSettingsHealthIndicatorService healthIndicatorService
) { ) {
super(clusterService, environment.configFile().toAbsolutePath().resolve(OPERATOR_DIRECTORY).resolve(SETTINGS_FILE_NAME)); super(clusterService, environment.configDir().toAbsolutePath().resolve(OPERATOR_DIRECTORY).resolve(SETTINGS_FILE_NAME));
this.stateService = stateService; this.stateService = stateService;
this.healthIndicatorService = healthIndicatorService; this.healthIndicatorService = healthIndicatorService;
} }

View file

@ -104,7 +104,7 @@ public class AbstractFileWatchingServiceTests extends ESTestCase {
env = newEnvironment(Settings.EMPTY); env = newEnvironment(Settings.EMPTY);
Files.createDirectories(env.configFile()); Files.createDirectories(env.configDir());
fileWatchingService = new TestFileWatchingService(getWatchedFilePath(env)); fileWatchingService = new TestFileWatchingService(getWatchedFilePath(env));
} }
@ -203,7 +203,7 @@ public class AbstractFileWatchingServiceTests extends ESTestCase {
} }
private static Path getWatchedFilePath(Environment env) { private static Path getWatchedFilePath(Environment env) {
return env.configFile().toAbsolutePath().resolve("test").resolve("test.json"); return env.configDir().toAbsolutePath().resolve("test").resolve("test.json");
} }
} }

View file

@ -97,7 +97,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testProcessSettingsFile() throws Exception { public void testProcessSettingsFile() throws Exception {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSON);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
assertTrue(secrets.isLoaded()); assertTrue(secrets.isLoaded());
assertThat(secrets.getVersion(), equalTo(1L)); assertThat(secrets.getVersion(), equalTo(1L));
@ -109,7 +109,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testProcessDeprecatedSettingsFile() throws Exception { public void testProcessDeprecatedSettingsFile() throws Exception {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSONDepricated); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSONDepricated);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
assertTrue(secrets.isLoaded()); assertTrue(secrets.isLoaded());
assertThat(secrets.getVersion(), equalTo(1L)); assertThat(secrets.getVersion(), equalTo(1L));
@ -119,7 +119,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testDuplicateSettingKeys() throws Exception { public void testDuplicateSettingKeys() throws Exception {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSONDuplicateKeys); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSONDuplicateKeys);
Exception e = expectThrows(Exception.class, () -> new LocallyMountedSecrets(env)); Exception e = expectThrows(Exception.class, () -> new LocallyMountedSecrets(env));
assertThat(e, instanceOf(XContentParseException.class)); assertThat(e, instanceOf(XContentParseException.class));
assertThat(e.getMessage(), containsString("failed to parse field")); assertThat(e.getMessage(), containsString("failed to parse field"));
@ -134,7 +134,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testSettingsGetFile() throws IOException, GeneralSecurityException { public void testSettingsGetFile() throws IOException, GeneralSecurityException {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSON);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
assertTrue(secrets.isLoaded()); assertTrue(secrets.isLoaded());
assertThat(secrets.getSettingNames(), containsInAnyOrder("aaa", "ccc", "eee")); assertThat(secrets.getSettingNames(), containsInAnyOrder("aaa", "ccc", "eee"));
@ -165,7 +165,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testSettingsSHADigest() throws IOException, GeneralSecurityException { public void testSettingsSHADigest() throws IOException, GeneralSecurityException {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSON);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
assertTrue(secrets.isLoaded()); assertTrue(secrets.isLoaded());
assertThat(secrets.getSettingNames(), containsInAnyOrder("aaa", "ccc", "eee")); assertThat(secrets.getSettingNames(), containsInAnyOrder("aaa", "ccc", "eee"));
@ -178,7 +178,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testProcessBadSettingsFile() throws IOException { public void testProcessBadSettingsFile() throws IOException {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), noMetadataJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), noMetadataJSON);
assertThat( assertThat(
expectThrows(IllegalArgumentException.class, () -> new LocallyMountedSecrets(env)).getMessage(), expectThrows(IllegalArgumentException.class, () -> new LocallyMountedSecrets(env)).getMessage(),
containsString("Required [metadata]") containsString("Required [metadata]")
@ -186,7 +186,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testSerializationWithSecrets() throws Exception { public void testSerializationWithSecrets() throws Exception {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSON);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
final BytesStreamOutput out = new BytesStreamOutput(); final BytesStreamOutput out = new BytesStreamOutput();
@ -213,7 +213,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
} }
public void testClose() throws IOException { public void testClose() throws IOException {
writeTestFile(env.configFile().resolve("secrets").resolve("secrets.json"), testJSON); writeTestFile(env.configDir().resolve("secrets").resolve("secrets.json"), testJSON);
LocallyMountedSecrets secrets = new LocallyMountedSecrets(env); LocallyMountedSecrets secrets = new LocallyMountedSecrets(env);
assertEquals("bbb", secrets.getString("aaa").toString()); assertEquals("bbb", secrets.getString("aaa").toString());
assertEquals("ddd", secrets.getString("ccc").toString()); assertEquals("ddd", secrets.getString("ccc").toString());

View file

@ -34,20 +34,20 @@ public class EnvironmentTests extends ESTestCase {
public void testRepositoryResolution() throws IOException { public void testRepositoryResolution() throws IOException {
Environment environment = newEnvironment(); Environment environment = newEnvironment();
assertThat(environment.resolveRepoFile("/test/repos/repo1"), nullValue()); assertThat(environment.resolveRepoDir("/test/repos/repo1"), nullValue());
assertThat(environment.resolveRepoFile("test/repos/repo1"), nullValue()); assertThat(environment.resolveRepoDir("test/repos/repo1"), nullValue());
environment = newEnvironment( environment = newEnvironment(
Settings.builder() Settings.builder()
.putList(Environment.PATH_REPO_SETTING.getKey(), "/test/repos", "/another/repos", "/test/repos/../other") .putList(Environment.PATH_REPO_SETTING.getKey(), "/test/repos", "/another/repos", "/test/repos/../other")
.build() .build()
); );
assertThat(environment.resolveRepoFile("/test/repos/repo1"), notNullValue()); assertThat(environment.resolveRepoDir("/test/repos/repo1"), notNullValue());
assertThat(environment.resolveRepoFile("test/repos/repo1"), notNullValue()); assertThat(environment.resolveRepoDir("test/repos/repo1"), notNullValue());
assertThat(environment.resolveRepoFile("/another/repos/repo1"), notNullValue()); assertThat(environment.resolveRepoDir("/another/repos/repo1"), notNullValue());
assertThat(environment.resolveRepoFile("/test/repos/../repo1"), nullValue()); assertThat(environment.resolveRepoDir("/test/repos/../repo1"), nullValue());
assertThat(environment.resolveRepoFile("/test/repos/../repos/repo1"), notNullValue()); assertThat(environment.resolveRepoDir("/test/repos/../repos/repo1"), notNullValue());
assertThat(environment.resolveRepoFile("/somethingeles/repos/repo1"), nullValue()); assertThat(environment.resolveRepoDir("/somethingeles/repos/repo1"), nullValue());
assertThat(environment.resolveRepoFile("/test/other/repo"), notNullValue()); assertThat(environment.resolveRepoDir("/test/other/repo"), notNullValue());
assertThat(environment.resolveRepoURL(new URL("file:///test/repos/repo1")), notNullValue()); assertThat(environment.resolveRepoURL(new URL("file:///test/repos/repo1")), notNullValue());
assertThat(environment.resolveRepoURL(new URL("file:/test/repos/repo1")), notNullValue()); assertThat(environment.resolveRepoURL(new URL("file:/test/repos/repo1")), notNullValue());
@ -66,7 +66,7 @@ public class EnvironmentTests extends ESTestCase {
final Path pathHome = createTempDir().toAbsolutePath(); final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build(); final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings, null); final Environment environment = new Environment(settings, null);
assertThat(environment.dataFiles(), equalTo(new Path[] { pathHome.resolve("data") })); assertThat(environment.dataDirs(), equalTo(new Path[] { pathHome.resolve("data") }));
} }
public void testPathDataNotSetInEnvironmentIfNotSet() { public void testPathDataNotSetInEnvironmentIfNotSet() {
@ -82,41 +82,41 @@ public class EnvironmentTests extends ESTestCase {
.put("path.data", createTempDir().toAbsolutePath() + "," + createTempDir().toAbsolutePath()) .put("path.data", createTempDir().toAbsolutePath() + "," + createTempDir().toAbsolutePath())
.build(); .build();
final Environment environment = new Environment(settings, null); final Environment environment = new Environment(settings, null);
assertThat(environment.dataFiles(), arrayWithSize(2)); assertThat(environment.dataDirs(), arrayWithSize(2));
} }
public void testPathLogsWhenNotSet() { public void testPathLogsWhenNotSet() {
final Path pathHome = createTempDir().toAbsolutePath(); final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build(); final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings, null); final Environment environment = new Environment(settings, null);
assertThat(environment.logsFile(), equalTo(pathHome.resolve("logs"))); assertThat(environment.logsDir(), equalTo(pathHome.resolve("logs")));
} }
public void testDefaultConfigPath() { public void testDefaultConfigPath() {
final Path path = createTempDir().toAbsolutePath(); final Path path = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", path).build(); final Settings settings = Settings.builder().put("path.home", path).build();
final Environment environment = new Environment(settings, null); final Environment environment = new Environment(settings, null);
assertThat(environment.configFile(), equalTo(path.resolve("config"))); assertThat(environment.configDir(), equalTo(path.resolve("config")));
} }
public void testConfigPath() { public void testConfigPath() {
final Path configPath = createTempDir().toAbsolutePath(); final Path configPath = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", createTempDir().toAbsolutePath()).build(); final Settings settings = Settings.builder().put("path.home", createTempDir().toAbsolutePath()).build();
final Environment environment = new Environment(settings, configPath); final Environment environment = new Environment(settings, configPath);
assertThat(environment.configFile(), equalTo(configPath)); assertThat(environment.configDir(), equalTo(configPath));
} }
public void testConfigPathWhenNotSet() { public void testConfigPathWhenNotSet() {
final Path pathHome = createTempDir().toAbsolutePath(); final Path pathHome = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder().put("path.home", pathHome).build(); final Settings settings = Settings.builder().put("path.home", pathHome).build();
final Environment environment = new Environment(settings, null); final Environment environment = new Environment(settings, null);
assertThat(environment.configFile(), equalTo(pathHome.resolve("config"))); assertThat(environment.configDir(), equalTo(pathHome.resolve("config")));
} }
public void testNonExistentTempPathValidation() { public void testNonExistentTempPathValidation() {
Settings build = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build(); Settings build = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build();
Environment environment = new Environment(build, null, createTempDir().resolve("this_does_not_exist")); Environment environment = new Environment(build, null, createTempDir().resolve("this_does_not_exist"));
FileNotFoundException e = expectThrows(FileNotFoundException.class, environment::validateTmpFile); FileNotFoundException e = expectThrows(FileNotFoundException.class, environment::validateTmpDir);
assertThat(e.getMessage(), startsWith("Temporary directory [")); assertThat(e.getMessage(), startsWith("Temporary directory ["));
assertThat(e.getMessage(), endsWith("this_does_not_exist] does not exist or is not accessible")); assertThat(e.getMessage(), endsWith("this_does_not_exist] does not exist or is not accessible"));
} }
@ -124,7 +124,7 @@ public class EnvironmentTests extends ESTestCase {
public void testTempPathValidationWhenRegularFile() throws IOException { public void testTempPathValidationWhenRegularFile() throws IOException {
Settings build = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build(); Settings build = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build();
Environment environment = new Environment(build, null, createTempFile("something", ".test")); Environment environment = new Environment(build, null, createTempFile("something", ".test"));
IOException e = expectThrows(IOException.class, environment::validateTmpFile); IOException e = expectThrows(IOException.class, environment::validateTmpDir);
assertThat(e.getMessage(), startsWith("Temporary directory [")); assertThat(e.getMessage(), startsWith("Temporary directory ["));
assertThat(e.getMessage(), endsWith(".test] is not a directory")); assertThat(e.getMessage(), endsWith(".test] is not a directory"));
} }

View file

@ -131,7 +131,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
boolean hasClusterState = randomBoolean(); boolean hasClusterState = randomBoolean();
createIndexDataFiles(dataMasterSettings, shardCount, hasClusterState); createIndexDataFiles(dataMasterSettings, shardCount, hasClusterState);
String messageText = NodeRepurposeCommand.noMasterMessage(1, environment.dataFiles().length * shardCount, 0); String messageText = NodeRepurposeCommand.noMasterMessage(1, environment.dataDirs().length * shardCount, 0);
Matcher<String> outputMatcher = allOf( Matcher<String> outputMatcher = allOf(
containsString(messageText), containsString(messageText),
@ -157,7 +157,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
createIndexDataFiles(dataMasterSettings, shardCount, hasClusterState); createIndexDataFiles(dataMasterSettings, shardCount, hasClusterState);
Matcher<String> matcher = allOf( Matcher<String> matcher = allOf(
containsString(NodeRepurposeCommand.shardMessage(environment.dataFiles().length * shardCount, 1)), containsString(NodeRepurposeCommand.shardMessage(environment.dataDirs().length * shardCount, 1)),
conditionalNot(containsString("testUUID"), verbose == false), conditionalNot(containsString("testUUID"), verbose == false),
conditionalNot(containsString("testIndex"), verbose == false || hasClusterState == false), conditionalNot(containsString("testIndex"), verbose == false || hasClusterState == false),
conditionalNot(containsString("no name for uuid: testUUID"), verbose == false || hasClusterState) conditionalNot(containsString("no name for uuid: testUUID"), verbose == false || hasClusterState)
@ -271,7 +271,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
private long digestPaths() { private long digestPaths() {
// use a commutative digest to avoid dependency on file system order. // use a commutative digest to avoid dependency on file system order.
return Arrays.stream(environment.dataFiles()).mapToLong(this::digestPath).sum(); return Arrays.stream(environment.dataDirs()).mapToLong(this::digestPath).sum();
} }
private long digestPath(Path path) { private long digestPath(Path path) {

View file

@ -453,7 +453,7 @@ public class AnalysisModuleTests extends ESTestCase {
InputStream aff = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.aff"); 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"); InputStream dic = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.dic");
Dictionary dictionary; Dictionary dictionary;
try (Directory tmp = newFSDirectory(environment.tmpFile())) { try (Directory tmp = newFSDirectory(environment.tmpDir())) {
dictionary = new Dictionary(tmp, "hunspell", aff, dic); dictionary = new Dictionary(tmp, "hunspell", aff, dic);
} }
AnalysisModule module = new AnalysisModule(environment, singletonList(new AnalysisPlugin() { AnalysisModule module = new AnalysisModule(environment, singletonList(new AnalysisPlugin() {

View file

@ -57,7 +57,7 @@ public class InternalSettingsPreparerTests extends ESTestCase {
assertEquals(defaultNodeName, settings.get("node.name")); assertEquals(defaultNodeName, settings.get("node.name"));
assertNotNull(settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey())); // a cluster name was set assertNotNull(settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey())); // a cluster name was set
String home = Environment.PATH_HOME_SETTING.get(baseEnvSettings); String home = Environment.PATH_HOME_SETTING.get(baseEnvSettings);
String configDir = env.configFile().toString(); String configDir = env.configDir().toString();
assertTrue(configDir, configDir.startsWith(home)); assertTrue(configDir, configDir.startsWith(home));
assertEquals("elasticsearch", settings.get("cluster.name")); assertEquals("elasticsearch", settings.get("cluster.name"));
} }

View file

@ -52,7 +52,7 @@ public class PluginsLoaderTests extends ESTestCase {
static PluginsLoader newPluginsLoader(Settings settings) { static PluginsLoader newPluginsLoader(Settings settings) {
return PluginsLoader.createPluginsLoader( return PluginsLoader.createPluginsLoader(
Set.of(), Set.of(),
PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsFile()), PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsDir()),
Map.of(), Map.of(),
false false
); );
@ -121,7 +121,7 @@ public class PluginsLoaderTests extends ESTestCase {
var pluginsLoader = PluginsLoader.createPluginsLoader( var pluginsLoader = PluginsLoader.createPluginsLoader(
Set.of(), Set.of(),
PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsFile()), PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsDir()),
Map.of(STABLE_PLUGIN_NAME, Set.of(STABLE_PLUGIN_MODULE_NAME)), Map.of(STABLE_PLUGIN_NAME, Set.of(STABLE_PLUGIN_MODULE_NAME)),
false false
); );
@ -182,7 +182,7 @@ public class PluginsLoaderTests extends ESTestCase {
var pluginsLoader = PluginsLoader.createPluginsLoader( var pluginsLoader = PluginsLoader.createPluginsLoader(
Set.of(), Set.of(),
PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsFile()), PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsDir()),
Map.of(MODULAR_PLUGIN_NAME, Set.of(MODULAR_PLUGIN_MODULE_NAME)), Map.of(MODULAR_PLUGIN_NAME, Set.of(MODULAR_PLUGIN_MODULE_NAME)),
false false
); );

View file

@ -70,7 +70,7 @@ public class PluginsServiceTests extends ESTestCase {
null, null,
PluginsLoader.createPluginsLoader( PluginsLoader.createPluginsLoader(
Set.of(), Set.of(),
PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsFile()), PluginsLoader.loadPluginsBundles(TestEnvironment.newEnvironment(settings).pluginsDir()),
Map.of(), Map.of(),
false false
) )

View file

@ -127,7 +127,7 @@ public class FileSettingsServiceTests extends ESTestCase {
clusterService.getMasterService().setClusterStateSupplier(() -> clusterState); clusterService.getMasterService().setClusterStateSupplier(() -> clusterState);
env = newEnvironment(Settings.EMPTY); env = newEnvironment(Settings.EMPTY);
Files.createDirectories(env.configFile()); Files.createDirectories(env.configDir());
ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
@ -176,7 +176,7 @@ public class FileSettingsServiceTests extends ESTestCase {
public void testOperatorDirName() { public void testOperatorDirName() {
Path operatorPath = fileSettingsService.watchedFileDir(); Path operatorPath = fileSettingsService.watchedFileDir();
assertTrue(operatorPath.startsWith(env.configFile())); assertTrue(operatorPath.startsWith(env.configDir()));
assertTrue(operatorPath.endsWith("operator")); assertTrue(operatorPath.endsWith("operator"));
Path operatorSettingsFile = fileSettingsService.watchedFile(); Path operatorSettingsFile = fileSettingsService.watchedFile();

View file

@ -94,7 +94,7 @@ public class DiskUsageIntegTestCase extends ESIntegTestCase {
} }
public TestFileStore getTestFileStore(String nodeName) { public TestFileStore getTestFileStore(String nodeName) {
return fileSystemProvider.getTestFileStore(internalCluster().getInstance(Environment.class, nodeName).dataFiles()[0]); return fileSystemProvider.getTestFileStore(internalCluster().getInstance(Environment.class, nodeName).dataDirs()[0]);
} }
protected static class TestFileStore extends FilterFileStore { protected static class TestFileStore extends FilterFileStore {

View file

@ -662,7 +662,7 @@ public final class DataStreamTestHelper {
).build(MapperBuilderContext.root(false, true)); ).build(MapperBuilderContext.root(false, true));
ClusterService clusterService = ClusterServiceUtils.createClusterService(testThreadPool); ClusterService clusterService = ClusterServiceUtils.createClusterService(testThreadPool);
Environment env = mock(Environment.class); Environment env = mock(Environment.class);
when(env.sharedDataFile()).thenReturn(null); when(env.sharedDataDir()).thenReturn(null);
AllocationService allocationService = mock(AllocationService.class); AllocationService allocationService = mock(AllocationService.class);
when(allocationService.reroute(any(ClusterState.class), any(String.class), any())).then(i -> i.getArguments()[0]); when(allocationService.reroute(any(ClusterState.class), any(String.class), any())).then(i -> i.getArguments()[0]);
when(allocationService.getShardRoutingRoleStrategy()).thenReturn(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY); when(allocationService.getShardRoutingRoleStrategy()).thenReturn(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY);

View file

@ -42,16 +42,12 @@ public class MockPluginsService extends PluginsService {
* @param classpathPlugins Plugins that exist in the classpath which should be loaded * @param classpathPlugins Plugins that exist in the classpath which should be loaded
*/ */
public MockPluginsService(Settings settings, Environment environment, Collection<Class<? extends Plugin>> classpathPlugins) { public MockPluginsService(Settings settings, Environment environment, Collection<Class<? extends Plugin>> classpathPlugins) {
super( super(settings, environment.configDir(), new PluginsLoader(Collections.emptySet(), Collections.emptySet(), Collections.emptyMap()));
settings,
environment.configFile(),
new PluginsLoader(Collections.emptySet(), Collections.emptySet(), Collections.emptyMap())
);
List<LoadedPlugin> pluginsLoaded = new ArrayList<>(); List<LoadedPlugin> pluginsLoaded = new ArrayList<>();
for (Class<? extends Plugin> pluginClass : classpathPlugins) { for (Class<? extends Plugin> pluginClass : classpathPlugins) {
Plugin plugin = loadPlugin(pluginClass, settings, environment.configFile()); Plugin plugin = loadPlugin(pluginClass, settings, environment.configDir());
PluginDescriptor pluginInfo = new PluginDescriptor( PluginDescriptor pluginInfo = new PluginDescriptor(
pluginClass.getName(), pluginClass.getName(),
"classpath plugin", "classpath plugin",

View file

@ -2263,7 +2263,7 @@ public abstract class ESIntegTestCase extends ESTestCase {
*/ */
public static Path randomRepoPath(Settings settings) { public static Path randomRepoPath(Settings settings) {
Environment environment = TestEnvironment.newEnvironment(settings); Environment environment = TestEnvironment.newEnvironment(settings);
Path[] repoFiles = environment.repoFiles(); Path[] repoFiles = environment.repoDirs();
assert repoFiles.length > 0; assert repoFiles.length > 0;
Path path; Path path;
do { do {

View file

@ -1808,7 +1808,7 @@ public final class InternalTestCluster extends TestCluster {
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
Set<Path> configPaths = Stream.concat(currentNodes.stream(), newNodes.stream()) Set<Path> configPaths = Stream.concat(currentNodes.stream(), newNodes.stream())
.map(nac -> nac.node.getEnvironment().configFile()) .map(nac -> nac.node.getEnvironment().configDir())
.collect(Collectors.toSet()); .collect(Collectors.toSet());
logger.debug("configuring discovery with {} at {}", discoveryFileContents, configPaths); logger.debug("configuring discovery with {} at {}", discoveryFileContents, configPaths);
for (final Path configPath : configPaths) { for (final Path configPath : configPaths) {
@ -1822,7 +1822,7 @@ public final class InternalTestCluster extends TestCluster {
} }
public Collection<Path> configPaths() { public Collection<Path> configPaths() {
return nodes.values().stream().map(nac -> nac.node.getEnvironment().configFile()).toList(); return nodes.values().stream().map(nac -> nac.node.getEnvironment().configDir()).toList();
} }
private void stopNodesAndClient(NodeAndClient nodeAndClient) throws IOException { private void stopNodesAndClient(NodeAndClient nodeAndClient) throws IOException {

View file

@ -411,9 +411,9 @@ public class XPackPlugin extends XPackClientPlugin
} }
public static Path resolveConfigFile(Environment env, String name) { public static Path resolveConfigFile(Environment env, String name) {
Path config = env.configFile().resolve(name); Path config = env.configDir().resolve(name);
if (Files.exists(config) == false) { if (Files.exists(config) == false) {
Path legacyConfig = env.configFile().resolve("x-pack").resolve(name); Path legacyConfig = env.configDir().resolve("x-pack").resolve(name);
if (Files.exists(legacyConfig)) { if (Files.exists(legacyConfig)) {
deprecationLogger.warn( deprecationLogger.warn(
DeprecationCategory.OTHER, DeprecationCategory.OTHER,

View file

@ -146,7 +146,7 @@ public class CertParsingUtils {
boolean acceptNonSecurePasswords boolean acceptNonSecurePasswords
) { ) {
final SslSettingsLoader settingsLoader = new SslSettingsLoader(settings, prefix, acceptNonSecurePasswords); final SslSettingsLoader settingsLoader = new SslSettingsLoader(settings, prefix, acceptNonSecurePasswords);
return settingsLoader.buildKeyConfig(environment.configFile()); return settingsLoader.buildKeyConfig(environment.configDir());
} }
/** /**

View file

@ -128,7 +128,7 @@ public final class SslSettingsLoader extends SslConfigurationLoader {
} }
public SslConfiguration load(Environment env) { public SslConfiguration load(Environment env) {
return load(env.configFile()); return load(env.configDir());
} }
public static SslConfiguration load(Settings settings, String prefix, Environment env) { public static SslConfiguration load(Settings settings, String prefix, Environment env) {

View file

@ -143,7 +143,7 @@ public class XPackPluginTests extends ESTestCase {
Environment mockEnvironment = mock(Environment.class); Environment mockEnvironment = mock(Environment.class);
when(mockEnvironment.settings()).thenReturn(Settings.builder().build()); when(mockEnvironment.settings()).thenReturn(Settings.builder().build());
when(mockEnvironment.configFile()).thenReturn(PathUtils.get("")); when(mockEnvironment.configDir()).thenReturn(PathUtils.get(""));
// ensure createComponents does not influence the results // ensure createComponents does not influence the results
Plugin.PluginServices services = mock(Plugin.PluginServices.class); Plugin.PluginServices services = mock(Plugin.PluginServices.class);
when(services.clusterService()).thenReturn(mock(ClusterService.class)); when(services.clusterService()).thenReturn(mock(ClusterService.class));
@ -187,7 +187,7 @@ public class XPackPluginTests extends ESTestCase {
}); });
Environment mockEnvironment = mock(Environment.class); Environment mockEnvironment = mock(Environment.class);
when(mockEnvironment.settings()).thenReturn(Settings.builder().build()); when(mockEnvironment.settings()).thenReturn(Settings.builder().build());
when(mockEnvironment.configFile()).thenReturn(PathUtils.get("")); when(mockEnvironment.configDir()).thenReturn(PathUtils.get(""));
Plugin.PluginServices services = mock(Plugin.PluginServices.class); Plugin.PluginServices services = mock(Plugin.PluginServices.class);
when(services.clusterService()).thenReturn(mock(ClusterService.class)); when(services.clusterService()).thenReturn(mock(ClusterService.class));
when(services.threadPool()).thenReturn(mock(ThreadPool.class)); when(services.threadPool()).thenReturn(mock(ThreadPool.class));

View file

@ -229,7 +229,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configDir()))
); );
} }
@ -244,7 +244,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configDir()))
); );
assertSettingDeprecationsAndWarnings(new Setting<?>[] { configurationSettings.x509KeyPair.legacyKeystorePassword }); assertSettingDeprecationsAndWarnings(new Setting<?>[] { configurationSettings.x509KeyPair.legacyKeystorePassword });
} }
@ -263,7 +263,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir()))
); );
} }
@ -279,7 +279,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir()))
); );
assertSettingDeprecationsAndWarnings( assertSettingDeprecationsAndWarnings(
new Setting<?>[] { new Setting<?>[] {
@ -298,7 +298,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("xpack/tls/path.jks", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("xpack/tls/path.jks", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir()))
); );
} }
@ -314,7 +314,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig(path, PASSWORD, "PKCS12", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig(path, PASSWORD, "PKCS12", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir()))
); );
} }
@ -328,7 +328,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(
ksKeyInfo, ksKeyInfo,
equalTo(new StoreKeyConfig("xpack/tls/path.foo", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) equalTo(new StoreKeyConfig("xpack/tls/path.foo", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir()))
); );
} }
@ -347,10 +347,7 @@ public class SslSettingsLoaderTests extends ESTestCase {
SslConfiguration sslConfiguration = getSslConfiguration(settings); SslConfiguration sslConfiguration = getSslConfiguration(settings);
assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class));
StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig();
assertThat( assertThat(ksKeyInfo, equalTo(new StoreKeyConfig(path, PASSWORD, type, null, KEYPASS, KEY_MGR_ALGORITHM, environment.configDir())));
ksKeyInfo,
equalTo(new StoreKeyConfig(path, PASSWORD, type, null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile()))
);
} }
public void testThatEmptySettingsAreEqual() { public void testThatEmptySettingsAreEqual() {

View file

@ -109,7 +109,7 @@ public class MachineLearningPackageLoader extends Plugin implements ActionPlugin
@Override @Override
public BootstrapCheckResult check(BootstrapContext context) { public BootstrapCheckResult check(BootstrapContext context) {
try { try {
validateModelRepository(MODEL_REPOSITORY.get(context.settings()), context.environment().configFile()); validateModelRepository(MODEL_REPOSITORY.get(context.settings()), context.environment().configDir());
} catch (Exception e) { } catch (Exception e) {
return BootstrapCheckResult.failure( return BootstrapCheckResult.failure(
"Found an invalid configuration for xpack.ml.model_repository. " "Found an invalid configuration for xpack.ml.model_repository. "

View file

@ -149,7 +149,7 @@ public class NativeAnalyticsProcessFactory implements AnalyticsProcessFactory<An
ProcessPipes processPipes ProcessPipes processPipes
) { ) {
AnalyticsBuilder analyticsBuilder = new AnalyticsBuilder( AnalyticsBuilder analyticsBuilder = new AnalyticsBuilder(
env::tmpFile, env::tmpDir,
nativeController, nativeController,
processPipes, processPipes,
analyticsProcessConfig, analyticsProcessConfig,

View file

@ -116,7 +116,7 @@ public class NativeMemoryUsageEstimationProcessFactory implements AnalyticsProce
ProcessPipes processPipes ProcessPipes processPipes
) { ) {
AnalyticsBuilder analyticsBuilder = new AnalyticsBuilder( AnalyticsBuilder analyticsBuilder = new AnalyticsBuilder(
env::tmpFile, env::tmpDir,
nativeController, nativeController,
processPipes, processPipes,
analyticsProcessConfig, analyticsProcessConfig,

View file

@ -209,9 +209,9 @@ public class AutodetectBuilder {
// createTempFile has a race condition where it may return the same // createTempFile has a race condition where it may return the same
// temporary file name to different threads if called simultaneously // temporary file name to different threads if called simultaneously
// from multiple threads, hence add the thread ID to avoid this // from multiple threads, hence add the thread ID to avoid this
FileUtils.recreateTempDirectoryIfNeeded(env.tmpFile()); FileUtils.recreateTempDirectoryIfNeeded(env.tmpDir());
Path stateFile = Files.createTempFile( Path stateFile = Files.createTempFile(
env.tmpFile(), env.tmpDir(),
jobId + "_quantiles_" + Thread.currentThread().getId(), jobId + "_quantiles_" + Thread.currentThread().getId(),
QUANTILES_FILE_EXTENSION QUANTILES_FILE_EXTENSION
); );
@ -227,8 +227,8 @@ public class AutodetectBuilder {
if (scheduledEvents.isEmpty()) { if (scheduledEvents.isEmpty()) {
return; return;
} }
FileUtils.recreateTempDirectoryIfNeeded(env.tmpFile()); FileUtils.recreateTempDirectoryIfNeeded(env.tmpDir());
Path eventsConfigFile = Files.createTempFile(env.tmpFile(), "eventsConfig", JSON_EXTENSION); Path eventsConfigFile = Files.createTempFile(env.tmpDir(), "eventsConfig", JSON_EXTENSION);
filesToDelete.add(eventsConfigFile); filesToDelete.add(eventsConfigFile);
List<ScheduledEventToRuleWriter> scheduledEventToRuleWriters = scheduledEvents.stream() List<ScheduledEventToRuleWriter> scheduledEventToRuleWriters = scheduledEvents.stream()
@ -252,8 +252,8 @@ public class AutodetectBuilder {
} }
private void buildJobConfig(List<String> command) throws IOException { private void buildJobConfig(List<String> command) throws IOException {
FileUtils.recreateTempDirectoryIfNeeded(env.tmpFile()); FileUtils.recreateTempDirectoryIfNeeded(env.tmpDir());
Path configFile = Files.createTempFile(env.tmpFile(), "config", JSON_EXTENSION); Path configFile = Files.createTempFile(env.tmpDir(), "config", JSON_EXTENSION);
filesToDelete.add(configFile); filesToDelete.add(configFile);
try ( try (
OutputStreamWriter osw = new OutputStreamWriter(Files.newOutputStream(configFile), StandardCharsets.UTF_8); OutputStreamWriter osw = new OutputStreamWriter(Files.newOutputStream(configFile), StandardCharsets.UTF_8);
@ -271,8 +271,8 @@ public class AutodetectBuilder {
if (referencedFilters.isEmpty()) { if (referencedFilters.isEmpty()) {
return; return;
} }
FileUtils.recreateTempDirectoryIfNeeded(env.tmpFile()); FileUtils.recreateTempDirectoryIfNeeded(env.tmpDir());
Path filtersConfigFile = Files.createTempFile(env.tmpFile(), "filtersConfig", JSON_EXTENSION); Path filtersConfigFile = Files.createTempFile(env.tmpDir(), "filtersConfig", JSON_EXTENSION);
filesToDelete.add(filtersConfigFile); filesToDelete.add(filtersConfigFile);
try ( try (

View file

@ -52,7 +52,7 @@ public class NativeStorageProvider {
*/ */
public void cleanupLocalTmpStorageInCaseOfUncleanShutdown() { public void cleanupLocalTmpStorageInCaseOfUncleanShutdown() {
try { try {
for (Path p : environment.dataFiles()) { for (Path p : environment.dataDirs()) {
IOUtils.rm(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER)); IOUtils.rm(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER));
} }
} catch (Exception e) { } catch (Exception e) {
@ -79,7 +79,7 @@ public class NativeStorageProvider {
} }
private Path tryAllocateStorage(String uniqueIdentifier, ByteSizeValue requestedSize) { private Path tryAllocateStorage(String uniqueIdentifier, ByteSizeValue requestedSize) {
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
try { try {
if (getUsableSpace(path) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes()) { if (getUsableSpace(path) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes()) {
Path tmpDirectory = path.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER).resolve(uniqueIdentifier); Path tmpDirectory = path.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER).resolve(uniqueIdentifier);
@ -97,7 +97,7 @@ public class NativeStorageProvider {
public boolean localTmpStorageHasEnoughSpace(Path path, ByteSizeValue requestedSize) { public boolean localTmpStorageHasEnoughSpace(Path path, ByteSizeValue requestedSize) {
Path realPath = path.toAbsolutePath(); Path realPath = path.toAbsolutePath();
for (Path p : environment.dataFiles()) { for (Path p : environment.dataDirs()) {
try { try {
if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) { if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
return getUsableSpace(p) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes(); return getUsableSpace(p) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes();
@ -122,7 +122,7 @@ public class NativeStorageProvider {
if (path != null) { if (path != null) {
// do not allow to breakout from the tmp storage provided // do not allow to breakout from the tmp storage provided
Path realPath = path.toAbsolutePath(); Path realPath = path.toAbsolutePath();
for (Path p : environment.dataFiles()) { for (Path p : environment.dataDirs()) {
if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) { if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
IOUtils.rm(path); IOUtils.rm(path);
} }

View file

@ -94,7 +94,7 @@ public class ProcessPipes {
) { ) {
this.namedPipeHelper = namedPipeHelper; this.namedPipeHelper = namedPipeHelper;
this.jobId = jobId; this.jobId = jobId;
this.tempDir = env.tmpFile(); this.tempDir = env.tmpDir();
this.timeout = timeout; this.timeout = timeout;
// The way the pipe names are formed MUST match what is done in the controller main() // The way the pipe names are formed MUST match what is done in the controller main()

View file

@ -78,7 +78,7 @@ public class NamedPipeHelper {
// All these factors need to align for everything to work in production. If any changes // All these factors need to align for everything to work in production. If any changes
// are made here then CNamedPipeFactory::defaultPath() in the C++ code will probably // are made here then CNamedPipeFactory::defaultPath() in the C++ code will probably
// also need to be changed. // also need to be changed.
return env.tmpFile().toString() + PathUtils.getDefaultFileSystem().getSeparator(); return env.tmpDir().toString() + PathUtils.getDefaultFileSystem().getSeparator();
} }
/** /**

View file

@ -123,7 +123,7 @@ public class NativeStorageProviderTests extends ESTestCase {
private NativeStorageProvider createNativeStorageProvider(Map<Path, Long> paths) throws IOException { private NativeStorageProvider createNativeStorageProvider(Map<Path, Long> paths) throws IOException {
Environment environment = mock(Environment.class); Environment environment = mock(Environment.class);
when(environment.dataFiles()).thenReturn(paths.keySet().toArray(new Path[paths.size()])); when(environment.dataDirs()).thenReturn(paths.keySet().toArray(new Path[paths.size()]));
NativeStorageProvider storageProvider = spy(new NativeStorageProvider(environment, ByteSizeValue.ofGb(5))); NativeStorageProvider storageProvider = spy(new NativeStorageProvider(environment, ByteSizeValue.ofGb(5)));
doAnswer( doAnswer(

View file

@ -67,7 +67,7 @@ public class NamedPipeHelperTests extends ESTestCase {
Environment env = TestEnvironment.newEnvironment( Environment env = TestEnvironment.newEnvironment(
Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build() Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build()
); );
Path tempFile = Files.createTempFile(env.tmpFile(), "not a named pipe", null); Path tempFile = Files.createTempFile(env.tmpDir(), "not a named pipe", null);
IOException ioe = ESTestCase.expectThrows( IOException ioe = ESTestCase.expectThrows(
IOException.class, IOException.class,
@ -83,7 +83,7 @@ public class NamedPipeHelperTests extends ESTestCase {
Environment env = TestEnvironment.newEnvironment( Environment env = TestEnvironment.newEnvironment(
Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build() Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build()
); );
Path tempFile = Files.createTempFile(env.tmpFile(), "not a named pipe", null); Path tempFile = Files.createTempFile(env.tmpDir(), "not a named pipe", null);
IOException ioe = ESTestCase.expectThrows( IOException ioe = ESTestCase.expectThrows(
IOException.class, IOException.class,

View file

@ -820,7 +820,7 @@ public class SearchableSnapshotsIntegTests extends BaseSearchableSnapshotsIntegT
final String tmpRepositoryName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT); final String tmpRepositoryName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
createRepositoryNoVerify(tmpRepositoryName, "fs"); createRepositoryNoVerify(tmpRepositoryName, "fs");
final Path repoPath = internalCluster().getCurrentMasterNodeInstance(Environment.class) final Path repoPath = internalCluster().getCurrentMasterNodeInstance(Environment.class)
.resolveRepoFile( .resolveRepoDir(
clusterAdmin().prepareGetRepositories(TEST_REQUEST_TIMEOUT, tmpRepositoryName) clusterAdmin().prepareGetRepositories(TEST_REQUEST_TIMEOUT, tmpRepositoryName)
.get() .get()
.repositories() .repositories()

View file

@ -145,7 +145,7 @@ public class SearchableSnapshotsPrewarmingIntegTests extends ESSingleNodeTestCas
docsPerIndex.put(indexName, nbDocs); docsPerIndex.put(indexName, nbDocs);
} }
final Path repositoryPath = node().getEnvironment().resolveRepoFile(randomAlphaOfLength(10)); final Path repositoryPath = node().getEnvironment().resolveRepoDir(randomAlphaOfLength(10));
final Settings.Builder repositorySettings = Settings.builder().put("location", repositoryPath); final Settings.Builder repositorySettings = Settings.builder().put("location", repositoryPath);
if (randomBoolean()) { if (randomBoolean()) {
repositorySettings.put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES); repositorySettings.put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES);

View file

@ -98,7 +98,7 @@ public class FrozenIndexInputTests extends AbstractSearchableSnapshotsTestCase {
.put("path.home", createTempDir()) .put("path.home", createTempDir())
.build(); .build();
final Environment environment = TestEnvironment.newEnvironment(settings); final Environment environment = TestEnvironment.newEnvironment(settings);
for (Path path : environment.dataFiles()) { for (Path path : environment.dataDirs()) {
Files.createDirectories(path); Files.createDirectories(path);
} }
SnapshotId snapshotId = new SnapshotId("_name", "_uuid"); SnapshotId snapshotId = new SnapshotId("_name", "_uuid");

View file

@ -163,7 +163,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
final boolean inEnrollmentMode = options.has(enrollmentTokenParam); final boolean inEnrollmentMode = options.has(enrollmentTokenParam);
// skipping security auto-configuration because node considered as restarting. // skipping security auto-configuration because node considered as restarting.
for (Path dataPath : env.dataFiles()) { for (Path dataPath : env.dataDirs()) {
if (Files.isDirectory(dataPath) && false == isDirEmpty(dataPath)) { if (Files.isDirectory(dataPath) && false == isDirEmpty(dataPath)) {
final String msg = "Skipping security auto configuration because it appears that the node is not starting up for the " final String msg = "Skipping security auto configuration because it appears that the node is not starting up for the "
+ "first time. The node might already be part of a cluster and this auto setup utility is designed to configure " + "first time. The node might already be part of a cluster and this auto setup utility is designed to configure "
@ -173,7 +173,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
// pre-flight checks for the files that are going to be changed // pre-flight checks for the files that are going to be changed
final Path ymlPath = env.configFile().resolve("elasticsearch.yml"); final Path ymlPath = env.configDir().resolve("elasticsearch.yml");
// it is odd for the `elasticsearch.yml` file to be missing or not be a regular (the node won't start) // it is odd for the `elasticsearch.yml` file to be missing or not be a regular (the node won't start)
// but auto configuration should not be concerned with fixing it (by creating the file) and let the node startup fail // but auto configuration should not be concerned with fixing it (by creating the file) and let the node startup fail
if (false == Files.exists(ymlPath) || false == Files.isRegularFile(ymlPath, LinkOption.NOFOLLOW_LINKS)) { if (false == Files.exists(ymlPath) || false == Files.isRegularFile(ymlPath, LinkOption.NOFOLLOW_LINKS)) {
@ -194,7 +194,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
); );
notifyOfFailure(inEnrollmentMode, terminal, Terminal.Verbosity.NORMAL, ExitCodes.NOOP, msg); notifyOfFailure(inEnrollmentMode, terminal, Terminal.Verbosity.NORMAL, ExitCodes.NOOP, msg);
} }
final Path keystorePath = KeyStoreWrapper.keystorePath(env.configFile()); final Path keystorePath = KeyStoreWrapper.keystorePath(env.configDir());
// Inform that auto-configuration will not run if keystore cannot be read. // Inform that auto-configuration will not run if keystore cannot be read.
if (Files.exists(keystorePath) if (Files.exists(keystorePath)
&& (false == Files.isRegularFile(keystorePath, LinkOption.NOFOLLOW_LINKS) || false == Files.isReadable(keystorePath))) { && (false == Files.isRegularFile(keystorePath, LinkOption.NOFOLLOW_LINKS) || false == Files.isReadable(keystorePath))) {
@ -218,7 +218,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
checkExistingConfiguration(env.settings(), inEnrollmentMode, terminal); checkExistingConfiguration(env.settings(), inEnrollmentMode, terminal);
final ZonedDateTime autoConfigDate = ZonedDateTime.now(ZoneOffset.UTC); final ZonedDateTime autoConfigDate = ZonedDateTime.now(ZoneOffset.UTC);
final Path tempGeneratedTlsCertsDir = env.configFile() final Path tempGeneratedTlsCertsDir = env.configDir()
.resolve(String.format(Locale.ROOT, TLS_GENERATED_CERTS_DIR_NAME + ".%d.tmp", autoConfigDate.toInstant().getEpochSecond())); .resolve(String.format(Locale.ROOT, TLS_GENERATED_CERTS_DIR_NAME + ".%d.tmp", autoConfigDate.toInstant().getEpochSecond()));
try { try {
// it is useful to pre-create the sub-config dir in order to check that the config dir is writable and that file owners match // it is useful to pre-create the sub-config dir in order to check that the config dir is writable and that file owners match
@ -247,12 +247,12 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
// If the node process works OK given the owner of the config dir, it should also tolerate the auto-created config dir, // If the node process works OK given the owner of the config dir, it should also tolerate the auto-created config dir,
// provided that they both have the same owner and permissions. // provided that they both have the same owner and permissions.
final UserPrincipal newFileOwner = Files.getOwner(tempGeneratedTlsCertsDir, LinkOption.NOFOLLOW_LINKS); final UserPrincipal newFileOwner = Files.getOwner(tempGeneratedTlsCertsDir, LinkOption.NOFOLLOW_LINKS);
if (false == newFileOwner.equals(Files.getOwner(env.configFile(), LinkOption.NOFOLLOW_LINKS))) { if (false == newFileOwner.equals(Files.getOwner(env.configDir(), LinkOption.NOFOLLOW_LINKS))) {
// the following is only printed once, if the node starts successfully // the following is only printed once, if the node starts successfully
UserException userException = new UserException( UserException userException = new UserException(
ExitCodes.CONFIG, ExitCodes.CONFIG,
"Aborting auto configuration because of config dir ownership mismatch. Config dir is owned by " "Aborting auto configuration because of config dir ownership mismatch. Config dir is owned by "
+ Files.getOwner(env.configFile(), LinkOption.NOFOLLOW_LINKS).getName() + Files.getOwner(env.configDir(), LinkOption.NOFOLLOW_LINKS).getName()
+ " but auto-configuration directory would be owned by " + " but auto-configuration directory would be owned by "
+ newFileOwner.getName() + newFileOwner.getName()
); );
@ -496,7 +496,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
// save the existing keystore before replacing // save the existing keystore before replacing
final Path keystoreBackupPath = env.configFile() final Path keystoreBackupPath = env.configDir()
.resolve( .resolve(
String.format(Locale.ROOT, KeyStoreWrapper.KEYSTORE_FILENAME + ".%d.orig", autoConfigDate.toInstant().getEpochSecond()) String.format(Locale.ROOT, KeyStoreWrapper.KEYSTORE_FILENAME + ".%d.orig", autoConfigDate.toInstant().getEpochSecond())
); );
@ -514,7 +514,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
final SetOnce<SecureString> nodeKeystorePassword = new SetOnce<>(); final SetOnce<SecureString> nodeKeystorePassword = new SetOnce<>();
try (KeyStoreWrapper nodeKeystore = KeyStoreWrapper.bootstrap(env.configFile(), () -> { try (KeyStoreWrapper nodeKeystore = KeyStoreWrapper.bootstrap(env.configDir(), () -> {
nodeKeystorePassword.set(new SecureString(terminal.readSecret(""))); nodeKeystorePassword.set(new SecureString(terminal.readSecret("")));
return nodeKeystorePassword.get().clone(); return nodeKeystorePassword.get().clone();
})) { })) {
@ -581,7 +581,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
nodeKeystore.setString("xpack.security.http.ssl.keystore.secure_password", httpKeystorePassword.getChars()); nodeKeystore.setString("xpack.security.http.ssl.keystore.secure_password", httpKeystorePassword.getChars());
} }
// finally overwrites the node keystore (if the keystores have been successfully written) // finally overwrites the node keystore (if the keystores have been successfully written)
nodeKeystore.save(env.configFile(), nodeKeystorePassword.get() == null ? new char[0] : nodeKeystorePassword.get().getChars()); nodeKeystore.save(env.configDir(), nodeKeystorePassword.get() == null ? new char[0] : nodeKeystorePassword.get().getChars());
} catch (Throwable t) { } catch (Throwable t) {
// restore keystore to revert possible keystore bootstrap // restore keystore to revert possible keystore bootstrap
try { try {
@ -614,10 +614,10 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
try { try {
// all certs and keys have been generated in the temp certs dir, therefore: // all certs and keys have been generated in the temp certs dir, therefore:
// 1. backup (move) any previously existing tls certs dir (this backup is NOT removed when auto-conf finishes) // 1. backup (move) any previously existing tls certs dir (this backup is NOT removed when auto-conf finishes)
if (Files.exists(env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME))) { if (Files.exists(env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME))) {
moveDirectory( moveDirectory(
env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME), env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME),
env.configFile() env.configDir()
.resolve( .resolve(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
@ -628,7 +628,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
); );
} }
// 2. move the newly populated temp certs dir to its permanent static dir name // 2. move the newly populated temp certs dir to its permanent static dir name
moveDirectory(tempGeneratedTlsCertsDir, env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME)); moveDirectory(tempGeneratedTlsCertsDir, env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME));
} catch (Throwable t) { } catch (Throwable t) {
// restore keystore to revert possible keystore bootstrap // restore keystore to revert possible keystore bootstrap
try { try {
@ -649,7 +649,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
// revert any previously existing TLS certs // revert any previously existing TLS certs
try { try {
if (Files.exists( if (Files.exists(
env.configFile() env.configDir()
.resolve( .resolve(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
@ -659,7 +659,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
) )
)) { )) {
moveDirectory( moveDirectory(
env.configFile() env.configDir()
.resolve( .resolve(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
@ -667,7 +667,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
autoConfigDate.toInstant().getEpochSecond() autoConfigDate.toInstant().getEpochSecond()
) )
), ),
env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME) env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME)
); );
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -686,7 +686,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
final Environment localFinalEnv = env; final Environment localFinalEnv = env;
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss", Locale.ROOT); final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss", Locale.ROOT);
List<String> existingConfigLines = Files.readAllLines(ymlPath, StandardCharsets.UTF_8); List<String> existingConfigLines = Files.readAllLines(ymlPath, StandardCharsets.UTF_8);
fullyWriteFile(env.configFile(), "elasticsearch.yml", true, stream -> { fullyWriteFile(env.configDir(), "elasticsearch.yml", true, stream -> {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
// start with the existing config lines // start with the existing config lines
for (String line : existingConfigLines) { for (String line : existingConfigLines) {
@ -827,16 +827,16 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
try { try {
// this removes a statically named directory, so it is potentially dangerous // this removes a statically named directory, so it is potentially dangerous
deleteDirectory(env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME)); deleteDirectory(env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME));
} catch (Exception ex) { } catch (Exception ex) {
t.addSuppressed(ex); t.addSuppressed(ex);
} }
Path backupCertsDir = env.configFile() Path backupCertsDir = env.configDir()
.resolve( .resolve(
String.format(Locale.ROOT, TLS_GENERATED_CERTS_DIR_NAME + ".%d.orig", autoConfigDate.toInstant().getEpochSecond()) String.format(Locale.ROOT, TLS_GENERATED_CERTS_DIR_NAME + ".%d.orig", autoConfigDate.toInstant().getEpochSecond())
); );
if (Files.exists(backupCertsDir)) { if (Files.exists(backupCertsDir)) {
moveDirectory(backupCertsDir, env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME)); moveDirectory(backupCertsDir, env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME));
} }
throw t; throw t;
} }
@ -887,14 +887,14 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
// with --enrolment-token token, in the first place. // with --enrolment-token token, in the first place.
final List<String> existingConfigLines; final List<String> existingConfigLines;
try { try {
existingConfigLines = Files.readAllLines(env.configFile().resolve("elasticsearch.yml"), StandardCharsets.UTF_8); existingConfigLines = Files.readAllLines(env.configDir().resolve("elasticsearch.yml"), StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
// This shouldn't happen, we would have failed earlier but we need to catch the exception // This shouldn't happen, we would have failed earlier but we need to catch the exception
throw new UserException(ExitCodes.IO_ERROR, "Aborting enrolling to cluster. Unable to read elasticsearch.yml.", e); throw new UserException(ExitCodes.IO_ERROR, "Aborting enrolling to cluster. Unable to read elasticsearch.yml.", e);
} }
final List<String> existingConfigWithoutAutoconfiguration = removePreviousAutoconfiguration(existingConfigLines); final List<String> existingConfigWithoutAutoconfiguration = removePreviousAutoconfiguration(existingConfigLines);
if (false == existingConfigLines.equals(existingConfigWithoutAutoconfiguration) if (false == existingConfigLines.equals(existingConfigWithoutAutoconfiguration)
&& Files.exists(env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME))) { && Files.exists(env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME))) {
terminal.println(""); terminal.println("");
terminal.println("This node will be reconfigured to join an existing cluster, using the enrollment token that you provided."); terminal.println("This node will be reconfigured to join an existing cluster, using the enrollment token that you provided.");
terminal.println("This operation will overwrite the existing configuration. Specifically: "); terminal.println("This operation will overwrite the existing configuration. Specifically: ");
@ -907,7 +907,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
removeAutoConfigurationFromKeystore(env, terminal); removeAutoConfigurationFromKeystore(env, terminal);
try { try {
fullyWriteFile(env.configFile(), "elasticsearch.yml", true, stream -> { fullyWriteFile(env.configDir(), "elasticsearch.yml", true, stream -> {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
for (String l : existingConfigWithoutAutoconfiguration) { for (String l : existingConfigWithoutAutoconfiguration) {
bw.write(l); bw.write(l);
@ -915,7 +915,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
} }
}); });
deleteDirectory(env.configFile().resolve(TLS_GENERATED_CERTS_DIR_NAME)); deleteDirectory(env.configDir().resolve(TLS_GENERATED_CERTS_DIR_NAME));
} catch (Throwable t) { } catch (Throwable t) {
throw new UserException( throw new UserException(
ExitCodes.IO_ERROR, ExitCodes.IO_ERROR,
@ -1262,9 +1262,9 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
private static void removeAutoConfigurationFromKeystore(Environment env, Terminal terminal) throws UserException { private static void removeAutoConfigurationFromKeystore(Environment env, Terminal terminal) throws UserException {
if (Files.exists(KeyStoreWrapper.keystorePath(env.configFile()))) { if (Files.exists(KeyStoreWrapper.keystorePath(env.configDir()))) {
try ( try (
KeyStoreWrapper existingKeystore = KeyStoreWrapper.load(env.configFile()); KeyStoreWrapper existingKeystore = KeyStoreWrapper.load(env.configDir());
SecureString keystorePassword = existingKeystore.hasPassword() SecureString keystorePassword = existingKeystore.hasPassword()
? new SecureString(terminal.readSecret("Enter password for the elasticsearch keystore: ")) ? new SecureString(terminal.readSecret("Enter password for the elasticsearch keystore: "))
: new SecureString(new char[0]); : new SecureString(new char[0]);
@ -1288,7 +1288,7 @@ public class AutoConfigureNode extends EnvironmentAwareCommand {
} }
existingKeystore.remove(setting); existingKeystore.remove(setting);
} }
existingKeystore.save(env.configFile(), keystorePassword.getChars()); existingKeystore.save(env.configDir(), keystorePassword.getChars());
} catch (Exception e) { } catch (Exception e) {
terminal.errorPrintln(Terminal.Verbosity.VERBOSE, ""); terminal.errorPrintln(Terminal.Verbosity.VERBOSE, "");
terminal.errorPrintln(Terminal.Verbosity.VERBOSE, ExceptionsHelper.stackTrace(e)); terminal.errorPrintln(Terminal.Verbosity.VERBOSE, ExceptionsHelper.stackTrace(e));

View file

@ -508,7 +508,7 @@ class HttpCertificateCommand extends EnvironmentAwareCommand {
map.put("DATE", now.format(DateTimeFormatter.ISO_LOCAL_DATE)); map.put("DATE", now.format(DateTimeFormatter.ISO_LOCAL_DATE));
map.put("TIME", now.format(DateTimeFormatter.ISO_OFFSET_TIME)); map.put("TIME", now.format(DateTimeFormatter.ISO_OFFSET_TIME));
map.put("VERSION", Version.CURRENT.toString()); map.put("VERSION", Version.CURRENT.toString());
map.put("CONF_DIR", env.configFile().toAbsolutePath().toString()); map.put("CONF_DIR", env.configDir().toAbsolutePath().toString());
map.putAll(entries); map.putAll(entries);
return map; return map;
} }
@ -1116,7 +1116,7 @@ class HttpCertificateCommand extends EnvironmentAwareCommand {
private static Path requestPath(String prompt, Terminal terminal, Environment env, boolean requireExisting) { private static Path requestPath(String prompt, Terminal terminal, Environment env, boolean requireExisting) {
for (;;) { for (;;) {
final String input = terminal.readText(prompt); final String input = terminal.readText(prompt);
final Path path = env.configFile().resolve(input).toAbsolutePath(); final Path path = env.configDir().resolve(input).toAbsolutePath();
if (path.getFileName() == null) { if (path.getFileName() == null) {
terminal.println(Terminal.Verbosity.SILENT, input + " is not a valid file"); terminal.println(Terminal.Verbosity.SILENT, input + " is not a valid file");

View file

@ -311,7 +311,7 @@ public class AutoConfigureNodeTests extends ESTestCase {
SecureString httpKeystorePassword = nodeKeystore.getString("xpack.security.http.ssl.keystore.secure_password"); SecureString httpKeystorePassword = nodeKeystore.getString("xpack.security.http.ssl.keystore.secure_password");
SecureString transportKeystorePassword = nodeKeystore.getString("xpack.security.transport.ssl.keystore.secure_password"); SecureString transportKeystorePassword = nodeKeystore.getString("xpack.security.transport.ssl.keystore.secure_password");
final Settings newSettings = Settings.builder().loadFromPath(env.configFile().resolve("elasticsearch.yml")).build(); final Settings newSettings = Settings.builder().loadFromPath(env.configDir().resolve("elasticsearch.yml")).build();
final String httpKeystorePath = newSettings.get("xpack.security.http.ssl.keystore.path"); final String httpKeystorePath = newSettings.get("xpack.security.http.ssl.keystore.path");
final String transportKeystorePath = newSettings.get("xpack.security.transport.ssl.keystore.path"); final String transportKeystorePath = newSettings.get("xpack.security.transport.ssl.keystore.path");

Some files were not shown because too many files have changed in this diff Show more