Skip to content

Commit b2d62ae

Browse files
committed
Detect remnants of path.data/default.path.data bug
In Elasticsearch 5.3.0 a bug was introduced in the merging of default settings when the target setting existed as an array. When this bug concerns path.data and default.path.data, we ended up in a situation where the paths specified in both settings would be used to write index data. Since our packaging sets default.path.data, users that configure multiple data paths via an array and use the packaging are subject to having shards land in paths in default.path.data when that is very likely not what they intended. This commit is an attempt to rectify this situation. If path.data and default.path.data are configured, we check for the presence of indices there. If we find any, we log messages explaining the situation and fail the node. Relates #24099
1 parent fb79a04 commit b2d62ae

File tree

4 files changed

+213
-15
lines changed

4 files changed

+213
-15
lines changed

core/src/main/java/org/elasticsearch/bootstrap/Security.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
import org.elasticsearch.SecureSM;
2323
import org.elasticsearch.Version;
24-
import org.elasticsearch.common.Strings;
2524
import org.elasticsearch.common.SuppressForbidden;
2625
import org.elasticsearch.common.io.PathUtils;
2726
import org.elasticsearch.common.network.NetworkModule;
@@ -257,6 +256,26 @@ static void addFilePermissions(Permissions policy, Environment environment) {
257256
for (Path path : environment.dataWithClusterFiles()) {
258257
addPathIfExists(policy, Environment.PATH_DATA_SETTING.getKey(), path, "read,readlink,write,delete");
259258
}
259+
/*
260+
* If path.data and default.path.data are set, we need read access to the paths in default.path.data to check for the existence of
261+
* index directories there that could have arisen from a bug in the handling of simultaneous configuration of path.data and
262+
* default.path.data that was introduced in Elasticsearch 5.3.0.
263+
*
264+
* If path.data is not set then default.path.data would take precedence in setting the data paths for the environment and
265+
* permissions would have been granted above.
266+
*
267+
* If path.data is not set and default.path.data is not set, then we would fallback to the default data directory under
268+
* Elasticsearch home and again permissions would have been granted above.
269+
*
270+
* If path.data is set and default.path.data is not set, there is nothing to do here.
271+
*/
272+
if (Environment.PATH_DATA_SETTING.exists(environment.settings())
273+
&& Environment.DEFAULT_PATH_DATA_SETTING.exists(environment.settings())) {
274+
for (final String path : Environment.DEFAULT_PATH_DATA_SETTING.get(environment.settings())) {
275+
// write permissions are not needed here, we are not going to be writing to any paths here
276+
addPath(policy, Environment.DEFAULT_PATH_DATA_SETTING.getKey(), getPath(path), "read,readlink");
277+
}
278+
}
260279
for (Path path : environment.repoFiles()) {
261280
addPath(policy, Environment.PATH_REPO_SETTING.getKey(), path, "read,readlink,write,delete");
262281
}
@@ -266,6 +285,11 @@ static void addFilePermissions(Permissions policy, Environment environment) {
266285
}
267286
}
268287

