Răsfoiți Sursa

Make Environment.dataFiles singular (#72327)

The path.data setting is now a singular string, but the method
dataFiles() that gives access to the path is still an array. This commit
renames the method and makes the return type a single Path.

relates #71205
Ryan Ernst 4 ani în urmă
părinte
comite
b1eab79f4c

+ 1 - 3
qa/evil-tests/src/test/java/org/elasticsearch/bootstrap/EvilSecurityTests.java

@@ -108,9 +108,7 @@ public class EvilSecurityTests extends ESTestCase {
         assertExactPermissions(new FilePermission(environment.pluginsFile().toString(), "read,readlink"), permissions);
 
         // data paths: r/w
-        for (Path dataPath : environment.dataFiles()) {
-            assertExactPermissions(new FilePermission(dataPath.toString(), "read,readlink,write,delete"), permissions);
-        }
+        assertExactPermissions(new FilePermission(environment.dataFile().toString(), "read,readlink,write,delete"), permissions);
         assertExactPermissions(new FilePermission(environment.sharedDataFile().toString(), "read,readlink,write,delete"), permissions);
         // logs: r/w
         assertExactPermissions(new FilePermission(environment.logsFile().toString(), "read,readlink,write,delete"), permissions);

+ 2 - 1
server/src/internalClusterTest/java/org/elasticsearch/index/shard/RemoveCorruptedShardDataCommandIT.java

@@ -566,7 +566,8 @@ public class RemoveCorruptedShardDataCommandIT extends ESIntegTestCase {
         for (String nodeName : nodeNames) {
             final Path indexPath = indexPathByNodeName.get(nodeName);
             final OptionSet options = parser.parse("--dir", indexPath.toAbsolutePath().toString());
-            command.findAndProcessShardPath(options, environmentByNodeName.get(nodeName), environmentByNodeName.get(nodeName).dataFiles(),
+            command.findAndProcessShardPath(options, environmentByNodeName.get(nodeName),
+                new Path[] { environmentByNodeName.get(nodeName).dataFile() },
                 state, shardPath -> assertThat(shardPath.resolveIndex(), equalTo(indexPath)));
         }
     }

+ 12 - 19
server/src/main/java/org/elasticsearch/bootstrap/Security.java

@@ -158,9 +158,7 @@ final class Security {
 
     private static Permissions createRecursiveDataPathPermission(Environment environment) throws IOException {
         Permissions policy = new Permissions();
-        for (Path path : environment.dataFiles()) {
-            addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete", true);
-        }
+        addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), environment.dataFile(), "read,readlink,write,delete", true);
         return policy;
     }
 
@@ -202,22 +200,17 @@ final class Security {
             addDirectoryPath(policy, Environment.PATH_SHARED_DATA_SETTING.getKey(), environment.sharedDataFile(),
                 "read,readlink,write,delete", false);
         }
-        final Set<Path> dataFilesPaths = new HashSet<>();
-        for (Path path : environment.dataFiles()) {
-            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
-             * invocation will fail if the directory does not already exist. We use Path#toRealPath to follow symlinks and handle issues
-             * like unicode normalization or case-insensitivity on some filesystems (e.g., the case-insensitive variant of HFS+ on macOS).
-             */
-            try {
-                final Path realPath = path.toRealPath();
-                if (dataFilesPaths.add(realPath) == false) {
-                    throw new IllegalStateException("path [" + realPath + "] is duplicated by [" + path + "]");
-                }
-            } catch (final IOException e) {
-                throw new IllegalStateException("unable to access [" + path + "]", e);
-            }
+        final Path dataPath = environment.dataFile();
+        addDirectoryPath(policy, Environment.PATH_DATA_SETTING.getKey(), dataPath, "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
+         * invocation will fail if the directory does not already exist. We use Path#toRealPath to follow symlinks and handle issues
+         * like unicode normalization or case-insensitivity on some filesystems (e.g., the case-insensitive variant of HFS+ on macOS).
+         */
+        try {
+            dataPath.toRealPath();
+        } catch (final IOException e) {
+            throw new IllegalStateException("unable to access [" + dataPath + "]", e);
         }
         for (Path path : environment.repoFiles()) {
             addDirectoryPath(policy, Environment.PATH_REPO_SETTING.getKey(), path, "read,readlink,write,delete", false);

+ 3 - 3
server/src/main/java/org/elasticsearch/env/Environment.java

@@ -169,8 +169,8 @@ public class Environment {
     /**
      * The data location.
      */
-    public Path[] dataFiles() {
-        return new Path[] { dataFile };
+    public Path dataFile() {
+        return dataFile;
     }
 
     /**
@@ -320,7 +320,7 @@ public class Environment {
      * object which may contain different setting)
      */
     public static void assertEquivalent(Environment actual, Environment expected) {
-        assertEquals(actual.dataFiles(), expected.dataFiles(), "dataFiles");
+        assertEquals(actual.dataFile(), expected.dataFile(), "dataFiles");
         assertEquals(actual.repoFiles(), expected.repoFiles(), "repoFiles");
         assertEquals(actual.configFile(), expected.configFile(), "configFile");
         assertEquals(actual.pluginsFile(), expected.pluginsFile(), "pluginsFile");

+ 45 - 53
server/src/main/java/org/elasticsearch/env/NodeEnvironment.java

@@ -195,27 +195,24 @@ public final class NodeEnvironment  implements Closeable {
                         final Environment environment,
                         final CheckedFunction<Path, Boolean, IOException> pathFunction,
                         final Function<Path, Path> subPathMapping) throws IOException {
-            nodePaths = new NodePath[environment.dataFiles().length];
-            locks = new Lock[nodePaths.length];
+            nodePaths = new NodePath[1];
+            locks = new Lock[1];
             try {
-                final Path[] dataPaths = environment.dataFiles();
-                for (int dirIndex = 0; dirIndex < dataPaths.length; dirIndex++) {
-                    Path dataDir = dataPaths[dirIndex];
-                    Path dir = subPathMapping.apply(dataDir);
-                    if (pathFunction.apply(dir) == false) {
-                        continue;
-                    }
-                    try (Directory luceneDir = FSDirectory.open(dir, NativeFSLockFactory.INSTANCE)) {
-                        logger.trace("obtaining node lock on {} ...", dir.toAbsolutePath());
-                        locks[dirIndex] = luceneDir.obtainLock(NODE_LOCK_FILENAME);
-                        nodePaths[dirIndex] = new NodePath(dir);
-                    } catch (IOException e) {
-                        logger.trace(() -> new ParameterizedMessage(
-                            "failed to obtain node lock on {}", dir.toAbsolutePath()), e);
-                        // release all the ones that were obtained up until now
-                        throw (e instanceof LockObtainFailedException ? e
-                            : new IOException("failed to obtain lock on " + dir.toAbsolutePath(), e));
-                    }
+                Path dataDir = environment.dataFile();
+                Path dir = subPathMapping.apply(dataDir);
+                if (pathFunction.apply(dir) == false) {
+                    return;
+                }
+                try (Directory luceneDir = FSDirectory.open(dir, NativeFSLockFactory.INSTANCE)) {
+                    logger.trace("obtaining node lock on {} ...", dir.toAbsolutePath());
+                    locks[0] = luceneDir.obtainLock(NODE_LOCK_FILENAME);
+                    nodePaths[0] = new NodePath(dir);
+                } catch (IOException e) {
+                    logger.trace(() -> new ParameterizedMessage(
+                        "failed to obtain node lock on {}", dir.toAbsolutePath()), e);
+                    // release all the ones that were obtained up until now
+                    throw (e instanceof LockObtainFailedException ? e
+                        : new IOException("failed to obtain lock on " + dir.toAbsolutePath(), e));
                 }
             } catch (IOException e) {
                 close();
@@ -247,10 +244,7 @@ public final class NodeEnvironment  implements Closeable {
 
         try {
             sharedDataPath = environment.sharedDataFile();
-
-            for (Path path : environment.dataFiles()) {
-                Files.createDirectories(path);
-            }
+            Files.createDirectories(environment.dataFile());
 
             final NodeLock nodeLock;
             try {
@@ -259,8 +253,8 @@ public final class NodeEnvironment  implements Closeable {
                 final String message = String.format(
                     Locale.ROOT,
                     "failed to obtain node locks, tried %s;" +
-                        " maybe these locations are not writable or multiple nodes were started on the same data path?",
-                    Arrays.toString(environment.dataFiles()));
+                        " maybe this location is not writable or multiple nodes were started on the same data path?",
+                    environment.dataFile());
                 throw new IllegalStateException(message, e);
             }
 
@@ -308,33 +302,31 @@ public final class NodeEnvironment  implements Closeable {
         boolean upgradeNeeded = false;
 
         // check if we can do an auto-upgrade
-        for (Path path : environment.dataFiles()) {
-            final Path nodesFolderPath = path.resolve("nodes");
-            if (Files.isDirectory(nodesFolderPath)) {
-                final List<Integer> nodeLockIds = new ArrayList<>();
-
-                try (DirectoryStream<Path> stream = Files.newDirectoryStream(nodesFolderPath)) {
-                    for (Path nodeLockIdPath : stream) {
-                        String fileName = nodeLockIdPath.getFileName().toString();
-                        if (Files.isDirectory(nodeLockIdPath) && fileName.chars().allMatch(Character::isDigit)) {
-                            int nodeLockId = Integer.parseInt(fileName);
-                            nodeLockIds.add(nodeLockId);
-                        } else if (FileSystemUtils.isDesktopServicesStore(nodeLockIdPath) == false) {
-                            throw new IllegalStateException("unexpected file/folder encountered during data folder upgrade: " +
-                                nodeLockIdPath);
-                        }
+        final Path nodesFolderPath = environment.dataFile().resolve("nodes");
+        if (Files.isDirectory(nodesFolderPath)) {
+            final List<Integer> nodeLockIds = new ArrayList<>();
+
+            try (DirectoryStream<Path> stream = Files.newDirectoryStream(nodesFolderPath)) {
+                for (Path nodeLockIdPath : stream) {
+                    String fileName = nodeLockIdPath.getFileName().toString();
+                    if (Files.isDirectory(nodeLockIdPath) && fileName.chars().allMatch(Character::isDigit)) {
+                        int nodeLockId = Integer.parseInt(fileName);
+                        nodeLockIds.add(nodeLockId);
+                    } else if (FileSystemUtils.isDesktopServicesStore(nodeLockIdPath) == false) {
+                        throw new IllegalStateException("unexpected file/folder encountered during data folder upgrade: " +
+                            nodeLockIdPath);
                     }
                 }
+            }
 
-                if (nodeLockIds.isEmpty() == false) {
-                    upgradeNeeded = true;
+            if (nodeLockIds.isEmpty() == false) {
+                upgradeNeeded = true;
 
-                    if (nodeLockIds.equals(Arrays.asList(0)) == false) {
-                        throw new IllegalStateException("data path " + nodesFolderPath + " cannot be upgraded automatically because it " +
-                            "contains data from nodes with ordinals " + nodeLockIds + ", due to previous use of the now obsolete " +
-                            "[node.max_local_storage_nodes] setting. Please check the breaking changes docs for the current version of " +
-                            "Elasticsearch to find an upgrade path");
-                    }
+                if (nodeLockIds.equals(Arrays.asList(0)) == false) {
+                    throw new IllegalStateException("data path " + nodesFolderPath + " cannot be upgraded automatically because it " +
+                        "contains data from nodes with ordinals " + nodeLockIds + ", due to previous use of the now obsolete " +
+                        "[node.max_local_storage_nodes] setting. Please check the breaking changes docs for the current version of " +
+                        "Elasticsearch to find an upgrade path");
                 }
             }
         }
@@ -344,7 +336,7 @@ public final class NodeEnvironment  implements Closeable {
             return false;
         }
 
-        logger.info("upgrading legacy data folders: {}", Arrays.toString(environment.dataFiles()));
+        logger.info("upgrading legacy data folder: {}", environment.dataFile());
 
         // acquire locks on legacy path for duration of upgrade (to ensure there is no older ES version running on this path)
         final NodeLock legacyNodeLock;
@@ -354,8 +346,8 @@ public final class NodeEnvironment  implements Closeable {
             final String message = String.format(
                 Locale.ROOT,
                 "failed to obtain legacy node locks, tried %s;" +
-                    " maybe these locations are not writable or multiple nodes were started on the same data path?",
-                Arrays.toString(environment.dataFiles()));
+                    " maybe this location is not writable or multiple nodes were started on the same data path?",
+                environment.dataFile());
             throw new IllegalStateException(message, e);
         }
 
@@ -429,7 +421,7 @@ public final class NodeEnvironment  implements Closeable {
         }
 
         // upgrade successfully completed, remove legacy nodes folders
-        IOUtils.rm(Stream.of(environment.dataFiles()).map(path -> path.resolve("nodes")).toArray(Path[]::new));
+        IOUtils.rm(environment.dataFile().resolve("nodes"));
 
         return true;
     }

+ 1 - 1
server/src/main/java/org/elasticsearch/node/Node.java

@@ -312,7 +312,7 @@ public class Node implements Closeable {
 
             if (logger.isDebugEnabled()) {
                 logger.debug("using config [{}], data [{}], logs [{}], plugins [{}]",
-                    initialEnvironment.configFile(), Arrays.toString(initialEnvironment.dataFiles()),
+                    initialEnvironment.configFile(), initialEnvironment.dataFile(),
                     initialEnvironment.logsFile(), initialEnvironment.pluginsFile());
             }
 

+ 1 - 1
server/src/test/java/org/elasticsearch/env/EnvironmentTests.java

@@ -62,7 +62,7 @@ public class EnvironmentTests extends ESTestCase {
         final Path pathHome = createTempDir().toAbsolutePath();
         final Settings settings = Settings.builder().put("path.home", pathHome).build();
         final Environment environment = new Environment(settings, null);
-        assertThat(environment.dataFiles(), equalTo(new Path[]{pathHome.resolve("data")}));
+        assertThat(environment.dataFile(), equalTo(pathHome.resolve("data")));
     }
 
     public void testPathDataNotSetInEnvironmentIfNotSet() {

+ 3 - 5
server/src/test/java/org/elasticsearch/env/NodeRepurposeCommandTests.java

@@ -32,7 +32,6 @@ import org.junit.Before;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.util.Arrays;
 import java.util.Set;
 import java.util.stream.Stream;
 
@@ -121,7 +120,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
 
         String messageText = NodeRepurposeCommand.noMasterMessage(
             1,
-            environment.dataFiles().length*shardCount,
+            shardCount,
             0);
 
         Matcher<String> outputMatcher = allOf(
@@ -148,7 +147,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
         createIndexDataFiles(dataMasterSettings, shardCount, hasClusterState);
 
         Matcher<String> matcher = allOf(
-            containsString(NodeRepurposeCommand.shardMessage(environment.dataFiles().length * shardCount, 1)),
+            containsString(NodeRepurposeCommand.shardMessage(shardCount, 1)),
             conditionalNot(containsString("testUUID"), verbose == false),
             conditionalNot(containsString("testIndex"), verbose == false || hasClusterState == false),
             conditionalNot(containsString("no name for uuid: testUUID"), verbose == false || hasClusterState)
@@ -245,8 +244,7 @@ public class NodeRepurposeCommandTests extends ESTestCase {
     }
 
     private long digestPaths() {
-        // use a commutative digest to avoid dependency on file system order.
-        return Arrays.stream(environment.dataFiles()).mapToLong(this::digestPath).sum();
+        return digestPath(environment.dataFile());
     }
 
     private long digestPath(Path path) {

+ 1 - 1
test/framework/src/main/java/org/elasticsearch/cluster/DiskUsageIntegTestCase.java

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

+ 19 - 24
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeStorageProvider.java

@@ -52,9 +52,7 @@ public class NativeStorageProvider {
      */
     public void cleanupLocalTmpStorageInCaseOfUncleanShutdown() {
         try {
-            for (Path p : environment.dataFiles()) {
-                IOUtils.rm(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER));
-            }
+            IOUtils.rm(environment.dataFile().resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER));
         } catch (Exception e) {
             LOGGER.warn("Failed to cleanup native storage from previous invocation", e);
         }
@@ -79,17 +77,16 @@ public class NativeStorageProvider {
     }
 
     private Path tryAllocateStorage(String uniqueIdentifier, ByteSizeValue requestedSize) {
-        for (Path path : environment.dataFiles()) {
-            try {
-                if (getUsableSpace(path) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes()) {
-                    Path tmpDirectory = path.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER).resolve(uniqueIdentifier);
-                    Files.createDirectories(tmpDirectory);
-                    allocatedStorage.put(uniqueIdentifier, tmpDirectory);
-                    return tmpDirectory;
-                }
-            } catch (IOException e) {
-                LOGGER.warn("Failed to obtain information about path [{}]: {}", path, e);
+        final Path path = environment.dataFile();
+        try {
+            if (getUsableSpace(path) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes()) {
+                Path tmpDirectory = path.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER).resolve(uniqueIdentifier);
+                Files.createDirectories(tmpDirectory);
+                allocatedStorage.put(uniqueIdentifier, tmpDirectory);
+                return tmpDirectory;
             }
+        } catch (IOException e) {
+            LOGGER.warn("Failed to obtain information about path [{}]: {}", path, e);
         }
         LOGGER.warn("Failed to find native storage for [{}], returning null", uniqueIdentifier);
         return null;
@@ -97,14 +94,13 @@ public class NativeStorageProvider {
 
     public boolean localTmpStorageHasEnoughSpace(Path path, ByteSizeValue requestedSize) {
         Path realPath = path.toAbsolutePath();
-        for (Path p : environment.dataFiles()) {
-            try {
-                if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
-                    return getUsableSpace(p) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes();
-                }
-            } catch (IOException e) {
-                LOGGER.warn("Failed to obtain information about path [{}]: {}", path, e);
+        Path dataPath = environment.dataFile();
+        try {
+            if (realPath.startsWith(dataPath.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
+                return getUsableSpace(dataPath) >= requestedSize.getBytes() + minLocalStorageAvailable.getBytes();
             }
+        } catch (IOException e) {
+            LOGGER.warn("Failed to obtain information about path [{}]: {}", path, e);
         }
 
         LOGGER.debug("Not enough space left for path [{}]", path);
@@ -122,10 +118,9 @@ public class NativeStorageProvider {
         if (path != null) {
             // do not allow to breakout from the tmp storage provided
             Path realPath = path.toAbsolutePath();
-            for (Path p : environment.dataFiles()) {
-                if (realPath.startsWith(p.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
-                    IOUtils.rm(path);
-                }
+            Path dataPath = environment.dataFile();
+            if (realPath.startsWith(dataPath.resolve(LOCAL_STORAGE_SUBFOLDER).resolve(LOCAL_STORAGE_TMP_FOLDER))) {
+                IOUtils.rm(path);
             }
         }
     }

+ 14 - 41
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/NativeStorageProviderTests.java

@@ -18,8 +18,6 @@ import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.util.HashMap;
-import java.util.Map;
 
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.doAnswer;
@@ -30,11 +28,9 @@ import static org.mockito.Mockito.when;
 public class NativeStorageProviderTests extends ESTestCase {
 
     public void testTmpStorage() throws IOException {
-        Map<Path, Long> storage = new HashMap<>();
         Path tmpDir = createTempDir();
-
-        storage.put(tmpDir, ByteSizeValue.ofGb(6).getBytes());
-        NativeStorageProvider storageProvider = createNativeStorageProvider(storage);
+        long tmpSize = ByteSizeValue.ofGb(6).getBytes();
+        NativeStorageProvider storageProvider = createNativeStorageProvider(tmpDir, tmpSize);
 
         Assert.assertNotNull(
                 storageProvider.tryGetLocalTmpStorage(randomAlphaOfLengthBetween(4, 10), ByteSizeValue.ofBytes(100)));
@@ -48,33 +44,10 @@ public class NativeStorageProviderTests extends ESTestCase {
         Assert.assertEquals(tmpDir.resolve("ml-local-data").resolve("tmp").resolve(id).toString(), path.toString());
     }
 
-    public void testTmpStorageChooseDisk() throws IOException {
-        Map<Path, Long> storage = new HashMap<>();
-        Path tmpDir = createTempDir();
-
-        // low disk space
-        Path disk1 = tmpDir.resolve(randomAlphaOfLengthBetween(4, 10));
-        storage.put(disk1, ByteSizeValue.ofGb(1).getBytes());
-
-        // sufficient disk space
-        Path disk2 = tmpDir.resolve(randomAlphaOfLengthBetween(4, 10));
-        storage.put(disk2, ByteSizeValue.ofGb(20).getBytes());
-
-        NativeStorageProvider storageProvider = createNativeStorageProvider(storage);
-
-        String id = randomAlphaOfLengthBetween(4, 10);
-        Path path = storageProvider.tryGetLocalTmpStorage(id, ByteSizeValue.ofGb(1));
-        Assert.assertNotNull(path);
-
-        // should resolve to disk2 as disk1 is low on space
-        Assert.assertEquals(disk2.resolve("ml-local-data").resolve("tmp").resolve(id).toString(), path.toString());
-    }
-
     public void testTmpStorageCleanup() throws IOException {
-        Map<Path, Long> storage = new HashMap<>();
         Path tmpDir = createTempDir();
-        storage.put(tmpDir, ByteSizeValue.ofGb(6).getBytes());
-        NativeStorageProvider storageProvider = createNativeStorageProvider(storage);
+        long tmpSize = ByteSizeValue.ofGb(6).getBytes();
+        NativeStorageProvider storageProvider = createNativeStorageProvider(tmpDir, tmpSize);
         String id = randomAlphaOfLengthBetween(4, 10);
 
         Path path = storageProvider.tryGetLocalTmpStorage(id, ByteSizeValue.ofKb(1));
@@ -95,10 +68,9 @@ public class NativeStorageProviderTests extends ESTestCase {
     }
 
     public void testTmpStorageCleanupOnStart() throws IOException {
-        Map<Path, Long> storage = new HashMap<>();
         Path tmpDir = createTempDir();
-        storage.put(tmpDir, ByteSizeValue.ofGb(6).getBytes());
-        NativeStorageProvider storageProvider = createNativeStorageProvider(storage);
+        long tmpSize = ByteSizeValue.ofGb(6).getBytes();
+        NativeStorageProvider storageProvider = createNativeStorageProvider(tmpDir, tmpSize);
         String id = randomAlphaOfLengthBetween(4, 10);
 
         Path path = storageProvider.tryGetLocalTmpStorage(id, ByteSizeValue.ofKb(1));
@@ -114,23 +86,24 @@ public class NativeStorageProviderTests extends ESTestCase {
         Assert.assertTrue(Files.isRegularFile(testFile));
 
         // create a new storage provider to test the case of a crashed node
-        storageProvider = createNativeStorageProvider(storage);
+        storageProvider = createNativeStorageProvider(tmpDir, tmpSize);
         storageProvider.cleanupLocalTmpStorageInCaseOfUncleanShutdown();
         Assert.assertFalse(Files.exists(testFile));
         Assert.assertFalse(Files.exists(path));
     }
 
-    private NativeStorageProvider createNativeStorageProvider(Map<Path, Long> paths) throws IOException {
+    private NativeStorageProvider createNativeStorageProvider(Path path, long size) throws IOException {
         Environment environment = mock(Environment.class);
 
-        when(environment.dataFiles()).thenReturn(paths.keySet().toArray(new Path[paths.size()]));
+        when(environment.dataFile()).thenReturn(path);
         NativeStorageProvider storageProvider = spy(new NativeStorageProvider(environment, ByteSizeValue.ofGb(5)));
 
         doAnswer(invocation -> {
-            return paths.getOrDefault(invocation.getArguments()[0], Long.valueOf(0)).longValue();
-        }
-
-        ).when(storageProvider).getUsableSpace(any(Path.class));
+            if (path.equals(invocation.getArguments()[0])) {
+                return size;
+            }
+            return 0L;
+        }).when(storageProvider).getUsableSpace(any(Path.class));
 
         return storageProvider;
     }

+ 1 - 3
x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/store/input/FrozenIndexInputTests.java

@@ -88,9 +88,7 @@ public class FrozenIndexInputTests extends AbstractSearchableSnapshotsTestCase {
             .put("path.home", createTempDir())
             .build();
         final Environment environment = TestEnvironment.newEnvironment(settings);
-        for (Path path : environment.dataFiles()) {
-            Files.createDirectories(path);
-        }
+        Files.createDirectories(environment.dataFile());
         SnapshotId snapshotId = new SnapshotId("_name", "_uuid");
         final Path shardDir = randomShardPath(SHARD_ID);
         final ShardPath shardPath = new ShardPath(false, shardDir, shardDir, SHARD_ID);