You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hbase.apache.org by ta...@apache.org on 2026/10/13 20:49:22 UTC
(hbase) branch HBASE-30018 updated: HBASE-30407 Add persistence support for cache components (#8739)
This is an automated email from the ASF dual-hosted git repository.
taklwu pushed a commit to branch HBASE-30018
in repository https://gitbox.apache.org/repos/asf/hbase.git
The following commit(s) were added to refs/heads/HBASE-30018 by this push:
new e735b10fa57 HBASE-30407 Add persistence support for cache components (#8739)
e735b10fa57 is described below
commit e735b10fa575ca06bc4f2ffb9381bdee69dfeb63
Author: Vladimir Rodionov <vl...@gmail.com>
AuthorDate: Tue Oct 13 13:49:15 2026 -0700
HBASE-30407 Add persistence support for cache components (#8739)
Signed-off-by: Tak Lon (Stephen) Wu <ta...@apache.org>
---
.../hbase/io/hfile/cache/CacheAccessService.java | 25 ++
.../io/hfile/cache/PersistentCacheComponent.java | 100 +++++
.../cache/TopologyBackedCacheAccessService.java | 27 +-
.../persistence/CachePersistenceCoordinator.java | 228 ++++++++++
.../cache/persistence/CachePersistenceOutput.java | 81 ++++
.../cache/persistence/CachePersistenceStorage.java | 66 +++
.../HadoopFsCachePersistenceStorage.java | 474 +++++++++++++++++++++
.../TestTopologyBackedCacheAccessService.java | 73 ++++
.../TestCachePersistenceCoordinator.java | 296 +++++++++++++
.../TestHadoopFsCachePersistenceStorage.java | 449 +++++++++++++++++++
10 files changed, 1818 insertions(+), 1 deletion(-)
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/CacheAccessService.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/CacheAccessService.java
index ceadedcd6dd..d0da4a479a3 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/CacheAccessService.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/CacheAccessService.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.hbase.io.hfile.cache;
+import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -30,6 +31,7 @@ import org.apache.hadoop.hbase.io.hfile.CacheStats;
import org.apache.hadoop.hbase.io.hfile.Cacheable;
import org.apache.hadoop.hbase.io.hfile.HFileBlock;
import org.apache.hadoop.hbase.io.hfile.HFileInfo;
+import org.apache.hadoop.hbase.io.hfile.cache.persistence.CachePersistenceStorage;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.yetus.audience.InterfaceAudience;
@@ -554,4 +556,27 @@ public interface CacheAccessService extends ConfigurationObserver {
return Optional.empty();
}
+ /**
+ * Saves persistent state owned by cache components managed by this service.
+ * <p>
+ * The default implementation performs no persistence. Implementations which manage persistent
+ * cache components should override this method and coordinate their persistence.
+ * </p>
+ * @param storage storage used to persist cache component state
+ * @throws IOException if persistent state cannot be saved
+ */
+ default void savePersistentState(CachePersistenceStorage storage) throws IOException {
+ }
+
+ /**
+ * Restores persistent state into cache components managed by this service.
+ * <p>
+ * Components must already have been constructed and configured before this method is invoked. The
+ * default implementation performs no restoration.
+ * </p>
+ * @param storage storage from which cache component state is restored
+ * @throws IOException if persistent state cannot be restored
+ */
+ default void restorePersistentState(CachePersistenceStorage storage) throws IOException {
+ }
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/PersistentCacheComponent.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/PersistentCacheComponent.java
new file mode 100644
index 00000000000..8cea2f53400
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/PersistentCacheComponent.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.yetus.audience.InterfaceAudience;
+
+/**
+ * Defines persistence capability for a cache component.
+ * <p>
+ * Implementing this interface indicates that a cache component owns runtime state which can be
+ * saved and restored across process restarts. Persistence is optional; cache components that do not
+ * support persistence simply do not implement this interface.
+ * </p>
+ * <p>
+ * A persistent component is constructed and configured normally before
+ * {@link #restore(InputStream)} is invoked. Persistence restores runtime state into the existing
+ * component instance and must not construct, configure, or replace the component.
+ * </p>
+ * <p>
+ * Current configuration remains authoritative when persisted state is restored. Implementations are
+ * responsible for applying their current configuration and runtime constraints to restored state.
+ * </p>
+ * <p>
+ * Each component persists only state that it directly owns. A topology, for example, must not
+ * recursively persist its cache engines, and a cache engine must not persist topology or placement
+ * policy state.
+ * </p>
+ * <p>
+ * Input and output streams are supplied and owned by the caller. Implementations must not close
+ * either stream.
+ * </p>
+ */
+@InterfaceAudience.Private
+public interface PersistentCacheComponent {
+
+ /**
+ * Returns a stable identifier for this component's persistence format.
+ * <p>
+ * The identifier is used together with the component's role in the cache hierarchy to locate
+ * persisted state. It must remain stable across process restarts and should remain unchanged
+ * while the component remains compatible with previously persisted state.
+ * </p>
+ * <p>
+ * The identifier describes the persistent component type or persistence format, not its placement
+ * in a topology. For example, an engine should return an identifier such as
+ * {@code bucket-cache-engine}, not {@code L2}.
+ * </p>
+ * <p>
+ * The identifier must be non-empty and must not contain path separators.
+ * </p>
+ * @return stable persistence identifier
+ */
+ String getPersistenceId();
+
+ /**
+ * Restores persisted runtime state into this component.
+ * <p>
+ * The component must already be constructed and initialized using the current configuration.
+ * Restored state is subject to the component's current configuration and constraints.
+ * </p>
+ * <p>
+ * This method must not close the supplied input stream.
+ * </p>
+ * @param input input stream containing persisted component state
+ * @throws IOException if persisted state cannot be read or restored
+ */
+ void restore(InputStream input) throws IOException;
+
+ /**
+ * Saves this component's runtime state to the supplied output stream.
+ * <p>
+ * Only state directly owned by this component should be written. Child cache components must not
+ * be persisted recursively by this method.
+ * </p>
+ * <p>
+ * This method must not close the supplied output stream.
+ * </p>
+ * @param output output stream to which component state is written
+ * @throws IOException if component state cannot be saved
+ */
+ void save(OutputStream output) throws IOException;
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/TopologyBackedCacheAccessService.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/TopologyBackedCacheAccessService.java
index d73e1f824a2..5c5034172cf 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/TopologyBackedCacheAccessService.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/TopologyBackedCacheAccessService.java
@@ -17,6 +17,7 @@
*/
package org.apache.hadoop.hbase.io.hfile.cache;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -35,6 +36,8 @@ import org.apache.hadoop.hbase.io.hfile.Cacheable;
import org.apache.hadoop.hbase.io.hfile.CachedBlock;
import org.apache.hadoop.hbase.io.hfile.HFileBlock;
import org.apache.hadoop.hbase.io.hfile.HFileInfo;
+import org.apache.hadoop.hbase.io.hfile.cache.persistence.CachePersistenceCoordinator;
+import org.apache.hadoop.hbase.io.hfile.cache.persistence.CachePersistenceStorage;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.yetus.audience.InterfaceAudience;
@@ -61,6 +64,7 @@ public class TopologyBackedCacheAccessService implements CacheAccessService, Ite
private final CacheTopology topology;
private final CachePlacementAdmissionPolicy policy;
private final CacheTopologyView topologyView;
+ private final CachePersistenceCoordinator persistenceCoordinator;
/**
* Creates a topology-backed cache access service.
@@ -77,6 +81,7 @@ public class TopologyBackedCacheAccessService implements CacheAccessService, Ite
topology.getEngine(tier)
.ifPresent(engine -> engine.setEvictionListener(this::handleEngineEviction));
}
+ this.persistenceCoordinator = new CachePersistenceCoordinator(topology, policy);
}
/**
@@ -743,7 +748,6 @@ public class TopologyBackedCacheAccessService implements CacheAccessService, Ite
return currentIterator.next();
}
};
-
return Optional.of(cachedBlocks);
}
@@ -762,4 +766,25 @@ public class TopologyBackedCacheAccessService implements CacheAccessService, Ite
Cacheable block) {
topology.handleEviction(cacheKey, block, sourceEngine);
}
+
+ /**
+ * Saves persistent state for cache components managed by this service.
+ * @param storage storage used to persist cache component state
+ * @throws IOException if persistent state cannot be saved
+ */
+ @Override
+ public void savePersistentState(CachePersistenceStorage storage) throws IOException {
+ persistenceCoordinator.save(storage);
+ }
+
+ /**
+ * Restores persistent state into cache components managed by this service.
+ * @param storage storage from which cache component state is restored
+ * @throws IOException if persistent state cannot be restored
+ */
+ @Override
+ public void restorePersistentState(CachePersistenceStorage storage) throws IOException {
+ persistenceCoordinator.restore(storage);
+ }
+
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceCoordinator.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceCoordinator.java
new file mode 100644
index 00000000000..825a4b50c25
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceCoordinator.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.Optional;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheEngine;
+import org.apache.hadoop.hbase.io.hfile.cache.CachePlacementAdmissionPolicy;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTier;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTopology;
+import org.apache.hadoop.hbase.io.hfile.cache.PersistentCacheComponent;
+import org.apache.yetus.audience.InterfaceAudience;
+
+/**
+ * Coordinates persistence of the components participating in a cache hierarchy.
+ * <p>
+ * Persistence capability is discovered dynamically. A cache topology, placement/admission policy,
+ * or cache engine participates in persistence only when its concrete implementation implements
+ * {@link PersistentCacheComponent}.
+ * </p>
+ * <p>
+ * Components are persisted independently. In particular, a persistent topology is responsible only
+ * for topology-owned state and must not persist its cache engines. The coordinator discovers and
+ * persists each engine separately.
+ * </p>
+ * <p>
+ * The coordinator assigns every persistent component a storage key composed from the component's
+ * role in the cache hierarchy and its stable {@link PersistentCacheComponent#getPersistenceId()
+ * persistence identifier}. This prevents state belonging to one engine implementation from being
+ * restored into another implementation occupying the same cache tier after a configuration change.
+ * </p>
+ * <p>
+ * All components must already have been constructed from the current configuration before
+ * {@link #restore(CachePersistenceStorage)} is called. Restore modifies only the runtime state of
+ * those existing component instances.
+ * </p>
+ */
+@InterfaceAudience.Private
+public final class CachePersistenceCoordinator {
+
+ private static final String TOPOLOGY_ROLE = "topology";
+ private static final String POLICY_ROLE = "policy";
+ private static final String ENGINE_ROLE = "engine";
+
+ private final CacheTopology topology;
+ private final CachePlacementAdmissionPolicy policy;
+
+ /**
+ * Creates a persistence coordinator for the supplied cache topology and placement/admission
+ * policy.
+ * @param topology active cache topology
+ * @param policy active cache placement/admission policy
+ */
+ public CachePersistenceCoordinator(CacheTopology topology, CachePlacementAdmissionPolicy policy) {
+ this.topology = Objects.requireNonNull(topology, "topology must not be null");
+ this.policy = Objects.requireNonNull(policy, "policy must not be null");
+ }
+
+ /**
+ * Saves the state of all persistent components participating in the cache hierarchy.
+ * <p>
+ * Components that do not implement {@link PersistentCacheComponent} are skipped. The topology,
+ * placement/admission policy, and each cache engine are considered independently.
+ * </p>
+ * <p>
+ * This method owns and closes all streams obtained from the supplied storage. Persistent cache
+ * components must not close those streams themselves.
+ * </p>
+ * @param storage storage used to persist component state
+ * @throws IOException if component state cannot be saved
+ */
+ public void save(CachePersistenceStorage storage) throws IOException {
+ Objects.requireNonNull(storage, "storage must not be null");
+
+ saveComponent(storage, TOPOLOGY_ROLE, topology);
+ saveComponent(storage, POLICY_ROLE, policy);
+
+ for (CacheTier tier : topology.getTiers()) {
+ Optional<CacheEngine> engine = topology.getEngine(tier);
+ if (engine.isPresent()) {
+ saveComponent(storage, getEngineRole(tier), engine.get());
+ }
+ }
+ }
+
+ /**
+ * Restores the state of all persistent components participating in the cache hierarchy.
+ * <p>
+ * Components that do not implement {@link PersistentCacheComponent} are skipped. Missing
+ * persisted state is also ignored, allowing newly configured components to start without a
+ * previous checkpoint.
+ * </p>
+ * <p>
+ * Restore operates on the existing topology, policy, and engine instances. No component is
+ * constructed or replaced by this method.
+ * </p>
+ * <p>
+ * This method owns and closes all streams obtained from the supplied storage. Persistent cache
+ * components must not close those streams themselves.
+ * </p>
+ * @param storage storage from which persisted component state is restored
+ * @throws IOException if persisted component state exists but cannot be restored
+ */
+ public void restore(CachePersistenceStorage storage) throws IOException {
+ Objects.requireNonNull(storage, "storage must not be null");
+
+ restoreComponent(storage, TOPOLOGY_ROLE, topology);
+ restoreComponent(storage, POLICY_ROLE, policy);
+
+ for (CacheTier tier : topology.getTiers()) {
+ Optional<CacheEngine> engine = topology.getEngine(tier);
+ if (engine.isPresent()) {
+ restoreComponent(storage, getEngineRole(tier), engine.get());
+ }
+ }
+ }
+
+ /**
+ * Saves a component when that component implements {@link PersistentCacheComponent}.
+ * @param storage persistence storage
+ * @param role component role within the cache hierarchy
+ * @param component component to inspect and persist
+ * @throws IOException if component state cannot be saved
+ */
+ private void saveComponent(CachePersistenceStorage storage, String role, Object component)
+ throws IOException {
+ if (!(component instanceof PersistentCacheComponent)) {
+ return;
+ }
+
+ PersistentCacheComponent persistent = (PersistentCacheComponent) component;
+ String key = getStorageKey(role, persistent);
+
+ try (CachePersistenceOutput output = storage.create(key)) {
+ persistent.save(output.getOutputStream());
+ output.commit();
+ }
+ }
+
+ /**
+ * Restores a component when that component implements {@link PersistentCacheComponent} and
+ * persisted state exists for it.
+ * @param storage persistence storage
+ * @param role component role within the cache hierarchy
+ * @param component component to inspect and restore
+ * @throws IOException if persisted state exists but cannot be restored
+ */
+ private void restoreComponent(CachePersistenceStorage storage, String role, Object component)
+ throws IOException {
+ if (!(component instanceof PersistentCacheComponent)) {
+ return;
+ }
+
+ PersistentCacheComponent persistent = (PersistentCacheComponent) component;
+ String key = getStorageKey(role, persistent);
+ Optional<InputStream> input = storage.open(key);
+
+ if (!input.isPresent()) {
+ return;
+ }
+
+ try (InputStream stream = input.get()) {
+ persistent.restore(stream);
+ }
+ }
+
+ /**
+ * Builds the storage key for a persistent component.
+ * @param role component role within the cache hierarchy
+ * @param component persistent component
+ * @return stable storage key for the component
+ */
+ private String getStorageKey(String role, PersistentCacheComponent component) {
+ String persistenceId =
+ Objects.requireNonNull(component.getPersistenceId(), "persistenceId must not be null");
+
+ validatePersistenceId(persistenceId);
+ return role + "/" + persistenceId;
+ }
+
+ /**
+ * Returns the persistence role assigned to an engine in the specified cache tier.
+ * @param tier cache tier occupied by the engine
+ * @return persistence role for the engine
+ */
+ private String getEngineRole(CacheTier tier) {
+ Objects.requireNonNull(tier, "tier must not be null");
+ return ENGINE_ROLE + "/" + tier.name().toLowerCase(Locale.ROOT);
+ }
+
+ /**
+ * Validates a component persistence identifier.
+ * <p>
+ * Component persistence identifiers are single path components. Placement information such as
+ * topology tier is supplied separately by the coordinator and therefore must not be encoded in
+ * the component identifier.
+ * </p>
+ * @param persistenceId persistence identifier to validate
+ * @throws IllegalArgumentException if the identifier is empty or contains a path separator
+ */
+ private void validatePersistenceId(String persistenceId) {
+ if (persistenceId.isEmpty()) {
+ throw new IllegalArgumentException("persistenceId must not be empty");
+ }
+ if (persistenceId.indexOf('/') >= 0 || persistenceId.indexOf('\\') >= 0) {
+ throw new IllegalArgumentException(
+ "persistenceId must not contain a path separator: " + persistenceId);
+ }
+ }
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceOutput.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceOutput.java
new file mode 100644
index 00000000000..626ad3336c7
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceOutput.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import org.apache.yetus.audience.InterfaceAudience;
+
+/**
+ * Represents an in-progress cache persistence write.
+ * <p>
+ * A persistence write is not visible as committed state until {@link #commit()} completes
+ * successfully. If the write is abandoned or an error occurs before commit, {@link #abort()}
+ * discards the incomplete state.
+ * </p>
+ * <p>
+ * {@link #close()} must abort an uncommitted write. This makes the handle safe to use with
+ * try-with-resources when a cache component throws while saving its state.
+ * </p>
+ * <p>
+ * The output stream returned by {@link #getOutputStream()} is owned by this handle. Cache
+ * components may write to the stream but must not close it directly.
+ * </p>
+ */
+@InterfaceAudience.Private
+public interface CachePersistenceOutput extends AutoCloseable {
+
+ /**
+ * Returns the output stream to which the cache component should write its persisted state.
+ * <p>
+ * The returned stream must not be closed by the cache component.
+ * </p>
+ * @return output stream for persisted component state
+ */
+ OutputStream getOutputStream();
+
+ /**
+ * Commits the completed persistence write.
+ * <p>
+ * After this method returns successfully, the newly written state becomes the state returned by
+ * subsequent persistence reads for the associated storage key.
+ * </p>
+ * @throws IOException if the state cannot be committed
+ */
+ void commit() throws IOException;
+
+ /**
+ * Aborts the persistence write and discards any incomplete state.
+ * <p>
+ * Calling this method after a successful commit has no effect.
+ * </p>
+ * @throws IOException if temporary state cannot be discarded
+ */
+ void abort() throws IOException;
+
+ /**
+ * Closes this persistence output.
+ * <p>
+ * If the write has not been committed, closing the handle aborts it. Closing the handle must
+ * never implicitly commit an unfinished write.
+ * </p>
+ * @throws IOException if the output cannot be closed or temporary state cannot be discarded
+ */
+ @Override
+ void close() throws IOException;
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceStorage.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceStorage.java
new file mode 100644
index 00000000000..35b79662ba6
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/CachePersistenceStorage.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Optional;
+import org.apache.yetus.audience.InterfaceAudience;
+
+/**
+ * Provides storage for persisted cache component state.
+ * <p>
+ * This abstraction separates cache persistence from the filesystem or storage system used to store
+ * persisted data. Cache components operate only on streams and do not depend on files, paths, or a
+ * particular storage implementation.
+ * </p>
+ * <p>
+ * Persistence storage keys are assigned by higher-level cache persistence infrastructure.
+ * Implementations may map those keys to files, objects, database entries, or another storage
+ * representation.
+ * </p>
+ */
+@InterfaceAudience.Private
+public interface CachePersistenceStorage {
+
+ /**
+ * Opens committed persisted state associated with the specified storage key.
+ * <p>
+ * Absence of persisted state is not an error and is represented by an empty {@link Optional}.
+ * </p>
+ * <p>
+ * The returned input stream is owned by the caller and must be closed by the caller.
+ * </p>
+ * @param key stable storage key assigned to a persistent cache component
+ * @return input stream containing persisted state, or an empty optional if no state exists
+ * @throws IOException if committed state exists but cannot be opened
+ */
+ Optional<InputStream> open(String key) throws IOException;
+
+ /**
+ * Starts a new persistence write for the specified storage key.
+ * <p>
+ * The write does not replace previously committed state until
+ * {@link CachePersistenceOutput#commit()} completes successfully.
+ * </p>
+ * @param key stable storage key assigned to a persistent cache component
+ * @return handle for writing and committing persisted state
+ * @throws IOException if the persistence write cannot be started
+ */
+ CachePersistenceOutput create(String key) throws IOException;
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/HadoopFsCachePersistenceStorage.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/HadoopFsCachePersistenceStorage.java
new file mode 100644
index 00000000000..1f6e49f0145
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/HadoopFsCachePersistenceStorage.java
@@ -0,0 +1,474 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.yetus.audience.InterfaceAudience;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@link CachePersistenceStorage} implementation backed by a Hadoop {@link FileSystem}.
+ * <p>
+ * This implementation works with filesystems available through Hadoop's filesystem abstraction,
+ * including HDFS and the local filesystem.
+ * </p>
+ * <p>
+ * Every persistence storage key is represented as a file below a configured root directory. Keys
+ * may contain relative path components separated by {@code /}, allowing higher-level persistence
+ * infrastructure to organize state by component role.
+ * </p>
+ * <p>
+ * Persistence writes are first written to a temporary file. The temporary file is promoted to the
+ * committed state path only after the caller explicitly commits the write. An abandoned write
+ * deletes its temporary file and leaves previously committed state unchanged.
+ * </p>
+ * <p>
+ * Publication uses filesystem rename operations. Rename atomicity and implementation details are
+ * determined by the underlying Hadoop filesystem. For filesystems where rename is implemented as
+ * copy-and-delete, publication has the corresponding filesystem semantics.
+ * </p>
+ * <p>
+ * This class does not own the supplied {@link FileSystem} and does not close it.
+ * </p>
+ */
+@InterfaceAudience.Private
+public class HadoopFsCachePersistenceStorage implements CachePersistenceStorage {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HadoopFsCachePersistenceStorage.class);
+ private static final String STATE_FILE_SUFFIX = ".state";
+ private static final String TEMP_FILE_MARKER = ".tmp-";
+ private static final String BACKUP_FILE_SUFFIX = ".backup";
+
+ private final FileSystem fileSystem;
+ private final Path rootPath;
+
+ /**
+ * Creates persistence storage using the filesystem associated with the supplied root path.
+ * @param conf Hadoop configuration used to resolve the filesystem
+ * @param rootPath root directory under which persisted cache state is stored
+ * @throws IOException if the filesystem for the root path cannot be resolved
+ */
+ public HadoopFsCachePersistenceStorage(Configuration conf, Path rootPath) throws IOException {
+ this(resolveFileSystem(conf, rootPath), rootPath);
+ }
+
+ /**
+ * Creates persistence storage using an explicitly supplied Hadoop filesystem.
+ * <p>
+ * The supplied filesystem remains owned by the caller and is not closed by this storage instance.
+ * </p>
+ * @param fileSystem Hadoop filesystem used to store cache state
+ * @param rootPath root directory under which persisted cache state is stored
+ */
+ public HadoopFsCachePersistenceStorage(FileSystem fileSystem, Path rootPath) {
+ this.fileSystem = Objects.requireNonNull(fileSystem, "fileSystem must not be null");
+ this.rootPath = Objects.requireNonNull(rootPath, "rootPath must not be null");
+ }
+
+ /**
+ * Opens committed persisted state for the specified storage key.
+ * @param key stable storage key assigned to a persistent cache component
+ * @return input stream containing committed state, or an empty optional if no state exists
+ * @throws IOException if committed state exists but cannot be opened
+ */
+ @Override
+ public Optional<InputStream> open(String key) throws IOException {
+ Path path = getStatePath(key);
+ recoverCommittedState(path);
+
+ if (!fileSystem.exists(path)) {
+ return Optional.empty();
+ }
+ return Optional.of(fileSystem.open(path));
+ }
+
+ /**
+ * Starts a new persistence write for the specified storage key.
+ * <p>
+ * Data is written to a temporary file located next to the final state file. The temporary file
+ * becomes committed state only when the returned handle is explicitly committed.
+ * </p>
+ * @param key stable storage key assigned to a persistent cache component
+ * @return handle for writing and committing persisted state
+ * @throws IOException if the temporary persistence file cannot be created
+ */
+ @Override
+ public CachePersistenceOutput create(String key) throws IOException {
+ Path targetPath = getStatePath(key);
+ Path parent = targetPath.getParent();
+ ensureDirectory(parent);
+ recoverCommittedState(targetPath);
+
+ Path temporaryPath = createTemporaryPath(targetPath);
+ FSDataOutputStream output = fileSystem.create(temporaryPath, false);
+
+ return new HadoopFsCachePersistenceOutput(fileSystem, output, temporaryPath, targetPath);
+ }
+
+ /**
+ * Creates the parent directory for a persistence state file when necessary.
+ * @param directory directory to create
+ * @throws IOException if the directory cannot be created
+ */
+ private void ensureDirectory(Path directory) throws IOException {
+ if (directory == null || fileSystem.exists(directory)) {
+ return;
+ }
+
+ if (!fileSystem.mkdirs(directory) && !fileSystem.exists(directory)) {
+ throw new IOException("Failed to create cache persistence directory " + directory);
+ }
+ }
+
+ /**
+ * Creates a unique temporary path adjacent to the specified committed state path.
+ * @param targetPath committed state path
+ * @return unique temporary path
+ */
+ private Path createTemporaryPath(Path targetPath) {
+ return new Path(targetPath.toString() + TEMP_FILE_MARKER + UUID.randomUUID());
+ }
+
+ /**
+ * Resolves the Hadoop filesystem associated with the supplied persistence root path.
+ * @param conf Hadoop configuration used to resolve the filesystem
+ * @param rootPath persistence root path
+ * @return filesystem associated with the root path
+ * @throws IOException if the filesystem cannot be resolved
+ */
+ private static FileSystem resolveFileSystem(Configuration conf, Path rootPath)
+ throws IOException {
+ Objects.requireNonNull(conf, "conf must not be null");
+ Objects.requireNonNull(rootPath, "rootPath must not be null");
+ return rootPath.getFileSystem(conf);
+ }
+
+ /**
+ * Returns the filesystem path containing committed state for the supplied persistence key.
+ * @param key persistence storage key
+ * @return filesystem path containing committed persisted state
+ */
+ private Path getStatePath(String key) {
+ validateKey(key);
+ return new Path(rootPath, key + STATE_FILE_SUFFIX);
+ }
+
+ /**
+ * Validates a persistence storage key before using it as a relative filesystem path.
+ * <p>
+ * Storage keys must be relative and may contain multiple path segments. Empty segments and the
+ * special {@code .} and {@code ..} path segments are not allowed.
+ * </p>
+ * @param key persistence storage key to validate
+ * @throws NullPointerException if the key is {@code null}
+ * @throws IllegalArgumentException if the key is empty or contains an invalid path component
+ */
+ private void validateKey(String key) {
+ Objects.requireNonNull(key, "key must not be null");
+
+ if (key.isEmpty()) {
+ throw new IllegalArgumentException("key must not be empty");
+ }
+ if (
+ key.startsWith("/") || key.endsWith("/") || key.indexOf('\\') >= 0 || key.contains("://")
+ || new Path(key + STATE_FILE_SUFFIX).toUri().getScheme() != null
+ ) {
+ throw new IllegalArgumentException("Invalid persistence key: " + key);
+ }
+
+ String[] components = key.split("/");
+ for (String component : components) {
+ if (component.isEmpty() || ".".equals(component) || "..".equals(component)) {
+ throw new IllegalArgumentException("Invalid persistence key: " + key);
+ }
+ }
+ }
+
+ /**
+ * Recovers previously committed state when publication was interrupted after the committed state
+ * was moved to its backup location.
+ * <p>
+ * If the normal state file exists, no recovery is required. If it is absent and a backup exists,
+ * the backup represents the last successfully committed state and is restored to the normal state
+ * path.
+ * </p>
+ * @param targetPath committed persistence state path
+ * @throws IOException if previously committed state cannot be recovered
+ */
+ private void recoverCommittedState(Path targetPath) throws IOException {
+ if (fileSystem.exists(targetPath)) {
+ return;
+ }
+
+ Path backupPath = getBackupPath(targetPath);
+ if (!fileSystem.exists(backupPath)) {
+ return;
+ }
+
+ if (!fileSystem.rename(backupPath, targetPath)) {
+ throw new IOException(
+ "Failed to recover committed cache persistence state " + backupPath + " to " + targetPath);
+ }
+ }
+
+ /**
+ * Returns the backup path used while replacing committed persistence state.
+ * @param targetPath committed persistence state path
+ * @return backup path for the committed state
+ */
+ private static Path getBackupPath(Path targetPath) {
+ return new Path(targetPath.toString() + BACKUP_FILE_SUFFIX);
+ }
+
+ /**
+ * Persistence output backed by a temporary Hadoop filesystem file.
+ * <p>
+ * A successful commit closes the temporary output stream and publishes the temporary file as the
+ * committed state file. Closing an uncommitted instance aborts the write.
+ * </p>
+ */
+ private static final class HadoopFsCachePersistenceOutput implements CachePersistenceOutput {
+
+ private final FileSystem fileSystem;
+ private final FSDataOutputStream output;
+ private final Path temporaryPath;
+ private final Path targetPath;
+
+ private boolean streamClosed;
+ private boolean committed;
+ private boolean aborted;
+
+ /**
+ * Creates a persistence output backed by a temporary filesystem file.
+ * @param fileSystem filesystem containing the temporary and target files
+ * @param output output stream writing the temporary file
+ * @param temporaryPath temporary persistence file
+ * @param targetPath committed persistence file
+ */
+ private HadoopFsCachePersistenceOutput(FileSystem fileSystem, FSDataOutputStream output,
+ Path temporaryPath, Path targetPath) {
+ this.fileSystem = Objects.requireNonNull(fileSystem, "fileSystem must not be null");
+ this.output = Objects.requireNonNull(output, "output must not be null");
+ this.temporaryPath = Objects.requireNonNull(temporaryPath, "temporaryPath must not be null");
+ this.targetPath = Objects.requireNonNull(targetPath, "targetPath must not be null");
+ }
+
+ /**
+ * Returns the stream used to write temporary persisted state.
+ * @return persistence output stream
+ */
+ @Override
+ public OutputStream getOutputStream() {
+ return output;
+ }
+
+ /**
+ * Commits the persistence write by publishing the completed temporary file.
+ * <p>
+ * If previously committed state exists, it is moved temporarily out of the way before the new
+ * state is published. If publication of the new state fails, this method attempts to restore
+ * the previous committed state.
+ * </p>
+ * @throws IOException if the output cannot be closed or the new state cannot be published
+ */
+ @Override
+ public void commit() throws IOException {
+ ensureActive();
+
+ closeOutput();
+
+ Path backupPath = getBackupPath(targetPath);
+ boolean previousStateMoved = false;
+
+ try {
+ if (fileSystem.exists(targetPath)) {
+ if (fileSystem.exists(backupPath) && !fileSystem.delete(backupPath, false)) {
+ throw new IOException("Failed to delete stale cache persistence backup " + backupPath);
+ }
+
+ if (!fileSystem.rename(targetPath, backupPath)) {
+ throw new IOException(
+ "Failed to preserve existing cache persistence state " + targetPath);
+ }
+ previousStateMoved = true;
+ }
+
+ if (!fileSystem.rename(temporaryPath, targetPath)) {
+ throw new IOException(
+ "Failed to publish cache persistence state " + temporaryPath + " to " + targetPath);
+ }
+
+ committed = true;
+
+ if (previousStateMoved) {
+ deleteBackupAfterCommit(backupPath);
+ }
+
+ } catch (IOException error) {
+ if (!committed && previousStateMoved) {
+ restorePreviousState(backupPath, error);
+ }
+ throw error;
+ }
+ }
+
+ /**
+ * Removes the previous committed-state backup after a new state has been successfully
+ * published.
+ * <p>
+ * Backup cleanup is best-effort. Once the new state has been published, failure to remove the
+ * obsolete backup must not cause the persistence operation to be reported as failed.
+ * </p>
+ * @param backupPath backup containing the previously committed state
+ */
+ private void deleteBackupAfterCommit(Path backupPath) {
+ try {
+ if (fileSystem.exists(backupPath) && !fileSystem.delete(backupPath, false)) {
+ LOG.warn("Failed to delete obsolete cache persistence backup {}", backupPath);
+ }
+ } catch (IOException error) {
+ LOG.warn("Failed to delete obsolete cache persistence backup {}", backupPath, error);
+ }
+ }
+
+ /**
+ * Aborts the persistence write and removes its temporary file.
+ * <p>
+ * Calling this method after a successful commit has no effect.
+ * </p>
+ * @throws IOException if the output cannot be closed or the temporary file cannot be removed
+ */
+ @Override
+ public void abort() throws IOException {
+ if (committed || aborted) {
+ return;
+ }
+
+ IOException failure = null;
+
+ try {
+ closeOutput();
+ } catch (IOException error) {
+ failure = error;
+ }
+
+ try {
+ deleteTemporaryFile();
+ } catch (IOException error) {
+ if (failure == null) {
+ failure = error;
+ } else {
+ failure.addSuppressed(error);
+ }
+ }
+
+ aborted = true;
+
+ if (failure != null) {
+ throw failure;
+ }
+ }
+
+ /**
+ * Closes this persistence output.
+ * <p>
+ * An uncommitted output is aborted. A successfully committed or previously aborted output
+ * requires no further action.
+ * </p>
+ * @throws IOException if an uncommitted write cannot be aborted
+ */
+ @Override
+ public void close() throws IOException {
+ if (!committed && !aborted) {
+ abort();
+ }
+ }
+
+ /**
+ * Verifies that this persistence output is still available for commit.
+ * @throws IllegalStateException if this output has already been committed or aborted
+ */
+ private void ensureActive() {
+ if (committed) {
+ throw new IllegalStateException("Persistence output has already been committed");
+ }
+ if (aborted) {
+ throw new IllegalStateException("Persistence output has already been aborted");
+ }
+ }
+
+ /**
+ * Closes the temporary file output stream if it is still open.
+ * @throws IOException if the output stream cannot be closed
+ */
+ private void closeOutput() throws IOException {
+ if (!streamClosed) {
+ output.close();
+ streamClosed = true;
+ }
+ }
+
+ /**
+ * Removes the temporary persistence file if it still exists.
+ * @throws IOException if the temporary file exists but cannot be removed
+ */
+ private void deleteTemporaryFile() throws IOException {
+ if (fileSystem.exists(temporaryPath) && !fileSystem.delete(temporaryPath, false)) {
+ throw new IOException(
+ "Failed to delete temporary cache persistence state " + temporaryPath);
+ }
+ }
+
+ /**
+ * Attempts to restore the previous committed state after publication of new state fails.
+ * <p>
+ * A rollback failure is added as a suppressed exception to the original publication failure.
+ * </p>
+ * @param backupPath path containing the previous committed state
+ * @param originalFailure original publication failure
+ */
+ private void restorePreviousState(Path backupPath, IOException originalFailure) {
+ if (backupPath == null) {
+ return;
+ }
+
+ try {
+ if (fileSystem.exists(targetPath)) {
+ fileSystem.delete(targetPath, false);
+ }
+
+ if (!fileSystem.rename(backupPath, targetPath)) {
+ originalFailure.addSuppressed(
+ new IOException("Failed to restore previous cache persistence state " + backupPath));
+ }
+ } catch (IOException rollbackFailure) {
+ originalFailure.addSuppressed(rollbackFailure);
+ }
+ }
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/TestTopologyBackedCacheAccessService.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/TestTopologyBackedCacheAccessService.java
index 4f7967e7ad5..f8019f45f7f 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/TestTopologyBackedCacheAccessService.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/TestTopologyBackedCacheAccessService.java
@@ -26,7 +26,11 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import org.apache.hadoop.conf.Configuration;
@@ -35,6 +39,8 @@ import org.apache.hadoop.hbase.io.hfile.BlockType;
import org.apache.hadoop.hbase.io.hfile.CacheStats;
import org.apache.hadoop.hbase.io.hfile.Cacheable;
import org.apache.hadoop.hbase.io.hfile.HFileBlock;
+import org.apache.hadoop.hbase.io.hfile.cache.persistence.CachePersistenceOutput;
+import org.apache.hadoop.hbase.io.hfile.cache.persistence.CachePersistenceStorage;
import org.apache.hadoop.hbase.testclassification.IOTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.jupiter.api.Tag;
@@ -556,6 +562,73 @@ public class TestTopologyBackedCacheAccessService {
verify(l2).onConfigurationChange(conf);
}
+ /**
+ * Verifies that saving persistent state through the cache access service delegates persistence to
+ * the persistent cache components managed by the service.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testSavePersistentState() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CacheTopologyView view = mock(CacheTopologyView.class);
+ when(topology.getView()).thenReturn(view);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine =
+ mock(CacheEngine.class, withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+ CachePersistenceOutput persistenceOutput = mock(CachePersistenceOutput.class);
+ OutputStream output = mock(OutputStream.class);
+
+ when(persistentEngine.getPersistenceId()).thenReturn("test-engine");
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.create("engine/single/test-engine")).thenReturn(persistenceOutput);
+ when(persistenceOutput.getOutputStream()).thenReturn(output);
+
+ TopologyBackedCacheAccessService service =
+ new TopologyBackedCacheAccessService(topology, policy);
+
+ service.savePersistentState(storage);
+
+ verify(persistentEngine).save(output);
+ verify(persistenceOutput).commit();
+ verify(persistenceOutput).close();
+ }
+
+ /**
+ * Verifies that restoring persistent state through the cache access service delegates restoration
+ * to the persistent cache components managed by the service.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testRestorePersistentState() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CacheTopologyView view = mock(CacheTopologyView.class);
+ when(topology.getView()).thenReturn(view);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine =
+ mock(CacheEngine.class, withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+ InputStream input = mock(InputStream.class);
+
+ when(persistentEngine.getPersistenceId()).thenReturn("test-engine");
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.open("engine/single/test-engine")).thenReturn(Optional.of(input));
+
+ TopologyBackedCacheAccessService service =
+ new TopologyBackedCacheAccessService(topology, policy);
+
+ service.restorePersistentState(storage);
+
+ verify(persistentEngine).restore(input);
+ verify(input).close();
+ }
+
private static CacheRequestContext requestContext() {
return CacheRequestContext.newBuilder().withCaching(true).withRepeat(false)
.withUpdateCacheMetrics(true).withBlockType(BlockType.DATA).build();
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestCachePersistenceCoordinator.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestCachePersistenceCoordinator.java
new file mode 100644
index 00000000000..04886750512
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestCachePersistenceCoordinator.java
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Optional;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheEngine;
+import org.apache.hadoop.hbase.io.hfile.cache.CachePlacementAdmissionPolicy;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTier;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTopology;
+import org.apache.hadoop.hbase.io.hfile.cache.PersistentCacheComponent;
+import org.apache.hadoop.hbase.testclassification.IOTests;
+import org.apache.hadoop.hbase.testclassification.SmallTests;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag(IOTests.TAG)
+@Tag(SmallTests.TAG)
+public class TestCachePersistenceCoordinator {
+
+ /**
+ * Verifies that non-persistent topology, policy, and cache engines are skipped.
+ * @throws IOException if persistence unexpectedly fails
+ */
+ @Test
+ public void testNonPersistentComponentsAreSkipped() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = mock(CacheEngine.class);
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ coordinator.save(storage);
+ coordinator.restore(storage);
+
+ verifyNoInteractions(storage);
+ }
+
+ /**
+ * Verifies that a persistent engine in a single-tier topology is saved using its engine role and
+ * persistence identifier.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testPersistentSingleTierEngineIsSaved() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = createPersistentEngine("test-engine");
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+ CachePersistenceOutput persistenceOutput = mock(CachePersistenceOutput.class);
+ OutputStream output = mock(OutputStream.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.create("engine/single/test-engine")).thenReturn(persistenceOutput);
+ when(persistenceOutput.getOutputStream()).thenReturn(output);
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ coordinator.save(storage);
+
+ verify(storage).create("engine/single/test-engine");
+ verify(persistentEngine).save(output);
+ verify(persistenceOutput).commit();
+ verify(persistenceOutput).close();
+ }
+
+ /**
+ * Verifies that persisted state is restored into the existing engine instance.
+ * @throws IOException if restoration fails
+ */
+ @Test
+ public void testPersistentSingleTierEngineIsRestored() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = createPersistentEngine("test-engine");
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+ InputStream input = mock(InputStream.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.open("engine/single/test-engine")).thenReturn(Optional.of(input));
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ coordinator.restore(storage);
+
+ verify(storage).open("engine/single/test-engine");
+ verify(persistentEngine).restore(input);
+ verify(input).close();
+ }
+
+ /**
+ * Verifies that absence of previously persisted state is not treated as an error.
+ * @throws IOException if restoration unexpectedly fails
+ */
+ @Test
+ public void testMissingPersistentStateIsIgnored() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = createPersistentEngine("test-engine");
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.open("engine/single/test-engine")).thenReturn(Optional.empty());
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ coordinator.restore(storage);
+
+ verify(storage).open("engine/single/test-engine");
+ verify(persistentEngine, never()).restore(org.mockito.ArgumentMatchers.any());
+ }
+
+ /**
+ * Verifies that topology, policy, and cache engine persistence are coordinated independently.
+ * <p>
+ * The L1 engine deliberately does not support persistence, while the L2 engine does.
+ * </p>
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testTieredComponentsArePersistedIndependently() throws IOException {
+ CacheTopology topology = createPersistentTopology("test-topology");
+ CachePlacementAdmissionPolicy policy = createPersistentPolicy("test-policy");
+ CacheEngine l1 = mock(CacheEngine.class);
+ CacheEngine l2 = createPersistentEngine("test-l2");
+
+ PersistentCacheComponent persistentTopology = (PersistentCacheComponent) topology;
+ PersistentCacheComponent persistentPolicy = (PersistentCacheComponent) policy;
+ PersistentCacheComponent persistentL2 = (PersistentCacheComponent) l2;
+
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+
+ CachePersistenceOutput topologyOutput = mock(CachePersistenceOutput.class);
+ CachePersistenceOutput policyOutput = mock(CachePersistenceOutput.class);
+ CachePersistenceOutput l2Output = mock(CachePersistenceOutput.class);
+
+ OutputStream topologyStream = mock(OutputStream.class);
+ OutputStream policyStream = mock(OutputStream.class);
+ OutputStream l2Stream = mock(OutputStream.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.L1, CacheTier.L2));
+ when(topology.getEngine(CacheTier.L1)).thenReturn(Optional.of(l1));
+ when(topology.getEngine(CacheTier.L2)).thenReturn(Optional.of(l2));
+
+ when(storage.create("topology/test-topology")).thenReturn(topologyOutput);
+ when(storage.create("policy/test-policy")).thenReturn(policyOutput);
+ when(storage.create("engine/l2/test-l2")).thenReturn(l2Output);
+
+ when(topologyOutput.getOutputStream()).thenReturn(topologyStream);
+ when(policyOutput.getOutputStream()).thenReturn(policyStream);
+ when(l2Output.getOutputStream()).thenReturn(l2Stream);
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ coordinator.save(storage);
+
+ verify(persistentTopology).save(topologyStream);
+ verify(persistentPolicy).save(policyStream);
+ verify(persistentL2).save(l2Stream);
+
+ verify(topologyOutput).commit();
+ verify(policyOutput).commit();
+ verify(l2Output).commit();
+
+ verify(storage, never()).create(org.mockito.ArgumentMatchers.startsWith("engine/l1/"));
+ }
+
+ /**
+ * Verifies that a component save failure does not commit incomplete persisted state.
+ * @throws IOException if mock setup unexpectedly fails
+ */
+ @Test
+ public void testSaveFailureDoesNotCommit() throws IOException {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = createPersistentEngine("test-engine");
+ PersistentCacheComponent persistentEngine = (PersistentCacheComponent) engine;
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+ CachePersistenceOutput persistenceOutput = mock(CachePersistenceOutput.class);
+ OutputStream output = mock(OutputStream.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+ when(storage.create("engine/single/test-engine")).thenReturn(persistenceOutput);
+ when(persistenceOutput.getOutputStream()).thenReturn(output);
+
+ IOException failure = new IOException("Expected persistence failure");
+ org.mockito.Mockito.doThrow(failure).when(persistentEngine).save(output);
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ assertThrows(IOException.class, () -> coordinator.save(storage));
+
+ verify(persistenceOutput, never()).commit();
+ verify(persistenceOutput).close();
+ }
+
+ /**
+ * Verifies that invalid persistence identifiers are rejected before storage is accessed.
+ */
+ @Test
+ public void testInvalidPersistenceIdIsRejected() {
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine = createPersistentEngine("../invalid");
+ CachePersistenceStorage storage = mock(CachePersistenceStorage.class);
+
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.SINGLE));
+ when(topology.getEngine(CacheTier.SINGLE)).thenReturn(Optional.of(engine));
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ assertThrows(IllegalArgumentException.class, () -> coordinator.save(storage));
+
+ verifyNoInteractions(storage);
+ }
+
+ /**
+ * Creates a cache engine mock that also implements {@link PersistentCacheComponent}.
+ * @param persistenceId persistence identifier returned by the mock
+ * @return persistent cache engine mock
+ */
+ private CacheEngine createPersistentEngine(String persistenceId) {
+ CacheEngine engine =
+ mock(CacheEngine.class, withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistent = (PersistentCacheComponent) engine;
+
+ when(persistent.getPersistenceId()).thenReturn(persistenceId);
+ return engine;
+ }
+
+ /**
+ * Creates a cache topology mock that also implements {@link PersistentCacheComponent}.
+ * @param persistenceId persistence identifier returned by the mock
+ * @return persistent cache topology mock
+ */
+ private CacheTopology createPersistentTopology(String persistenceId) {
+ CacheTopology topology =
+ mock(CacheTopology.class, withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistent = (PersistentCacheComponent) topology;
+
+ when(persistent.getPersistenceId()).thenReturn(persistenceId);
+ return topology;
+ }
+
+ /**
+ * Creates a placement/admission policy mock that also implements
+ * {@link PersistentCacheComponent}.
+ * @param persistenceId persistence identifier returned by the mock
+ * @return persistent placement/admission policy mock
+ */
+ private CachePlacementAdmissionPolicy createPersistentPolicy(String persistenceId) {
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class,
+ withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistent = (PersistentCacheComponent) policy;
+
+ when(persistent.getPersistenceId()).thenReturn(persistenceId);
+ return policy;
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestHadoopFsCachePersistenceStorage.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestHadoopFsCachePersistenceStorage.java
new file mode 100644
index 00000000000..fb253dbe8aa
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/cache/persistence/TestHadoopFsCachePersistenceStorage.java
@@ -0,0 +1,449 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.io.hfile.cache.persistence;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Optional;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheEngine;
+import org.apache.hadoop.hbase.io.hfile.cache.CachePlacementAdmissionPolicy;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTier;
+import org.apache.hadoop.hbase.io.hfile.cache.CacheTopology;
+import org.apache.hadoop.hbase.io.hfile.cache.PersistentCacheComponent;
+import org.apache.hadoop.hbase.testclassification.IOTests;
+import org.apache.hadoop.hbase.testclassification.SmallTests;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+@Tag(IOTests.TAG)
+@Tag(SmallTests.TAG)
+public class TestHadoopFsCachePersistenceStorage {
+
+ private static final String KEY = "engine/l2/bucket-cache-engine";
+
+ @TempDir
+ private java.nio.file.Path temporaryDirectory;
+
+ private FileSystem fileSystem;
+ private Path rootPath;
+ private HadoopFsCachePersistenceStorage storage;
+
+ /**
+ * Creates an isolated Hadoop local filesystem instance and persistence root for each test.
+ * @throws IOException if the local filesystem cannot be created
+ */
+ @BeforeEach
+ public void setUp() throws IOException {
+ Configuration conf = new Configuration(false);
+
+ fileSystem = FileSystem.newInstance(URI.create("file:///"), conf);
+ rootPath = new Path(temporaryDirectory.toUri());
+ storage = new HadoopFsCachePersistenceStorage(fileSystem, rootPath);
+ }
+
+ /**
+ * Closes the isolated local filesystem after each test.
+ * @throws IOException if the filesystem cannot be closed
+ */
+ @AfterEach
+ public void tearDown() throws IOException {
+ if (fileSystem != null) {
+ fileSystem.close();
+ }
+ }
+
+ /**
+ * Verifies that committed state can be opened and read.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testCommitPublishesState() throws IOException {
+ byte[] expected = "persistent-state".getBytes(StandardCharsets.UTF_8);
+
+ writeState(KEY, expected);
+
+ assertArrayEquals(expected, readState(KEY));
+ }
+
+ /**
+ * Verifies that committing a replacement makes the new state visible.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testCommitReplacesExistingState() throws IOException {
+ byte[] original = "original-state".getBytes(StandardCharsets.UTF_8);
+ byte[] replacement = "replacement-state".getBytes(StandardCharsets.UTF_8);
+
+ writeState(KEY, original);
+ writeState(KEY, replacement);
+
+ assertArrayEquals(replacement, readState(KEY));
+ }
+
+ /**
+ * Verifies that aborting a replacement leaves previously committed state unchanged.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testAbortPreservesExistingState() throws IOException {
+ byte[] original = "original-state".getBytes(StandardCharsets.UTF_8);
+ byte[] replacement = "incomplete-state".getBytes(StandardCharsets.UTF_8);
+
+ writeState(KEY, original);
+
+ try (CachePersistenceOutput output = storage.create(KEY)) {
+ output.getOutputStream().write(replacement);
+ output.abort();
+ }
+
+ assertArrayEquals(original, readState(KEY));
+ assertNoTemporaryFiles(KEY);
+ }
+
+ /**
+ * Verifies that closing an uncommitted output aborts the write automatically.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testCloseWithoutCommitAbortsWrite() throws IOException {
+ byte[] original = "original-state".getBytes(StandardCharsets.UTF_8);
+ byte[] replacement = "uncommitted-state".getBytes(StandardCharsets.UTF_8);
+
+ writeState(KEY, original);
+
+ try (CachePersistenceOutput output = storage.create(KEY)) {
+ output.getOutputStream().write(replacement);
+ }
+
+ assertArrayEquals(original, readState(KEY));
+ assertNoTemporaryFiles(KEY);
+ }
+
+ /**
+ * Verifies that closing an uncommitted first write leaves no committed or temporary state.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testAbortedInitialWriteLeavesNoState() throws IOException {
+ try (CachePersistenceOutput output = storage.create(KEY)) {
+ output.getOutputStream().write("incomplete".getBytes(StandardCharsets.UTF_8));
+ }
+ assertFalse(storage.open(KEY).isPresent());
+ assertNoPersistenceFiles(KEY);
+ }
+
+ /**
+ * Verifies that opening a key with no persisted state returns an empty optional.
+ * @throws IOException if storage access fails
+ */
+ @Test
+ public void testOpenMissingStateReturnsEmpty() throws IOException {
+ Optional<InputStream> input = storage.open("engine/l1/missing-engine");
+
+ assertFalse(input.isPresent());
+ }
+
+ /**
+ * Verifies that nested component keys cause their parent directories to be created.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testNestedStorageKeyCreatesParentDirectories() throws IOException {
+ String key = "engine/l2/test-engine";
+
+ writeState(key, "state".getBytes(StandardCharsets.UTF_8));
+
+ Path parent = new Path(rootPath, "engine/l2");
+ assertTrue(fileSystem.exists(parent));
+ assertTrue(fileSystem.getFileStatus(parent).isDirectory());
+ }
+
+ /**
+ * Verifies that invalid relative storage keys are rejected.
+ */
+ @Test
+ public void testInvalidStorageKeysAreRejected() {
+ assertThrows(IllegalArgumentException.class, () -> storage.open(""));
+ assertThrows(IllegalArgumentException.class, () -> storage.open("/absolute"));
+ assertThrows(IllegalArgumentException.class, () -> storage.open("../outside"));
+ assertThrows(IllegalArgumentException.class, () -> storage.open("engine//l2"));
+ assertThrows(IllegalArgumentException.class, () -> storage.open("engine\\l2"));
+ assertThrows(IllegalArgumentException.class, () -> storage.open("file://state"));
+ }
+
+ /**
+ * Verifies that commit leaves only the final state file and no temporary or backup files.
+ * @throws IOException if persistence fails
+ */
+ @Test
+ public void testSuccessfulCommitCleansTemporaryFiles() throws IOException {
+ writeState(KEY, "first".getBytes(StandardCharsets.UTF_8));
+ writeState(KEY, "second".getBytes(StandardCharsets.UTF_8));
+
+ Path parent = new Path(rootPath, "engine/l2");
+ FileStatus[] files = fileSystem.listStatus(parent);
+
+ assertEquals(1, files.length);
+ assertEquals("bucket-cache-engine.state", files[0].getPath().getName());
+ }
+
+ /**
+ * Verifies that a component save failure does not replace previously committed state.
+ * @throws IOException if persistence setup or verification fails
+ */
+ @Test
+ public void testFailedComponentSavePreservesPreviouslyCommittedState() throws IOException {
+ byte[] original = "original-state".getBytes(StandardCharsets.UTF_8);
+ writeState(KEY, original);
+
+ CacheTopology topology = mock(CacheTopology.class);
+ CachePlacementAdmissionPolicy policy = mock(CachePlacementAdmissionPolicy.class);
+ CacheEngine engine =
+ mock(CacheEngine.class, withSettings().extraInterfaces(PersistentCacheComponent.class));
+ PersistentCacheComponent persistent = (PersistentCacheComponent) engine;
+
+ when(persistent.getPersistenceId()).thenReturn("bucket-cache-engine");
+ when(topology.getTiers()).thenReturn(List.of(CacheTier.L2));
+ when(topology.getEngine(CacheTier.L2)).thenReturn(Optional.of(engine));
+
+ doAnswer(invocation -> {
+ OutputStream output = invocation.getArgument(0);
+ output.write("partial-state".getBytes(StandardCharsets.UTF_8));
+ throw new IOException("Expected save failure");
+ }).when(persistent).save(any(OutputStream.class));
+
+ CachePersistenceCoordinator coordinator = new CachePersistenceCoordinator(topology, policy);
+
+ assertThrows(IOException.class, () -> coordinator.save(storage));
+
+ assertArrayEquals(original, readState(KEY));
+ assertOnlyCommittedStateFile(KEY);
+ }
+
+ /**
+ * Verifies that previously committed state is recovered when publication is interrupted after the
+ * committed state is moved to its backup location.
+ * @throws IOException if persistence or recovery fails
+ */
+ @Test
+ public void testRecoversStateAfterInterruptedReplacement() throws IOException {
+ byte[] original = "original-state".getBytes(StandardCharsets.UTF_8);
+ writeState(KEY, original);
+
+ Path targetPath = new Path(rootPath, KEY + ".state");
+ Path backupPath = new Path(targetPath.toString() + ".backup");
+
+ assertTrue(fileSystem.rename(targetPath, backupPath));
+ assertFalse(fileSystem.exists(targetPath));
+ assertTrue(fileSystem.exists(backupPath));
+
+ assertArrayEquals(original, readState(KEY));
+
+ assertTrue(fileSystem.exists(targetPath));
+ assertFalse(fileSystem.exists(backupPath));
+ }
+
+ /**
+ * Verifies that failure to delete an obsolete backup after publication does not fail the commit.
+ * @throws IOException if persistence unexpectedly fails
+ */
+ @Test
+ public void testBackupDeleteFalseAfterCommitIsNonFatal() throws IOException {
+ FileSystem fileSystem = mock(FileSystem.class);
+ FSDataOutputStream outputStream = mock(FSDataOutputStream.class);
+ Path rootPath = new Path("/cache");
+ Path targetPath = new Path(rootPath, KEY + ".state");
+ Path backupPath = new Path(targetPath.toString() + ".backup");
+
+ configureSuccessfulReplacement(fileSystem, outputStream, rootPath, targetPath, backupPath);
+
+ when(fileSystem.delete(backupPath, false)).thenReturn(false);
+
+ HadoopFsCachePersistenceStorage testStorage =
+ new HadoopFsCachePersistenceStorage(fileSystem, rootPath);
+
+ try (CachePersistenceOutput output = testStorage.create(KEY)) {
+ assertDoesNotThrow(output::commit);
+ }
+
+ verify(fileSystem).delete(backupPath, false);
+ }
+
+ /**
+ * Verifies that an exception while deleting an obsolete backup after publication does not fail
+ * the commit.
+ * @throws IOException if persistence setup unexpectedly fails
+ */
+ @Test
+ public void testBackupDeleteExceptionAfterCommitIsNonFatal() throws IOException {
+ FileSystem fileSystem = mock(FileSystem.class);
+ FSDataOutputStream outputStream = mock(FSDataOutputStream.class);
+ Path rootPath = new Path("/cache");
+ Path targetPath = new Path(rootPath, KEY + ".state");
+ Path backupPath = new Path(targetPath.toString() + ".backup");
+
+ configureSuccessfulReplacement(fileSystem, outputStream, rootPath, targetPath, backupPath);
+
+ when(fileSystem.delete(backupPath, false))
+ .thenThrow(new IOException("Expected cleanup failure"));
+
+ HadoopFsCachePersistenceStorage testStorage =
+ new HadoopFsCachePersistenceStorage(fileSystem, rootPath);
+
+ try (CachePersistenceOutput output = testStorage.create(KEY)) {
+ assertDoesNotThrow(output::commit);
+ }
+
+ verify(fileSystem).delete(backupPath, false);
+ }
+
+ /**
+ * Creates persistence storage backed by a mocked filesystem and configures a replacement commit
+ * through the point where backup cleanup is attempted.
+ * @param fileSystem mocked filesystem
+ * @param output temporary persistence output stream
+ * @param rootPath persistence root path
+ * @param targetPath committed state path
+ * @param backupPath backup state path
+ * @throws IOException if mock setup fails
+ */
+ private void configureSuccessfulReplacement(FileSystem fileSystem, FSDataOutputStream output,
+ Path rootPath, Path targetPath, Path backupPath) throws IOException {
+ Path parent = targetPath.getParent();
+
+ when(fileSystem.exists(parent)).thenReturn(true);
+ when(fileSystem.exists(targetPath)).thenReturn(true);
+ when(fileSystem.exists(backupPath)).thenReturn(false, true);
+ when(fileSystem.create(any(Path.class), eq(false))).thenReturn(output);
+ when(fileSystem.rename(any(Path.class), any(Path.class))).thenReturn(true);
+ }
+
+ /**
+ * Writes and commits state for the specified persistence key.
+ * @param key persistence storage key
+ * @param data state to write
+ * @throws IOException if state cannot be written or committed
+ */
+ private void writeState(String key, byte[] data) throws IOException {
+ try (CachePersistenceOutput output = storage.create(key)) {
+ output.getOutputStream().write(data);
+ output.commit();
+ }
+ }
+
+ /**
+ * Reads all committed state associated with the specified persistence key.
+ * @param key persistence storage key
+ * @return persisted state bytes
+ * @throws IOException if persisted state does not exist or cannot be read
+ */
+ private byte[] readState(String key) throws IOException {
+ Optional<InputStream> input = storage.open(key);
+ assertTrue(input.isPresent(), "Expected persisted state for " + key);
+
+ try (InputStream stream = input.get()) {
+ return stream.readAllBytes();
+ }
+ }
+
+ /**
+ * Verifies that no temporary or backup persistence files remain next to the committed state.
+ * @param key persistence storage key
+ * @throws IOException if the persistence directory cannot be inspected
+ */
+ private void assertNoTemporaryFiles(String key) throws IOException {
+ int separator = key.lastIndexOf('/');
+ String parentKey = separator >= 0 ? key.substring(0, separator) : "";
+ String stateName = separator >= 0 ? key.substring(separator + 1) : key;
+
+ Path parent = parentKey.isEmpty() ? rootPath : new Path(rootPath, parentKey);
+ FileStatus[] files = fileSystem.listStatus(parent);
+
+ assertEquals(1, files.length);
+ assertEquals(stateName + ".state", files[0].getPath().getName());
+ }
+
+ /**
+ * Verifies that no persistence files remain for the specified storage key.
+ * @param key persistence storage key
+ * @throws IOException if the persistence directory cannot be inspected
+ */
+ private void assertNoPersistenceFiles(String key) throws IOException {
+ Path parent = getParentPath(key);
+ if (!fileSystem.exists(parent)) {
+ return;
+ }
+ FileStatus[] files = fileSystem.listStatus(parent);
+ assertEquals(0, files.length);
+ }
+
+ /**
+ * Returns the persistence directory containing the specified storage key.
+ * @param key persistence storage key
+ * @return parent persistence directory
+ */
+ private Path getParentPath(String key) {
+ int separator = key.lastIndexOf('/');
+ if (separator < 0) {
+ return rootPath;
+ }
+ return new Path(rootPath, key.substring(0, separator));
+ }
+
+ /**
+ * Verifies that only the committed state file remains for the specified storage key.
+ * @param key persistence storage key
+ * @throws IOException if the persistence directory cannot be inspected
+ */
+ private void assertOnlyCommittedStateFile(String key) throws IOException {
+ int separator = key.lastIndexOf('/');
+ String stateName = separator >= 0 ? key.substring(separator + 1) : key;
+ Path parent = getParentPath(key);
+
+ FileStatus[] files = fileSystem.listStatus(parent);
+
+ assertEquals(1, files.length);
+ assertEquals(stateName + ".state", files[0].getPath().getName());
+ }
+}