288+
@SuppressForbidden(reason = "read path that is not configured in environment")
289+
private static Path getPath(final String path) {
290+
return PathUtils.get(path);
291+
}
292+
269293
/**
270294
* Add dynamic {@link SocketPermission}s based on HTTP and transport settings.
271295
*

core/src/main/java/org/elasticsearch/env/NodeEnvironment.java

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ public NodeEnvironment(Settings settings, Environment environment) throws IOExce
217217
"Elasticsearch 6.0 will not allow the cluster name as a folder within the data path", dataDir);
218218
dataDir = dataDirWithClusterName;
219219
}
220-
Path dir = dataDir.resolve(NODES_FOLDER).resolve(Integer.toString(possibleLockId));
220+
Path dir = resolveNodePath(dataDir, possibleLockId);
221221
Files.createDirectories(dir);
222222

223223
try (Directory luceneDir = FSDirectory.open(dir, NativeFSLockFactory.INSTANCE)) {
@@ -283,6 +283,17 @@ public NodeEnvironment(Settings settings, Environment environment) throws IOExce
283283
}
284284
}
285285

286+
/**
287+
* Resolve a specific nodes/{node.id} path for the specified path and node lock id.
288+
*
289+
* @param path the path
290+
* @param nodeLockId the node lock id
291+
* @return the resolved path
292+
*/
293+
public static Path resolveNodePath(final Path path, final int nodeLockId) {
294+
return path.resolve(NODES_FOLDER).resolve(Integer.toString(nodeLockId));
295+
}
296+
286297
/** Returns true if the directory is empty */
287298
private static boolean dirEmpty(final Path path) throws IOException {
288299
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
@@ -758,6 +769,14 @@ public NodePath[] nodePaths() {
758769
return nodePaths;
759770
}
760771

772+
public int getNodeLockId() {
773+
assertEnvIsLocked();
774+
if (nodePaths == null || locks == null) {
775+
throw new IllegalStateException("node is not configured to store local location");
776+
}
777+
return nodeLockId;
778+
}
779+
761780
/**
762781
* Returns all index paths.
763782
*/
@@ -770,6 +789,8 @@ public Path[] indexPaths(Index index) {
770789
return indexPaths;
771790
}
772791

792+
793+
773794
/**
774795
* Returns all shard paths excluding custom shard path. Note: Shards are only allocated on one of the
775796
* returned paths. The returned array may contain paths to non-existing directories.
@@ -798,19 +819,36 @@ public Set<String> availableIndexFolders() throws IOException {
798819
assertEnvIsLocked();
799820
Set<String> indexFolders = new HashSet<>();
800821
for (NodePath nodePath : nodePaths) {
801-
Path indicesLocation = nodePath.indicesPath;
802-
if (Files.isDirectory(indicesLocation)) {
803-
try (DirectoryStream<Path> stream = Files.newDirectoryStream(indicesLocation)) {
804-
for (Path index : stream) {
805-
if (Files.isDirectory(index)) {
806-
indexFolders.add(index.getFileName().toString());
807-
}
822+
indexFolders.addAll(availableIndexFoldersForPath(nodePath));
823+
}
824+
return indexFolders;
825+
826+
}
827+
828+
/**
829+
* Return all directory names in the nodes/{node.id}/indices directory for the given node path.
830+
*
831+
* @param nodePath the path
832+
* @return all directories that could be indices for the given node path.
833+
* @throws IOException if an I/O exception occurs traversing the filesystem
834+
*/
835+
public Set<String> availableIndexFoldersForPath(final NodePath nodePath) throws IOException {
836+
if (nodePaths == null || locks == null) {
837+
throw new IllegalStateException("node is not configured to store local location");
838+
}
839+
assertEnvIsLocked();
840+
final Set<String> indexFolders = new HashSet<>();
841+
Path indicesLocation = nodePath.indicesPath;
842+
if (Files.isDirectory(indicesLocation)) {
843+
try (DirectoryStream<Path> stream = Files.newDirectoryStream(indicesLocation)) {
844+
for (Path index : stream) {
845+
if (Files.isDirectory(index)) {
846+
indexFolders.add(index.getFileName().toString());
808847
}
809848
}
810849
}
811850
}
812851
return indexFolders;
813-
814852
}
815853

816854
/**

core/src/main/java/org/elasticsearch/node/Node.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
import org.elasticsearch.cluster.routing.allocation.AllocationService;
5151
import org.elasticsearch.cluster.service.ClusterService;
5252
import org.elasticsearch.common.StopWatch;
53+
import org.elasticsearch.common.SuppressForbidden;
5354
import org.elasticsearch.common.component.Lifecycle;
5455
import org.elasticsearch.common.component.LifecycleComponent;
5556
import org.elasticsearch.common.inject.Binder;
@@ -58,6 +59,7 @@
5859
import org.elasticsearch.common.inject.Module;
5960
import org.elasticsearch.common.inject.ModulesBuilder;
6061
import org.elasticsearch.common.inject.util.Providers;
62+
import org.elasticsearch.common.io.PathUtils;
6163
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
6264
import org.elasticsearch.common.lease.Releasables;
6365
import org.elasticsearch.common.logging.DeprecationLogger;
@@ -148,7 +150,9 @@
148150
import java.util.Collection;
149151
import java.util.Collections;
150152
import java.util.List;
153+
import java.util.Locale;
151154
import java.util.Map;
155+
import java.util.Set;
152156
import java.util.concurrent.CountDownLatch;
153157
import java.util.concurrent.TimeUnit;
154158
import java.util.function.Consumer;
@@ -264,6 +268,9 @@ protected Node(final Environment environment, Collection<Class<? extends Plugin>
264268
Logger logger = Loggers.getLogger(Node.class, tmpSettings);
265269
final String nodeId = nodeEnvironment.nodeId();
266270
tmpSettings = addNodeNameIfNeeded(tmpSettings, nodeId);
271+
if (DiscoveryNode.nodeRequiresLocalStorage(tmpSettings)) {
272+
checkForIndexDataInDefaultPathData(tmpSettings, nodeEnvironment, logger);
273+
}
267274
// this must be captured after the node name is possibly added to the settings
268275
final String nodeName = NODE_NAME_SETTING.get(tmpSettings);
269276
if (hadPredefinedNodeName == false) {
@@ -507,6 +514,58 @@ protected Node(final Environment environment, Collection<Class<? extends Plugin>
507514
}
508515
}
509516

517+
/**
518+
* Checks for path.data and default.path.data being configured, and there being index data in any of the paths in default.path.data.
519+
*
520+
* @param settings the settings to check for path.data and default.path.data
521+
* @param nodeEnv the current node environment
522+
* @param logger a logger where messages regarding the detection will be logged
523+
* @throws IOException if an I/O exception occurs reading the directory structure
524+
*/
525+
static void checkForIndexDataInDefaultPathData(
526+
final Settings settings, final NodeEnvironment nodeEnv, final Logger logger) throws IOException {
527+
if (!Environment.PATH_DATA_SETTING.exists(settings) || !Environment.DEFAULT_PATH_DATA_SETTING.exists(settings)) {
528+
return;
529+
}
530+
531+
boolean clean = true;
532+
for (final String defaultPathData : Environment.DEFAULT_PATH_DATA_SETTING.get(settings)) {
533+
final Path nodeDirectory = NodeEnvironment.resolveNodePath(getPath(defaultPathData), nodeEnv.getNodeLockId());
534+
if (Files.exists(nodeDirectory) == false) {
535+
continue;
536+
}
537+
final NodeEnvironment.NodePath nodePath = new NodeEnvironment.NodePath(nodeDirectory);
538+
final Set<String> availableIndexFolders = nodeEnv.availableIndexFoldersForPath(nodePath);
539+
if (availableIndexFolders.isEmpty()) {
540+
continue;
541+
}
542+
clean = false;
543+
logger.error("detected index data in default.path.data [{}] where there should not be any", nodePath.indicesPath);
544+
for (final String availableIndexFolder : availableIndexFolders) {
545+
logger.info(
546+
"index folder [{}] in default.path.data [{}] must be moved to any of {}",
547+
availableIndexFolder,
548+
nodePath.indicesPath,
549+
Arrays.stream(nodeEnv.nodePaths()).map(np -> np.indicesPath).collect(Collectors.toList()));
550+
}
551+
}
552+
553+
if (clean) {
554+
return;
555+
}
556+
557+
final String message = String.format(
558+
Locale.ROOT,
559+
"detected index data in default.path.data %s where there should not be any; check the logs for details",
560+
Environment.DEFAULT_PATH_DATA_SETTING.get(settings));
561+
throw new IllegalStateException(message);
562+
}
563+
564+
@SuppressForbidden(reason = "read path that is not configured in environment")
565+
private static Path getPath(final String path) {
566+
return PathUtils.get(path);
567+
}
568+
510569
// visible for testing
511570
static void warnIfPreRelease(final Version version, final boolean isSnapshot, final Logger logger) {
512571
if (!version.isRelease() || isSnapshot) {

test/framework/src/main/java/org/elasticsearch/node/NodeTests.java

Lines changed: 82 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,41 @@
1919
package org.elasticsearch.node;
2020

2121
import org.apache.logging.log4j.Logger;
22+
import org.apache.lucene.util.LuceneTestCase;
2223
import org.elasticsearch.Version;
2324
import org.elasticsearch.bootstrap.BootstrapCheck;
2425
import org.elasticsearch.cluster.ClusterName;
26+
import org.elasticsearch.common.UUIDs;
2527
import org.elasticsearch.common.network.NetworkModule;
2628
import org.elasticsearch.common.settings.Settings;
2729
import org.elasticsearch.common.transport.BoundTransportAddress;
2830
import org.elasticsearch.env.Environment;
31+
import org.elasticsearch.env.NodeEnvironment;
2932
import org.elasticsearch.plugins.Plugin;
3033
import org.elasticsearch.test.ESTestCase;
3134
import org.elasticsearch.test.InternalTestCluster;
3235
import org.elasticsearch.transport.MockTcpTransportPlugin;
3336

3437
import java.io.IOException;
38+
import java.nio.file.Files;
3539
import java.nio.file.Path;
3640
import java.util.Arrays;
3741
import java.util.Collections;
3842
import java.util.List;
43+
import java.util.Locale;
3944
import java.util.concurrent.atomic.AtomicBoolean;
45+
import java.util.stream.Collectors;
46+
import java.util.stream.IntStream;
4047

48+
import static org.hamcrest.Matchers.containsString;
4149
import static org.hamcrest.Matchers.equalTo;
50+
import static org.hamcrest.Matchers.hasToString;
4251
import static org.mockito.Mockito.mock;
4352
import static org.mockito.Mockito.reset;
4453
import static org.mockito.Mockito.verify;
4554
import static org.mockito.Mockito.verifyNoMoreInteractions;
4655

56+
@LuceneTestCase.SuppressFileSystems(value = "ExtrasFS")
4757
public class NodeTests extends ESTestCase {
4858

4959
public void testNodeName() throws IOException {
@@ -165,14 +175,81 @@ public void testNodeAttributes() throws IOException {
165175
}
166176
}
167177

178+
public void testDefaultPathDataSet() throws IOException {
179+
final Path zero = createTempDir().toAbsolutePath();
180+
final Path one = createTempDir().toAbsolutePath();
181+
final Path defaultPathData = createTempDir().toAbsolutePath();
182+
final Settings settings = Settings.builder()
183+
.put("path.home", "/home")
184+
.put("path.data.0", zero)
185+
.put("path.data.1", one)
186+
.put("default.path.data", defaultPathData)
187+
.build();
188+
try (NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings))) {
189+
final Path defaultPathDataWithNodesAndId = defaultPathData.resolve("nodes/0");
190+
Files.createDirectories(defaultPathDataWithNodesAndId);
191+
final NodeEnvironment.NodePath defaultNodePath = new NodeEnvironment.NodePath(defaultPathDataWithNodesAndId);
192+
final boolean indexExists = randomBoolean();
193+
final List<String> indices;
194+
if (indexExists) {
195+
indices = IntStream.range(0, randomIntBetween(1, 3)).mapToObj(i -> UUIDs.randomBase64UUID()).collect(Collectors.toList());
196+
for (final String index : indices) {
197+
Files.createDirectories(defaultNodePath.indicesPath.resolve(index));
198+
}
199+
} else {
200+
indices = Collections.emptyList();
201+
}
202+
final Logger mock = mock(Logger.class);
203+
if (indexExists) {
204+
final IllegalStateException e = expectThrows(
205+
IllegalStateException.class,
206+
() -> Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock));
207+
final String message = String.format(
208+
Locale.ROOT,
209+
"detected index data in default.path.data [%s] where there should not be any; check the logs for details",
210+
defaultPathData);
211+
assertThat(e, hasToString(containsString(message)));
212+
verify(mock)
213+
.error("detected index data in default.path.data [{}] where there should not be any", defaultNodePath.indicesPath);
214+
for (final String index : indices) {
215+
verify(mock).info(
216+
"index folder [{}] in default.path.data [{}] must be moved to any of {}",
217+
index,
218+
defaultNodePath.indicesPath,
219+
Arrays.stream(nodeEnv.nodePaths()).map(np -> np.indicesPath).collect(Collectors.toList()));
220+
}
221+
verifyNoMoreInteractions(mock);
222+
} else {
223+
Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock);
224+
verifyNoMoreInteractions(mock);
225+
}
226+
}
227+
}
228+
229+
public void testDefaultPathDataNotSet() throws IOException {
230+
final Path zero = createTempDir().toAbsolutePath();
231+
final Path one = createTempDir().toAbsolutePath();
232+
final Settings settings = Settings.builder()
233+
.put("path.home", "/home")
234+
.put("path.data.0", zero)
235+
.put("path.data.1", one)
236+
.build();
237+
try (NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings))) {
238+
final Logger mock = mock(Logger.class);
239+
Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock);
240+
verifyNoMoreInteractions(mock);
241+
}
242+
}
243+
168244
private static Settings.Builder baseSettings() {
169245
final Path tempDir = createTempDir();
170246
return Settings.builder()
171-
.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), InternalTestCluster.clusterName("single-node-cluster", randomLong()))
172-
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
173-
.put(NetworkModule.HTTP_ENABLED.getKey(), false)
174-
.put("transport.type", "mock-socket-network")
175-
.put(Node.NODE_DATA_SETTING.getKey(), true);
247+
.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), InternalTestCluster.clusterName("single-node-cluster", randomLong()))
248+
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
249+
.put(NetworkModule.HTTP_ENABLED.getKey(), false)
250+
.put("transport.type", "mock-socket-network")
251+
.put(Node.NODE_DATA_SETTING.getKey(), true);
176252
}
177253

254+
178255
}

0 commit comments

Comments
 (0)