diff --git a/documentation/en/user/source/configuration/storage.rst b/documentation/en/user/source/configuration/storage.rst index f47ab11c2d..6310b00848 100644 --- a/documentation/en/user/source/configuration/storage.rst +++ b/documentation/en/user/source/configuration/storage.rst @@ -510,3 +510,228 @@ Additional Information: * The package makes use of the open source multi-cloud toolkit `jclouds `_ * Jclouds documentation for `getting started with Openstack `_ * Jclouds documentation for `OpenStack Keystone V3 Support `_ used in config + +In-memory tile cache +-------------------- + +The in-memory tile cache keeps the most requested tiles in memory, in front of the blob stores. It is meant for layers whose tiles +expire quickly and are requested by many clients at once, where reading each tile from disk or from a cloud store costs more than +rendering time saved. In particular, it allows to share the tiles among all the nodes of a cluster, so that a tile rendered by one +node is served by every other node until it expires. + +The cache is configured once in :file:`geowebcache.xml`, with the ``memoryCache`` element after ``blobStores``, or through the +:ref:`REST API `, and used by the layers that set ``memoryCached`` to ``true``. For example: + +.. code-block:: xml + + + true + 300 + true + 300 + + 64 + + + +* **enabled**: whether the cache is used, defaults to ``false``. +* **timeToLive**: seconds a tile stays in the cache when its layer sets no ``expireCache``, defaults to 300. A layer ``expireCache`` + applies instead, whether shorter or longer. A tile read from the blob store with passthrough on is kept for what is left of + the layer ``expireCache``, and at most ``timeToLive``, so that a read racing a truncate cannot bring back a removed tile for + longer than that. +* **passthrough**: whether tiles are also written to, and read from, the blob store. Defaults to ``true``. When ``false``, tiles live in + the cache only, and an expired or evicted tile is rendered again. Truncating a tile, an area or a gridset then leaves the blob store + alone, so tiles it still holds from before are kept: truncate the whole layer before turning ``passthrough`` back on. +* **statsInterval**: seconds between two statistics lines per layer in the log, defaults to 300. ``0`` turns them off. +* **backend**: where the tiles are kept, named by the ``class`` attribute. Defaults to ``heapKeyValueStore``. When the module of the backend + is removed, GeoWebCache still starts: the cache is unusable, with the reason in the log, truncates run on the blob store only, and the + backend settings are kept as they are, so that installing the module again restores them. + +Each layer opts in with ``memoryCached``, off by default, placed before the layer ``name``: + +.. code-block:: xml + + + true + topp:states + ... + + +**Nodes sharing one** :file:`geowebcache.xml` **read the** ``memoryCache`` **settings when they start or reload**: after changing them, +reload or restart every other node. It is to be noted that until then, another node saving its configuration (a blob store or a +gridset change) writes its old ``memoryCache`` settings back over the change. + +Layer metadata and parameter mappings always stay in the blob store. The cache only holds tiles. + +When the backend cannot be reached, tiles are served without the cache, and the log reports when the cache goes down and when +it comes back. A tile request never fails because of the cache. While the cache is down, tile requests do not wait for it: each node +tries it again from time to time, from every second at the start of the outage up to every 30 seconds for long ones. A cache that keeps +going down and up again is reported once with its error, then with a short "unreachable again" line each time. + +A truncate of a layer using the cache removes its tiles from both the cache and the blob store. **While the cache is down, or when it +fails to remove the tiles, the truncate is not run at all**, blob store included, and reports an error: retry it once the cache is back, +since the tiles cached before the outage are served again when it recovers. Deletes of single tiles or bounding boxes, as disk quota +runs, are the exception with passthrough on: they still delete from the blob store, so that disk quota frees space during a long outage, +and the copies cached before it are served until they expire. The log reports it once per outage. If the cache fails only after the blob store was truncated, an error is reported and cached tiles may stay stale up to +their time to live. Removing a layer always deletes its tiles from the blob store, even with the cache down; its cached tiles then expire +with their time to live. Layers not using the cache are truncated in the blob store as usual, whatever the state of the cache. + +Heap backend +++++++++++++ + +The ``heapKeyValueStore`` backend keeps tiles in the memory of each node, **not shared** with other nodes. ``maxSizeMB`` (defaults to 64) +bounds the memory used, the least used tiles are dropped first. + +Hazelcast backends +++++++++++++++++++ + +The Hazelcast backends keep tiles in a `Hazelcast `_ map, shared by all the nodes. There are two of them: + +* ``hazelcastClientKeyValueStore`` connects to a separate Hazelcast cluster, which holds the tiles. Nodes stay small and stateless, and the + cluster is sized and restarted on its own. +* ``hazelcastEmbeddedKeyValueStore`` makes each node a member of the cluster, holding a share of the tiles in its own memory. There is no + separate service to run, at the cost of a larger memory footprint per node. + +**Hazelcast open source has no authentication nor encryption**. The cluster must only be reachable from the GeoWebCache nodes, for example +on a private network or with network policies, as anyone reaching it can read and change the tiles. + +Client backend +~~~~~~~~~~~~~~ + +.. code-block:: xml + + + dev + hazelcast-1:5701, hazelcast-2:5701 + gwc-tiles + + +* **clusterName**: the name of the cluster, defaults to ``gwc``. +* **members**: comma separated ``host:port`` list of cluster members to connect to, defaults to ``localhost:5701``. One reachable member + is enough, the client then finds the others. +* **mapName**: the map holding the tiles, defaults to ``gwc-tiles``. It must be declared on the cluster, see below. + +**clusterName and members apply on restart only**: the client connects once, the first time the cache is used, and keeps that +connection until GeoWebCache stops. Saving new values, or reloading the configuration, does not change it. ``mapName`` applies on save. + +GeoWebCache starts even when the cluster is down. Tiles are then served without the cache, and the client keeps trying to connect in the +background, waiting up to 30 seconds between attempts. Reading or writing a tile gives up after 2 seconds, and the cache is then treated +as down; each cluster call of a truncate gives up after 10 seconds, and the truncate then reports an error. The limits can be changed with +the ``GWC_MEMORYCACHE_CALL_TIMEOUT`` and ``GWC_MEMORYCACHE_BULK_TIMEOUT`` system properties, servlet context parameters or environment +variables, in milliseconds. Copying a tile read from the blob store into the cache, with passthrough on, follows the tile limit too, and +is skipped while too many copies are still waiting on a member that stopped answering. The cluster-wide locks have no such limit: they +wait until the connection is declared dead, 60 seconds by default. + +For settings not covered above, such as discovery or timeouts, a :file:`hazelcast-client.xml` file can be placed in the same directory as +:file:`geowebcache.xml`. When present, it **replaces** ``clusterName``, ``members`` and the connection defaults, following the +`Hazelcast client configuration `_. It is to be noted that +the client always starts in the background and retries forever, whatever the file says, so that an unreachable cluster never stops +GeoWebCache: a finite ``cluster-connect-timeout-millis`` is ignored, with a warning in the log. ``mapName`` is still taken from +:file:`geowebcache.xml`. The file also keeps the 5 seconds request timeout and the retry ``multiplier`` (2) and ``jitter`` (0.2) of +the cache, unless it sets ``hazelcast.client.invocation.timeout.seconds``, ``multiplier`` or ``jitter`` itself. Changes to the file +apply on restart only. + +Embedded backend +~~~~~~~~~~~~~~~~ + +.. code-block:: xml + + + gwc-tiles + + +* **mapName**: the map holding the tiles, defaults to ``gwc-tiles``. + +The member is configured by a :file:`hazelcast.xml` file, **mandatory**, in the same directory as :file:`geowebcache.xml`, following the +`Hazelcast member configuration `_. Changes to the file +apply on restart. + +It is to be noted that the member joins the cluster in the background when the cache is first used. Tile requests do not wait for it, they +are served without the cache until the member has joined, and the log reports the cache unreachable then reachable again. A missing +file, or a file not declaring the map, leaves the cache unusable, with the reason in the log, while tiles keep being served without it. +A member that fails to start, or stops later, for example after running out of memory or through a cluster shutdown, is started again +when the cache is next tried, at most every 30 seconds. + +The following example fits a Kubernetes deployment, where members find each other through a service. The pods need permission to read +endpoints and pods in their namespace: + +.. code-block:: xml + + + gwc + + + + + gwc + gwc-hazelcast + + + + + 1 + + + + +Declaring the map +~~~~~~~~~~~~~~~~~ + +With both backends, the map must be declared in the cluster configuration with an eviction policy and a size bound. **A map without +them grows until the members run out of memory**, as Hazelcast keeps every entry by default. The embedded backend refuses to start on an +undeclared map. The client backend cannot check it, so the cluster configuration must be reviewed by hand. + +The time to live does not need to be declared, as each tile is stored with its own. + +``backup-count`` sets how many other members keep a copy of each tile. With ``1``, losing a member loses no tiles, at the cost of twice +the memory. With ``0``, tiles of a lost member are rendered again. + +The first truncate adds a sorted index on the map keys, so that removing the tiles of a layer, gridset or parameter set looks up the +matching keys instead of reading every tile on the members. The index costs some memory per tile on the members and a little time on +every write, so size the members for it: an entry count limit does not account for it. To keep the cluster configuration under your +control, declare it with the map instead: + +.. code-block:: xml + + + + + + __key + + + + + +An index added by GeoWebCache is lost when the whole cluster restarts, and added again by the next truncate. If it cannot be added, for +example when the cluster configuration refuses it, truncates still run without it, reading every tile on the members, with a warning in +the log, and the next truncate tries again. + +Truncating a bounding box reads the keys of each affected zoom level, for one parameter set and format, into the memory of the node doing +it, and removes the tiles inside the box. **Above 100,000 tiles in a zoom level it removes the whole zoom level instead**, with a line in +the log, so that the node memory stays bounded: the extra tiles are rendered again when requested. The limit can be changed with the +``GWC_MEMORYCACHE_MATCHING_LIMIT`` system property, servlet context parameter or environment variable, ``0`` always removing the whole +zoom level; it applies when the cache settings are next saved or on restart. + +Cluster-wide tile locks +~~~~~~~~~~~~~~~~~~~~~~~ + +When a tile is missing, a node renders its whole metatile, and other requests for the same metatile on that node wait for it. Separate +nodes do not: when several of them miss the same metatile at once, for example right after its tiles expired, each of them renders it. +With a Hazelcast backend, the nodes can lock on the cluster instead, so that one node renders the metatile and the others wait, then serve +its tiles from the shared cache. Name ``hazelcastLock`` as the lock provider in :file:`geowebcache.xml`, after ``backendTimeout``: + +.. code-block:: xml + + 120 + hazelcastLock + +* **It needs the cache enabled with a Hazelcast backend**, as the locks are kept on the same cluster, in a map named after the tile map + with a ``.locks`` suffix, ``gwc-tiles.locks`` by default, which needs no declaration. Otherwise each node locks on its own, with a + warning in the log. Switching the cache to another backend takes the nodes back to their own locks as soon as the settings are saved. +* A node never fails a request because of these locks. When the cluster cannot be reached, or while the cache considers it down after a + failed call, nodes lock on their own at once until it is back, and a metatile may then be rendered once per node. A node waits for a lock at most the number of seconds set by the ``GWC_LOCK_TIMEOUT`` + system property, 120 by default, then goes on anyway with a warning in the log. A node stopping while it holds a lock keeps it at most + that long. +* It is to be noted that the blob stores use the same lock provider. **The S3 blob store holds a lock for the whole of a bulk delete**, + often longer than ``GWC_LOCK_TIMEOUT``, so the lock can expire under it and another node can start the same delete meanwhile. diff --git a/documentation/en/user/source/rest/index.rst b/documentation/en/user/source/rest/index.rst index 778032c80e..554a8f23ae 100644 --- a/documentation/en/user/source/rest/index.rst +++ b/documentation/en/user/source/rest/index.rst @@ -15,6 +15,7 @@ This section will discuss the GeoWebCache REST API. seed.rst diskquota.rst masstruncate.rst + memorycache.rst diff --git a/documentation/en/user/source/rest/memorycache.rst b/documentation/en/user/source/rest/memorycache.rst new file mode 100644 index 0000000000..b41edc4b1b --- /dev/null +++ b/documentation/en/user/source/rest/memorycache.rst @@ -0,0 +1,83 @@ +.. _rest.memorycache: + +Managing the In-memory Tile Cache through the REST API +====================================================== + +The REST API for the in-memory tile cache allows to view and replace its settings, the ``memoryCache`` element of +:file:`geowebcache.xml` described in :ref:`configuration.storage`. + +Operations +---------- + +``/rest/memorycache`` + +.. list-table:: + :header-rows: 1 + + * - Method + - Action + - Return Code + - Formats + * - GET + - Return the saved settings + - 200 + - XML, JSON + * - POST + - + - 405 + - + * - PUT + - Replace the settings + - 200, 400 + - XML, JSON + * - DELETE + - + - 405 + - + +GET returns the settings as saved: a value missing from the response takes its default. + +PUT replaces all the settings, **a value left out goes back to its default**, it does not keep its current value. Changing the +settings empties the cache, while sending the same settings again leaves it as it is. Settings the cache could not start with, +a ``timeToLive`` below 1 or a ``backend`` class that is not installed, are rejected with a 400 and not saved. + +The ``backend`` element takes the same ``class`` and settings as in :file:`geowebcache.xml`, for example ``hazelcastClientKeyValueStore`` +for the Hazelcast client backend when that module is installed. Saving does not connect to the backend: it is reached the next time the +cache is used, and an unreachable one is then reported in the log. + +As for any other change of :file:`geowebcache.xml`, other nodes sharing the file only see the new settings after a reload or a restart. + +cURL Examples +------------- + +Get the settings: + +.. code-block:: bash + + curl -u geowebcache:secured "http://localhost:8080/geowebcache/rest/memorycache.xml" + +Or if using the GeoServer integrated version of GeoWebCache: + +.. code-block:: bash + + curl -u user:password "http://localhost:8080/geoserver/gwc/rest/memorycache.xml" + +Given a :file:`memorycache.xml` file as the following: + +.. code-block:: xml + + + true + 120 + + 256 + + + +replace the settings with: + +.. code-block:: bash + + curl -u geowebcache:secured -XPUT -H "Content-type: text/xml" -d @memorycache.xml "http://localhost:8080/geowebcache/rest/memorycache.xml" + +This turns the cache on, with tiles kept 120 seconds in up to 256 MB of heap, and ``passthrough`` and ``statsInterval`` back to their defaults. diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java index 530fbafd6b..c935b12ef4 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java @@ -372,7 +372,8 @@ private String getMimeType(TileObject obj) { return mimeType; } - private void putParametersMetadata(String layerName, String parametersId, Map parameters) { + @Override + public void putParametersMetadata(String layerName, String parametersId, Map parameters) { assert (isNull(parametersId) == isNull(parameters)); if (isNull(parametersId)) { return; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java index ff7487b528..65c1125d25 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java @@ -21,6 +21,7 @@ import org.geowebcache.locks.LockProvider; import org.geowebcache.locks.MemoryLockProvider; import org.geowebcache.mime.FormatModifier; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; /** * POJO for geowebcache.xml configuration @@ -70,6 +71,9 @@ public class GeoWebCacheConfiguration { private List blobStores; + // volatile, as tile requests read it while a save replaces it; the instance is never changed once set + private volatile MemoryCacheInfo memoryCache; + private List gridSets; private Boolean fullWMS; @@ -226,6 +230,16 @@ public List getBlobStores() { return blobStores; } + /** The {@code } settings, null when the element is absent. */ + public MemoryCacheInfo getMemoryCache() { + return memoryCache; + } + + /** Replaces the {@code } settings, null removes the element. */ + public void setMemoryCache(MemoryCacheInfo memoryCache) { + this.memoryCache = memoryCache; + } + /** @return the gridSets */ public List getGridSets() { return gridSets; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java index e9ae405436..f73ffb941d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java @@ -16,6 +16,7 @@ import java.io.IOException; import org.geowebcache.config.meta.ServiceInformation; import org.geowebcache.locks.LockProvider; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; /** * Interface for managing global server configuration information. @@ -55,6 +56,11 @@ public interface ServerConfiguration extends BaseConfiguration { /** Set the lock provider for this configuration. */ void setLockProvider(LockProvider lockProvider) throws IOException; + /** The tile cache settings, or null when this configuration does not hold them. */ + default MemoryCacheInfo getMemoryCache() { + return null; + } + /** * Used for getting the "fullWMS" parameter from GeoWebCacheConfigration if present * diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java index 381b789808..abfa812bce 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java @@ -87,6 +87,9 @@ import org.geowebcache.seed.TruncateLayerRequest; import org.geowebcache.storage.DefaultStorageFinder; import org.geowebcache.storage.UnsuitableStorageException; +import org.geowebcache.storage.memorycache.HeapKeyValueStoreInfo; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; +import org.geowebcache.storage.memorycache.UnresolvedKeyValueStoreInfo; import org.geowebcache.util.ApplicationContextProvider; import org.geowebcache.util.ExceptionUtils; import org.geowebcache.util.URLs; @@ -374,6 +377,9 @@ public static XStream getConfiguredXStreamWithContext( xs.alias("blobStores", new ArrayList().getClass()); xs.alias("FileBlobStore", FileBlobStoreInfo.class); + xs.alias("heapKeyValueStore", HeapKeyValueStoreInfo.class); + // a removed backend module must not fail the whole configuration + UnresolvedKeyValueStoreInfo.register(xs); xs.aliasAttribute(BlobStoreInfo.class, "_default", "default"); // Alias added to retain XML backwards-compatibility. // TODO: Would be nice to be able to use name for consistency @@ -1246,6 +1252,17 @@ public void setLockProvider(LockProvider lockProvider) throws IOException { save(); } + @Override + public MemoryCacheInfo getMemoryCache() { + return getGwcConfig().getMemoryCache(); + } + + /** Saves the tile cache settings; pass a new instance, the cache is rebuilt only when the instance changes. */ + public void setMemoryCache(MemoryCacheInfo memoryCache) throws IOException { + getGwcConfig().setMemoryCache(memoryCache); + save(); + } + private GeoWebCacheConfiguration getGwcConfig() { try { if (gwcConfig == null) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java index 6cdaf7ffdf..3e8fc9b7de 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java @@ -51,6 +51,8 @@ public abstract class AbstractTileLayer extends TileLayer { @Nullable protected String blobStoreId; + protected Boolean memoryCached; + protected Boolean enabled; protected Boolean advertised; @@ -159,6 +161,16 @@ public void setBlobStoreId(@Nullable String blobStoreId) { this.blobStoreId = blobStoreId; } + @Override + public boolean isMemoryCached() { + return Boolean.TRUE.equals(memoryCached); + } + + /** Sets whether the tiles of this layer go through the in-memory tile cache. */ + public void setMemoryCached(boolean memoryCached) { + this.memoryCached = memoryCached; + } + /** Then name of the layer */ @Override public String getName() { diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java index 786ce3dda9..7963a69fbf 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java @@ -94,6 +94,11 @@ public abstract class TileLayer implements Info { public abstract void setBlobStoreId(@Nullable String blobStoreId); + /** Whether the tiles of this layer go through the in-memory tile cache, when one is configured. */ + public boolean isMemoryCached() { + return false; + } + /** Then name of the layer */ @Override public abstract String getName(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java index 1f469aea7d..fb1350d5b0 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java @@ -163,6 +163,15 @@ public default Set getParameterIds(String layerName) throws StorageExcep */ Map>> getParametersMapping(String layerName); + /** + * Records the parameter combination used by a tile, so that {@link #getParametersMapping} lists it. Called from + * {@link #put(TileObject)}, and by a cache whose tiles do not reach this store. + */ + default void putParametersMetadata(String layerName, String parametersId, Map parameters) + throws StorageException { + // stores that do not track parameter mappings ignore this + } + /** If the given layer is cached, remove */ public default boolean purgeOrphans(TileLayer layer) throws StorageException { // TODO maybe do purging based on gridset and format diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java index c3dfa365cc..9ed5ae21bb 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java @@ -18,6 +18,7 @@ import com.google.common.base.Strings; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -39,6 +40,8 @@ import org.geowebcache.layer.TileLayerDispatcher; import org.geowebcache.locks.LockProvider; import org.geowebcache.storage.blobstore.file.FileBlobStore; +import org.geowebcache.storage.memorycache.MemoryCache; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; /** * A composite {@link BlobStore} that multiplexes tile operations to configured blobstores based on @@ -78,6 +81,10 @@ public class CompositeBlobStore implements BlobStore, BlobStoreConfigurationList private final BlobStoreListenerList listeners = new BlobStoreListenerList(); + private final ServerConfiguration serverConfiguration; + + private volatile MemoryCache memoryCache; + @VisibleForTesting static final class LiveStore { BlobStoreInfo config; @@ -137,6 +144,7 @@ public CompositeBlobStore( this.layers = layers; this.defaultStorageFinder = defaultStorageFinder; this.lockProvider = serverConfiguration.getLockProvider(); + this.serverConfiguration = serverConfiguration; this.blobStoreConfigs = blobStoreAggregator; StoreSuitabilityCheck oldCheck = storeSuitability.get(); // Disable suitability checks when loading during startup. @@ -188,6 +196,7 @@ public void clear() throws StorageException { @Override public synchronized void destroy() { destroy(blobStores); + if (memoryCache != null) memoryCache.close(); } private void destroy(Map blobStores) { @@ -235,15 +244,19 @@ public boolean removeListener(BlobStoreListener listener) { @Override public boolean rename(String oldLayerName, String newLayerName) throws StorageException { return readFunctionUnsafe(() -> { + boolean renamed = false; for (LiveStore bs : blobStores.values()) { BlobStoreInfo config = bs.config; if (config.isEnabled()) { if (bs.liveInstance.rename(oldLayerName, newLayerName)) { - return true; + renamed = true; + break; } } } - return false; + // even when no store had tiles, as with passthrough off they are all in the cache + memoryCache().layerRenamed(oldLayerName, newLayerName); + return renamed; }); } @@ -267,9 +280,11 @@ public boolean layerExists(String layerName) { private BlobStore store(String layerId) throws StorageException { + TileLayer layer; LiveStore store; try { - store = forLayer(layerId); + layer = layers.getTileLayer(layerId); + store = forLayer(layer); } catch (GeoWebCacheException e) { throw new StorageException(e.getMessage(), e); } @@ -277,20 +292,27 @@ private BlobStore store(String layerId) throws StorageException { throw new StorageException("Attempted to use a blob store that's disabled: " + store.config.getName()); } - return store.liveInstance; + return memoryCache().wrap(layer, store.liveInstance); + } + + /** The cache for the current settings, rebuilt when they change, closing the previous one. */ + private MemoryCache memoryCache() { + // a reload replaces the settings with equal ones, which must keep the cached tiles and the connection; + // Objects.equals checks identity first, so the per-request check stays cheap + MemoryCacheInfo info = serverConfiguration.getMemoryCache(); + MemoryCache cache = memoryCache; + if (cache != null && Objects.equals(cache.getInfo(), info)) return cache; + synchronized (this) { + MemoryCache previous = memoryCache; + if (previous != null && Objects.equals(previous.getInfo(), info)) return previous; + memoryCache = new MemoryCache(info, layers); + if (previous != null) previous.close(); + return memoryCache; + } } - /** - * @throws StorageException if the blobstore is not enabled or does not exist - * @throws GeoWebCacheException if the layer is not found - */ - private LiveStore forLayer(String layerName) throws StorageException, GeoWebCacheException { - TileLayer layer; - try { - layer = layers.getTileLayer(layerName); - } catch (GeoWebCacheException e) { - throw e; - } + /** @throws StorageException if the blobstore is not enabled or does not exist */ + private LiveStore forLayer(TileLayer layer) throws StorageException { String storeId = layer.getBlobStoreId(); LiveStore store; if (null == storeId) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java index 3eb201cd78..94ca16d167 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java @@ -489,13 +489,16 @@ public void put(TileObject stObj) throws StorageException { } } - private void putParametersMetadata(String layerName, String parametersId, Map parameters) + @Override + public void putParametersMetadata(String layerName, String parametersId, Map parameters) throws StorageException { // check if we even need to use any IO if (parametersId == null || parameters == null || parameters.isEmpty()) return; File parametersFile = parametersFile(layerName, parametersId); if (parametersFile.exists()) return; + // a tile put creates the layer directory, a tile cache with passthrough off never does + parametersFile.getParentFile().mkdirs(); writeFile(parametersFile, false, file -> { Properties properties = new Properties(); @@ -820,10 +823,9 @@ private static Map propertiesToMap(Properties properties) { @Override public Set getParameterIds(String layerName) { - try (Stream layerChildStream = layerChildStream(layerName, (p) -> Files.isDirectory(p))) { + try (Stream layerChildStream = layerChildStream(layerName, p -> true)) { return layerChildStream - .map(p -> p.getFileName().toString()) - .map(s -> s.substring(s.lastIndexOf('_') + 1)) + .map(FileBlobStore::parameterId) .filter(s -> s.length() == paramIdLength) // Zoom level should never be the same // length so this should be safe .collect(Collectors.toSet()); @@ -831,4 +833,16 @@ public Set getParameterIds(String layerName) { throw new UncheckedIOException(e); } } + + /** The id ending a tile directory name, or held in a mapping file name; empty for any other file. */ + private static String parameterId(Path child) { + String name = child.getFileName().toString(); + if (Files.isDirectory(child)) return name.substring(name.lastIndexOf('_') + 1); + // mapping files exist without tile directories when a tile cache keeps the tiles + if (!name.startsWith(PARAMETERS_METADATA_OBJECT_PREFIX) || !name.endsWith(PARAMETERS_METADATA_OBJECT_SUFFIX)) { + return ""; + } + return name.substring( + PARAMETERS_METADATA_OBJECT_PREFIX.length(), name.length() - PARAMETERS_METADATA_OBJECT_SUFFIX.length()); + } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java new file mode 100644 index 0000000000..11c33e3d59 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java @@ -0,0 +1,512 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.ERROR; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.EXPIRED; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.HIT; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.MISS; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.STORE; + +import com.google.common.util.concurrent.Striped; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.function.Consumer; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.IntStream; +import javax.annotation.Nullable; +import org.geotools.util.logging.Logging; +import org.geowebcache.io.ByteArrayResource; +import org.geowebcache.io.Resource; +import org.geowebcache.layer.TileLayer; +import org.geowebcache.storage.BlobStore; +import org.geowebcache.storage.BlobStoreListener; +import org.geowebcache.storage.StorageException; +import org.geowebcache.storage.TileObject; +import org.geowebcache.storage.TileRange; +import org.geowebcache.storage.memorycache.MemoryCacheStats.LayerStats; +import org.geowebcache.storage.memorycache.MemoryCacheStats.Result; +import org.geowebcache.util.TMSKeyBuilder; + +/** + * Puts a {@link MemoryCache} in front of the layer blob store, which still keeps the layer metadata and parameter + * mappings. + * + *

Cache failures never fail a tile request: a failed read is a miss, a failed write is dropped. A truncate of a + * memory cached layer fails before the store while the cache is down or refuses the removal; a layer removal deletes + * the store anyway, then throws. + */ +class CachingBlobStore implements BlobStore { + + private static final Logger LOGGER = Logging.getLogger(CachingBlobStore.class.getName()); + + // value layout: format version, creation time in epoch millis, tile bytes + private static final byte FORMAT_VERSION = 1; + + private static final int HEADER_SIZE = Byte.BYTES + Long.BYTES; + + /** Returned by {@link #cacheGet} when the cache failed, told apart from a miss by identity. */ + private static final byte[] FAILED = {}; + + /** + * Locks of the parameter mapping writes, by layer id and parameters id; static, so that a cache rebuilt by a + * settings save and the one it replaces do not write the same mapping at once. + */ + private static final Striped MAPPING_LOCKS = Striped.lazyWeakLock(256); + + private final BlobStore delegate; + + private final MemoryCache cache; + + private final TMSKeyBuilder keys; + + private final TileLayer layer; + + /** Whether the layer's tiles go through the cache, false when only its bulk truncates do. */ + private final boolean cached; + + /** Null when not {@link #cached}. */ + private final LayerStats stats; + + /** Every tile operation must target {@code layer}. */ + CachingBlobStore(BlobStore delegate, MemoryCache cache, TileLayer layer, boolean cached) { + this.delegate = delegate; + this.cache = cache; + this.keys = cache.getKeys(); + this.layer = layer; + this.cached = cached; + this.stats = cached ? cache.getStats().forLayer(layer.getName()) : null; + } + + /** True when the store behind holds the tiles: passthrough on, or a layer not using the cache. */ + private boolean storeHoldsTiles() { + return cache.isPassthrough() || !cached; + } + + @Override + public boolean get(TileObject obj) throws StorageException { + if (!cached) return delegate.get(obj); + long start = System.nanoTime(); + String key = keys.forTile(obj, layer.getId()); + Result result = decode(obj, cacheGet(key)); + boolean found = result == HIT || result == EXPIRED; + if (!found && cache.isPassthrough() && delegate.get(obj)) { + // never over a newer tile a concurrent put cached meanwhile + cachePut(key, obj, obj.getCreated(), true); + found = true; + // a failed cache read stays an error even when the store had the tile + if (result == MISS) result = STORE; + } + stats.read(result); + logRead(obj, result, start); + cache.getStats().report(); + return found; + } + + /** Fills {@code obj} from a cache value, which is null on a miss and {@link #FAILED} when the read failed. */ + private Result decode(TileObject obj, byte[] value) { + if (value == FAILED) return ERROR; + if (value == null || value.length < HEADER_SIZE || value[0] != FORMAT_VERSION) return MISS; + long created = ByteBuffer.wrap(value, 1, Long.BYTES).getLong(); + obj.setCreated(created); + int length = value.length - HEADER_SIZE; + // the offset constructor rejects an empty tile + obj.setBlob( + length > 0 ? new ByteArrayResource(value, HEADER_SIZE, length) : new ByteArrayResource(new byte[0])); + // the time to live already ends there, unless the writing node's clock is behind this one + int expireCache = expireCache(obj); + return expireCache > 0 && System.currentTimeMillis() - created > expireCache * 1000L ? EXPIRED : HIT; + } + + private static void logRead(TileObject obj, Result result, long start) { + long[] xyz = obj.getXYZ(); + LOGGER.fine(() -> String.format( + Locale.ROOT, + "In-memory tile cache %s for layer %s, gridset %s, z/x/y %d/%d/%d in %.2f ms", + result.name().toLowerCase(Locale.ROOT), + obj.getLayerName(), + obj.getGridSetId(), + xyz[2], + xyz[0], + xyz[1], + (System.nanoTime() - start) / 1_000_000.0)); + } + + @Override + public void put(TileObject obj) throws StorageException { + if (!cached) { + delegate.put(obj); + return; + } + // first, as building the key also sets the parameters id the mapping write needs + String key = keys.forTile(obj, layer.getId()); + if (cache.isPassthrough()) { + delegate.put(obj); + } else { + putParametersMetadataOnce(obj, key); + } + cachePut(key, obj, System.currentTimeMillis(), false); + cache.getStats().report(); + } + + /** + * Writes the mapping the store behind would record on put, unless the cache holds a marker saying it is there. + * Never throws: a failed write is retried by the next put of the parameter set. + */ + private void putParametersMetadataOnce(TileObject obj, String tileKey) { + String parametersId = obj.getParametersId(); + if (parametersId == null) return; + // shared by every node: a truncate removing the mapping from the store removes the marker with the tiles + String marker = markerKey(tileKey, parametersId); + byte[] storeId = String.valueOf(layer.getBlobStoreId()).getBytes(UTF_8); + Lock lock = MAPPING_LOCKS.get(layer.getId() + "/" + parametersId); + // one check at a time: the tiles of a metatile are saved in parallel, and concurrent writers of one file make + // it briefly disappear on Windows, where a rename deletes the target first; the marker is written before the + // lock is released, so the threads waiting on it find the marker and return + lock.lock(); + try { + byte[] written = cacheGet(marker); + // with the cache down the tile is not cached either, so it needs no mapping + if (written == FAILED || Arrays.equals(written, storeId)) return; + delegate.putParametersMetadata(obj.getLayerName(), parametersId, obj.getParameters()); + cacheWrite(marker, storeId, cache.getTtlSeconds(), false); + if (cache.getMappingWritesFailing().compareAndSet(true, false)) { + LOGGER.severe("In-memory tile cache records parameter mappings in the blob stores again"); + } + } catch (StorageException | RuntimeException e) { + // the tile is cached anyway: failing the put would render every request while the store is down + if (cache.getMappingWritesFailing().compareAndSet(false, true)) { + // SEVERE as the outage lines, production logging keeps org.geowebcache at error + String message = "In-memory tile cache could not record parameters " + parametersId + " of layer " + + obj.getLayerName() + " in its blob store, retrying on the next tiles: until then truncates" + + " by parameters or bounding box miss the tiles cached meanwhile"; + LOGGER.log(Level.SEVERE, message, e); + } + } finally { + lock.unlock(); + } + } + + /** + * The marker of a parameter set mapping, {@code ////mapping}: under the + * prefixes of layer, gridset and parameters truncates, outside those of the zoom levels a bounding box truncate + * removes. + */ + private static String markerKey(String tileKey, String parametersId) { + String segment = "/" + parametersId + "/"; + return tileKey.substring(0, tileKey.indexOf(segment) + segment.length()) + "mapping"; + } + + private byte[] cacheGet(String key) { + try { + return cache.getStore().get(key); + } catch (RuntimeException e) { + // logged by the guarded store, once per outage + return FAILED; + } + } + + /** + * Caches the tile. A read through from the store is capped at the global time to live: read before a concurrent + * truncate, it can land after it, and must not be served for the layer's whole expire server cache. + */ + private void cachePut(String key, TileObject obj, long created, boolean readThrough) { + long ttl = ttlSeconds(obj, created); + if (readThrough) ttl = Math.min(ttl, cache.getTtlSeconds()); + // a tile read through from the store can be already past the layer's expire server cache + if (ttl <= 0) return; + byte[] value; + try { + value = encode(obj.getBlob(), created); + } catch (IOException e) { + // a lazy store resource whose file a truncate removed after the read + LOGGER.log(Level.FINE, "Could not read tile " + key + " to cache it", e); + stats.failedPut(); + return; + } + if (!cacheWrite(key, value, ttl, readThrough)) stats.failedPut(); + } + + /** Writes a value, unless present when {@code ifAbsent}, returning false when the cache failed. */ + private boolean cacheWrite(String key, byte[] value, long ttl, boolean ifAbsent) { + try { + if (ifAbsent) cache.getStore().putIfAbsent(key, value, ttl); + else cache.getStore().put(key, value, ttl); + return true; + } catch (RuntimeException e) { + return false; + } + } + + // reads the stream rather than trusting the declared size, which a lazy resource computes apart from its content + private static byte[] encode(Resource blob, long created) throws IOException { + try (InputStream in = blob.getInputStream()) { + byte[] tile = in.readAllBytes(); + return ByteBuffer.allocate(HEADER_SIZE + tile.length) + .put(FORMAT_VERSION) + .putLong(created) + .put(tile) + .array(); + } + } + + /** + * What is left of the layer's expire server cache since {@code created}, or the global time to live when the layer + * sets none. Zero or negative when nothing is left. + */ + private long ttlSeconds(TileObject obj, long created) { + int expireCache = expireCache(obj); + if (expireCache <= 0) return cache.getTtlSeconds(); + // not capped by the global time to live: a tile evicted before its expiry would only be rendered again + return expireCache - MILLISECONDS.toSeconds(System.currentTimeMillis() - created); + } + + /** The layer's expire server cache in seconds at the tile's zoom level, positive only when the layer sets one. */ + private int expireCache(TileObject obj) { + // zero and negative values are "unset", "never expire" or "use the backend value" + return layer.getExpireCache((int) obj.getXYZ()[2]); + } + + @Override + public boolean delete(String layerName) throws StorageException { + String prefix = keys.forLayer(layerName); + Consumer removeFromCache = store -> store.removeByPrefix(prefix); + StoreTruncate deleteStore = () -> delegate.delete(layerName); + if (!truncateNeedsCache()) return truncate(removeFromCache, deleteStore); + // only a layer removal deletes a whole layer, truncates go gridset by gridset: the layer is gone and nobody can + // retry, so its store is deleted whatever the cache, whose leftovers expire with their time to live + cacheRemovalFailure(removeFromCache); + return truncateStoreThenCache(removeFromCache, deleteStore); + } + + @Override + public boolean deleteByGridsetId(String layerName, String gridSetId) throws StorageException { + String prefix = keys.forGridset(layerName, gridSetId); + return truncateTiles( + store -> store.removeByPrefix(prefix), () -> delegate.deleteByGridsetId(layerName, gridSetId)); + } + + @Override + public boolean deleteByParametersId(String layerName, String parametersId) throws StorageException { + Set prefixes = keys.forParameters(layerName, parametersId); + return truncate( + store -> prefixes.forEach(store::removeByPrefix), + () -> delegate.deleteByParametersId(layerName, parametersId)); + } + + @Override + public boolean delete(TileObject obj) throws StorageException { + // disk quota deletes tile by tile, two cache calls each are not worth one stale tile of a former cached layer + if (!cached) return delegate.delete(obj); + String key = keys.forTile(obj, layer.getId()); + return deleteTiles(store -> store.remove(key), () -> delegate.delete(obj)); + } + + @Override + public boolean delete(TileRange range) throws StorageException { + // prefixes first, so that only store failures count as a cache outage + List prefixes = IntStream.rangeClosed(range.getZoomStart(), range.getZoomStop()) + .mapToObj(z -> keys.forZoomLevel(range, z)) + .toList(); + return deleteTiles(store -> removeRange(store, range, prefixes), () -> delegate.delete(range)); + } + + /** + * A {@link #truncateTiles} that, with passthrough on, still deletes from the store behind while the cache is down, + * so that disk quota frees space during an outage; the cached copies are then served until they expire. + */ + private boolean deleteTiles(Consumer removeFromCache, StoreTruncate truncateStore) + throws StorageException { + // with passthrough off the store holds no tiles, there is no space to free: fail as the other truncates + if (!truncateNeedsCache() || !storeHoldsTiles()) return truncateTiles(removeFromCache, truncateStore); + if (cacheRemovalFailure(removeFromCache) != null) { + if (cache.getDeletesSkippingCache().compareAndSet(false, true)) { + // SEVERE as the outage lines, production logging keeps org.geowebcache at error + LOGGER.severe("In-memory tile cache is unreachable, tile deletes of layer " + layer.getName() + + " run on the blob store only, cached copies are served until they expire"); + } + return truncateStore.run(); + } + cache.getDeletesSkippingCache().set(false); + return truncateStoreThenCache(removeFromCache, truncateStore); + } + + /** Removes the range from the cache, {@code prefixes} holding the key prefix of each of its zoom levels. */ + private static void removeRange(KeyValueStore store, TileRange range, List prefixes) { + for (int i = 0; i < prefixes.size(); i++) { + int z = range.getZoomStart() + i; + store.removeMatching(prefixes.get(i), key -> inRange(range, key, z)); + } + } + + /** Checks a key ending with {@code /.} against the range; a key of any other shape is in it. */ + private static boolean inRange(TileRange range, String key, int z) { + int dot = key.lastIndexOf('.'); + int ySlash = key.lastIndexOf('/', dot); + int xSlash = key.lastIndexOf('/', ySlash - 1); + try { + long x = Long.parseLong(key, xSlash + 1, ySlash, 10); + long y = Long.parseLong(key, ySlash + 1, dot, 10); + return range.contains(x, y, z); + } catch (NumberFormatException | IndexOutOfBoundsException e) { + // removing more than asked is allowed, throwing would turn one stray key into a cache outage + return true; + } + } + + @Override + public void clear() throws StorageException { + truncate(KeyValueStore::clear, () -> { + delegate.clear(); + return true; + }); + } + + /** + * A {@link #truncate} of tiles only, leaving the store behind alone when it holds no tiles. Layer and parameters + * truncates still reach it, since they also remove metadata and mappings. + */ + private boolean truncateTiles(Consumer removeFromCache, StoreTruncate truncateStore) + throws StorageException { + // with passthrough off nothing reads through, so the second removal protects nothing, kept to share one + // failure path + return truncate(removeFromCache, () -> !storeHoldsTiles() || truncateStore.run()); + } + + /** + * Removes the truncated tiles from the cache, truncates the store behind, then removes them from the cache again. + * + * @param removeFromCache removes the keys of the truncated tiles, run twice + * @param truncateStore the same truncate on the store behind, whose result is returned + * @throws StorageException for a memory cached layer, before the store when the first removal fails or is refused, + * a retry then truncates both; after it when the second removal fails + */ + private boolean truncate(Consumer removeFromCache, StoreTruncate truncateStore) + throws StorageException { + if (!truncateNeedsCache()) { + // only leftovers there, which nothing reads; refused at once while the cache is down + cacheRemovalFailure(removeFromCache); + return truncateStore.run(); + } + // truncating the store alone would leave the cached tiles, served again once the cache is back + RuntimeException failure = cacheRemovalFailure(removeFromCache); + if (failure != null) { + String message = "In-memory tile cache is unreachable, truncate of layer " + layer.getName() + + " not run, retry once it recovers"; + throw new StorageException(message, failure); + } + return truncateStoreThenCache(removeFromCache, truncateStore); + } + + /** + * Whether a cache failure fails a truncate: not for a layer not using the cache, whose tiles never go there, nor + * for an unusable cache, which never held any. + */ + private boolean truncateNeedsCache() { + return cached && !cache.getStore().isUnusable(); + } + + /** + * Truncates the store, then removes from the cache again, so that a tile read through from the store while it was + * being truncated does not survive. + * + * @throws StorageException when the removal fails, the store being truncated already + */ + private boolean truncateStoreThenCache(Consumer removeFromCache, StoreTruncate truncateStore) + throws StorageException { + boolean result = truncateStore.run(); + RuntimeException failure = cacheRemovalFailure(removeFromCache); + if (failure != null) { + String message = "In-memory tile cache removal failed after the blob store truncate of layer " + + layer.getName() + ", cached tiles may be stale until they expire"; + throw new StorageException(message, failure); + } + // with passthrough off the store behind holds no tiles, so its false only means it had nothing to delete + return result || !storeHoldsTiles(); + } + + /** Runs the removal on the cache; the failure, null on success. */ + @Nullable + private RuntimeException cacheRemovalFailure(Consumer removeFromCache) { + try { + removeFromCache.accept(cache.getStore()); + return null; + } catch (RuntimeException e) { + return e; + } + } + + /** A truncate of the store behind, true when it removed something. */ + @FunctionalInterface + private interface StoreTruncate { + boolean run() throws StorageException; + } + + @Override + public boolean rename(String oldLayerName, String newLayerName) throws StorageException { + // cache keys use the layer id, which a rename keeps + return delegate.rename(oldLayerName, newLayerName); + } + + @Override + public void destroy() { + delegate.destroy(); + } + + @Override + public void addListener(BlobStoreListener listener) { + delegate.addListener(listener); + } + + @Override + public boolean removeListener(BlobStoreListener listener) { + return delegate.removeListener(listener); + } + + @Override + public String getLayerMetadata(String layerName, String key) { + return delegate.getLayerMetadata(layerName, key); + } + + @Override + public void putLayerMetadata(String layerName, String key, String value) { + delegate.putLayerMetadata(layerName, key, value); + } + + @Override + public boolean layerExists(String layerName) { + return delegate.layerExists(layerName); + } + + @Override + public Set getParameterIds(String layerName) throws StorageException { + return delegate.getParameterIds(layerName); + } + + @Override + public Map>> getParametersMapping(String layerName) { + return delegate.getParametersMapping(layerName); + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java new file mode 100644 index 0000000000..baf1c3ee80 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java @@ -0,0 +1,269 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.google.common.base.Ticker; +import java.io.Serial; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import org.geotools.util.logging.Logging; + +/** + * Stops calling a failing backend for a while, so that a stalled cluster does not cost every tile request a full + * timeout. Failures, and calls refused meanwhile, throw {@link UnavailableException}; the backend hears of each change + * through {@link KeyValueStore#reachable}. Thread safe. + * + *

+ *   UP --fail--> DOWN --wait over--> PROBING --ok--> UP
+ *                  ^                     |
+ *                  +-------fail----------+
+ * 
+ * + *

While probing, a single call tests the backend. The wait grows with the outage, and a failure soon after a + * recovery continues the same outage. A call that started before the last change does not move the state. + */ +class GuardedStore implements KeyValueStore { + + private static final Logger LOGGER = Logging.getLogger(GuardedStore.class.getName()); + + /** Shortest wait between two probes. */ + private static final long MIN_RETRY = SECONDS.toNanos(1); + + /** Longest wait between two probes, also how long a recovery must hold before a failure starts a new outage. */ + private static final long MAX_RETRY = SECONDS.toNanos(30); + + /** The backend health, all times in ticker nanos. */ + private sealed interface State permits Up, Down, Probing {} + + /** Calls go through. {@code outageSince} and {@code recoveredAt} describe the last outage. */ + private record Up(long outageSince, long recoveredAt) implements State {} + + /** Calls are refused until {@code retryAt}. */ + private record Down(long since, long retryAt) implements State {} + + /** + * One call, granted at {@code grantedAt}, is testing the backend. Others are refused until it reports, or until + * {@code deadline} if it never does (a hung or lost probe), when the next caller probes instead. + */ + private record Probing(long since, long grantedAt, long deadline) implements State {} + + private final AtomicReference state; + + /** Null when unusable. */ + private final KeyValueStore delegate; + + /** Why the backend could not be built, null when usable. */ + private final String unusableReason; + + private final Ticker ticker; + + GuardedStore(KeyValueStore delegate, Ticker ticker) { + this(delegate, null, ticker); + } + + private GuardedStore(@Nullable KeyValueStore delegate, @Nullable String unusableReason, Ticker ticker) { + this.delegate = delegate; + this.unusableReason = unusableReason; + this.ticker = ticker; + // as if recovered long enough ago: every later failure starts a new outage + this.state = new AtomicReference<>(new Up(0, ticker.read() - MAX_RETRY)); + } + + /** A store refusing every call, for settings that cannot work until they change. Logs the reason once. */ + static GuardedStore unusable(String reason, @Nullable Throwable cause) { + LOGGER.log(Level.SEVERE, "In-memory tile cache unusable, " + reason, cause); + return new GuardedStore(null, reason, Ticker.systemTicker()); + } + + /** Whether the settings left no backend: the store never held tiles, and never recovers until they change. */ + boolean isUnusable() { + return delegate == null; + } + + /** + * Whether a call may go to the backend now. DOWN, or a PROBING past its deadline, moves to PROBING for one caller. + */ + private boolean mayCall() { + State current = state.get(); + if (current instanceof Up) return true; + long now = ticker.read(); + long since; + if (current instanceof Down down && now - down.retryAt() >= 0) { + since = down.since(); + } else if (current instanceof Probing probing && now - probing.deadline() >= 0) { + since = probing.since(); + } else { + return false; + } + // the caller winning the swap is the probe, the others keep being refused + return state.compareAndSet(current, new Probing(since, now, now + backoff(since, now))); + } + + /** DOWN or PROBING to UP, unless the call started before the outage. */ + private void succeeded(long start) { + State current = state.get(); + long since; + if (current instanceof Down down) { + since = down.since(); + } else if (current instanceof Probing probing) { + since = probing.since(); + } else { + return; + } + // on a cluster a call can answer after a newer one failed on another member: it says nothing about the outage + if (start - since < 0) return; + long now = ticker.read(); + if (state.compareAndSet(current, new Up(since, now))) { + LOGGER.severe("In-memory tile cache is reachable again after " + NANOSECONDS.toSeconds(now - since) + " s"); + reportState(); + } + } + + /** UP to DOWN, starting or resuming an outage; a failed probe back to DOWN with a longer wait. */ + private void failed(long start, RuntimeException e) { + long now = ticker.read(); + while (true) { + State current = state.get(); + long since; + boolean resumed; + if (current instanceof Probing probing && start - probing.grantedAt() >= 0) { + since = probing.since(); + resumed = false; + } else if (current instanceof Up up && start - up.recoveredAt() >= 0) { + resumed = now - up.recoveredAt() < MAX_RETRY; + since = resumed ? up.outageSince() : now; + } else { + // already DOWN, or a call started before the last change, failing on the state before it + return; + } + if (state.compareAndSet(current, new Down(since, now + backoff(since, now)))) { + logFailure(current, resumed, e); + // a failed probe stays unreachable, nothing to report + if (current instanceof Up) reportState(); + return; + } + } + } + + /** + * Tells the backend whether it is reachable. Reads the state under the lock, so that two changes racing cannot + * leave the older one reported last. + */ + private synchronized void reportState() { + delegate.reachable(state.get() instanceof Up); + } + + /** + * Logs an outage start or resume at SEVERE, as production logging keeps org.geowebcache at error and an outage + * start without its end cannot be read; a failed probe is not logged, the outage is already. + */ + private static void logFailure(State previous, boolean resumed, RuntimeException e) { + if (!(previous instanceof Up)) return; + if (resumed) { + LOGGER.severe("In-memory tile cache is unreachable again"); + return; + } + LOGGER.log( + Level.SEVERE, "In-memory tile cache is unreachable, tiles are served without it until it recovers", e); + } + + /** Half the outage age within the retry bounds, with 20% jitter so that nodes do not probe in lockstep. */ + private static long backoff(long since, long now) { + long wait = Math.min(Math.max((now - since) / 2, MIN_RETRY), MAX_RETRY); + return (long) (wait * ThreadLocalRandom.current().nextDouble(0.8, 1.2)); + } + + /** Thrown for every failed or refused call. No stack trace: while down it is thrown once per tile request. */ + static class UnavailableException extends RuntimeException { + + @Serial + private static final long serialVersionUID = 1L; + + UnavailableException(String message, @Nullable Throwable cause) { + super(message, cause, false, false); + } + } + + private T call(Function operation) { + // permanent, outside the state machine: no probe, no outage log, the reason was logged on creation + if (delegate == null) throw new UnavailableException("In-memory tile cache unusable, " + unusableReason, null); + if (!mayCall()) throw new UnavailableException("In-memory tile cache is down", null); + long start = ticker.read(); + try { + T result = operation.apply(delegate); + succeeded(start); + return result; + } catch (RuntimeException e) { + failed(start, e); + throw new UnavailableException("In-memory tile cache call failed", e); + } + } + + private void run(Consumer operation) { + call(store -> { + operation.accept(store); + return null; + }); + } + + @Override + public byte[] get(String key) { + return call(store -> store.get(key)); + } + + @Override + public void put(String key, byte[] value, long ttlSeconds) { + run(store -> store.put(key, value, ttlSeconds)); + } + + @Override + public void putIfAbsent(String key, byte[] value, long ttlSeconds) { + run(store -> store.putIfAbsent(key, value, ttlSeconds)); + } + + @Override + public void remove(String key) { + run(store -> store.remove(key)); + } + + @Override + public void removeByPrefix(String prefix) { + run(store -> store.removeByPrefix(prefix)); + } + + @Override + public void removeMatching(String prefix, Predicate remove) { + run(store -> store.removeMatching(prefix, remove)); + } + + @Override + public void clear() { + run(KeyValueStore::clear); + } + + /** Closes the backend store; requests still running on it see failures, handled as misses. */ + @Override + public void close() { + if (delegate != null) delegate.close(); + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java new file mode 100644 index 0000000000..711ae54fb7 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java @@ -0,0 +1,102 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.google.common.base.Ticker; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.util.function.Predicate; + +/** {@link KeyValueStore} in the local JVM heap, bounded by the total size of its values. */ +public class HeapKeyValueStore implements KeyValueStore { + + /** Guava only expires per cache, so the per-entry deadline is checked on read. */ + private record Entry(byte[] value, long expiresAtNanos) {} + + private final Cache cache; + + private final Ticker ticker; + + /** + * Creates a store holding at most {@code maxBytes} of values; an expired entry keeps its memory until read or + * evicted. + */ + public HeapKeyValueStore(long maxBytes) { + this(maxBytes, Ticker.systemTicker()); + } + + HeapKeyValueStore(long maxBytes, Ticker ticker) { + this.ticker = ticker; + this.cache = CacheBuilder.newBuilder() + .maximumWeight(maxBytes) + .weigher((String key, Entry entry) -> entry.value.length) + .build(); + } + + @Override + public byte[] get(String key) { + Entry entry = cache.getIfPresent(key); + if (entry == null) return null; + if (expired(entry)) { + cache.asMap().remove(key, entry); + return null; + } + return entry.value; + } + + @Override + public void put(String key, byte[] value, long ttlSeconds) { + cache.put(key, new Entry(value, ticker.read() + SECONDS.toNanos(ttlSeconds))); + } + + @Override + public void putIfAbsent(String key, byte[] value, long ttlSeconds) { + Entry entry = new Entry(value, ticker.read() + SECONDS.toNanos(ttlSeconds)); + Entry current = cache.asMap().putIfAbsent(key, entry); + // an expired entry counts as absent, as get reports it so + if (current != null && expired(current)) cache.asMap().replace(key, current, entry); + } + + private boolean expired(Entry entry) { + // nanoTime-style values can overflow, compare the difference + return ticker.read() - entry.expiresAtNanos >= 0; + } + + @Override + public void remove(String key) { + cache.invalidate(key); + } + + @Override + public void removeByPrefix(String prefix) { + cache.asMap().keySet().removeIf(key -> key.startsWith(prefix)); + } + + @Override + public void removeMatching(String prefix, Predicate remove) { + cache.asMap().keySet().removeIf(key -> key.startsWith(prefix) && remove.test(key)); + } + + @Override + public void clear() { + cache.invalidateAll(); + } + + @Override + public void close() { + // nothing to release, the entries go with the instance + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java new file mode 100644 index 0000000000..5d99c32adc --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java @@ -0,0 +1,55 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import java.io.Serial; + +/** + * Settings of the {@link HeapKeyValueStore}, tiles in the heap of each node; an absent element reads as its default. + */ +public class HeapKeyValueStoreInfo implements KeyValueStoreInfo { + + @Serial + private static final long serialVersionUID = 1L; + + static final int DEFAULT_MAX_SIZE_MB = 64; + + private Integer maxSizeMB; + + /** Maximum total size of the cached tiles on each node, in megabytes, 64 by default. */ + public int getMaxSizeMB() { + return maxSizeMB == null ? DEFAULT_MAX_SIZE_MB : maxSizeMB; + } + + /** Sets the maximum total size of the cached tiles on each node, in megabytes. */ + public void setMaxSizeMB(int maxSizeMB) { + this.maxSizeMB = maxSizeMB; + } + + @Override + public KeyValueStore createStore() { + return new HeapKeyValueStore(getMaxSizeMB() * 1024L * 1024L); + } + + /** Equal when the effective settings are, an absent value matching its default. */ + @Override + public boolean equals(Object o) { + return o instanceof HeapKeyValueStoreInfo other && getMaxSizeMB() == other.getMaxSizeMB(); + } + + @Override + public int hashCode() { + return getMaxSizeMB(); + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java new file mode 100644 index 0000000000..c139cae275 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java @@ -0,0 +1,65 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import java.util.function.Predicate; + +/** + * Stores byte arrays under string keys, a key prefix naming a set of entries. + * + *

Entries expire after the time to live given by the caller, and may be dropped earlier, so never keep state here + * that must survive. Keys and values are opaque to implementations, which must be thread safe and throw an unchecked + * exception when their backend cannot be reached. + */ +public interface KeyValueStore extends AutoCloseable { + + /** Returns the value, or null when the key is absent or expired. */ + byte[] get(String key); + + /** Stores the value for at most {@code ttlSeconds}, positive. */ + void put(String key, byte[] value, long ttlSeconds); + + /** Stores the value as {@link #put} does, unless the key already holds one. Atomic. */ + void putIfAbsent(String key, byte[] value, long ttlSeconds); + + /** Removes the entry, if any. */ + void remove(String key); + + /** Removes every entry whose key starts with the prefix. Other nodes see the removal on return. */ + void removeByPrefix(String prefix); + + /** + * Removes the entries under the prefix that the predicate accepts. + * + *

An implementation may remove more than that and log it. Callers already have to accept losing entries at any + * time, since storage is ephemeral. + */ + void removeMatching(String prefix, Predicate remove); + + /** Removes every entry, including entries other nodes wrote. */ + void clear(); + + /** + * Told whether the cache now considers this store reachable, when that changes. Calls may repeat a value but never + * overlap, and the last one carries the current state. Must return quickly. Does nothing by default. + */ + default void reachable(boolean reachable) {} + + /** + * Releases what this store owns. Entries are left in place, and a connection shared with other callers outlives the + * call. + */ + @Override + void close(); +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java new file mode 100644 index 0000000000..bdb3d481b9 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java @@ -0,0 +1,26 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import java.io.Serializable; + +/** + * Settings of one cache backend, persisted as the {@code } of {@code }, and the factory of its + * {@link KeyValueStore}; each implementation needs an XStream alias, registered by its module. + */ +public interface KeyValueStoreInfo extends Serializable { + + /** Returns a new store for these settings; the caller closes it. */ + KeyValueStore createStore(); +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java new file mode 100644 index 0000000000..d02a079d9d --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java @@ -0,0 +1,153 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import com.google.common.base.Ticker; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import org.geotools.util.logging.Logging; +import org.geowebcache.layer.TileLayer; +import org.geowebcache.layer.TileLayerDispatcher; +import org.geowebcache.storage.BlobStore; +import org.geowebcache.util.TMSKeyBuilder; + +/** + * In-memory tile cache shared by all cached layers of this node, built from one {@link MemoryCacheInfo}: its + * {@link KeyValueStore}, guarded against outages. Thread safe. + */ +public class MemoryCache implements AutoCloseable { + + private static final Logger LOGGER = Logging.getLogger(MemoryCache.class.getName()); + + private final MemoryCacheInfo info; + + /** Null when the cache is disabled, refusing every call when enabled but unusable. */ + private final GuardedStore store; + + private final TMSKeyBuilder keys; + + /** Whether the last parameter mapping write failed, so that a store outage is logged once, not per tile. */ + private final AtomicBoolean mappingWritesFailing = new AtomicBoolean(); + + /** Whether the last tile delete ran on the blob store only, so that a cache outage is logged once, not per tile. */ + private final AtomicBoolean deletesSkippingCache = new AtomicBoolean(); + + private final MemoryCacheStats stats; + + /** + * Builds the cache for {@code info}, disabled when null. Invalid settings or a backend that cannot be created are + * logged, not thrown, and leave the cache unusable: cached layers then miss and drop writes. + */ + public MemoryCache(@Nullable MemoryCacheInfo info, TileLayerDispatcher layers) { + this(info, layers, Ticker.systemTicker()); + } + + MemoryCache(@Nullable MemoryCacheInfo info, TileLayerDispatcher layers, Ticker ticker) { + this.info = info; + this.store = info != null && info.isEnabled() ? createStore(info, ticker) : null; + // no key prefix, the cache holds tiles only + this.keys = new TMSKeyBuilder(null, layers); + this.stats = new MemoryCacheStats(info == null ? 0 : info.getStatsInterval(), ticker); + } + + // never null: falling back to the layer's own store would write tiles there with passthrough off + private static GuardedStore createStore(MemoryCacheInfo info, Ticker ticker) { + if (info.getTimeToLive() < 1) { + return GuardedStore.unusable("time to live must be at least 1 second, got " + info.getTimeToLive(), null); + } + KeyValueStoreInfo settings = info.getBackend(); + if (settings instanceof UnresolvedKeyValueStoreInfo unresolved) { + return GuardedStore.unusable("backend " + unresolved.getAlias() + " is not installed", null); + } + try { + return new GuardedStore(settings.createStore(), ticker); + } catch (RuntimeException | LinkageError e) { + // a LinkageError comes from a backend jar missing its library or built against another version of it; + // left to escape, it would fail every blob store call, as the cache is built again on each of them + return GuardedStore.unusable( + "could not create backend " + settings.getClass().getSimpleName(), e); + } + } + + /** The settings this cache was built from, null if none. */ + @Nullable + public MemoryCacheInfo getInfo() { + return info; + } + + /** + * Returns {@code store} unchanged when the cache is disabled, otherwise a store serving the layer tiles from the + * cache if the layer uses it. Truncates clear the layer tiles from the cache either way. + */ + public BlobStore wrap(TileLayer layer, BlobStore store) { + return this.store == null ? store : new CachingBlobStore(store, this, layer, layer.isMemoryCached()); + } + + /** + * Drops the tiles cached under the old name of a renamed layer, which a new layer with that name would serve + * otherwise. Does nothing when layer ids are not their names, as in GeoServer. Never throws. + */ + public void layerRenamed(String oldName, String newName) { + if (store == null) return; + try { + // keys start with the layer id: one that survives the rename leaves nothing under the old name + if (!newName.equals(keys.layerId(newName))) return; + } catch (RuntimeException e) { + // layer not found, remove to be safe + } + // the TMSKeyBuilder.forLayer layout, which cannot be used as no layer has that name any more + String prefix = oldName + "/"; + try { + store.removeByPrefix(prefix); + } catch (RuntimeException e) { + LOGGER.warning("In-memory tile cache could not remove the tiles of renamed layer " + oldName + + ", a new layer with that name may serve them until they expire"); + } + } + + /** Closes the backend store; requests still running on it see failures, handled as misses. */ + @Override + public void close() { + if (store != null) store.close(); + } + + GuardedStore getStore() { + return store; + } + + long getTtlSeconds() { + return info.getTimeToLive(); + } + + boolean isPassthrough() { + return info.isPassthrough(); + } + + TMSKeyBuilder getKeys() { + return keys; + } + + AtomicBoolean getMappingWritesFailing() { + return mappingWritesFailing; + } + + AtomicBoolean getDeletesSkippingCache() { + return deletesSkippingCache; + } + + MemoryCacheStats getStats() { + return stats; + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java new file mode 100644 index 0000000000..d8cc8cf554 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java @@ -0,0 +1,105 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import java.io.Serial; +import java.io.Serializable; +import java.util.Objects; + +/** The {@code } settings of {@code geowebcache.xml}; an absent element reads as its default. */ +public class MemoryCacheInfo implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + static final long DEFAULT_TIME_TO_LIVE = 300; + + static final long DEFAULT_STATS_INTERVAL = 300; + + private Boolean enabled; + + private Long timeToLive; + + private Boolean passthrough; + + private Long statsInterval; + + private KeyValueStoreInfo backend; + + /** Whether cached layers go through the cache, false by default. */ + public boolean isEnabled() { + return Boolean.TRUE.equals(enabled); + } + + /** Turns the cache on or off for every cached layer. */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /** Time to live in seconds of the tiles of layers without an expire server cache, 300 by default. */ + public long getTimeToLive() { + return timeToLive == null ? DEFAULT_TIME_TO_LIVE : timeToLive; + } + + /** Sets the time to live of the tiles of layers without an expire server cache, in seconds and positive. */ + public void setTimeToLive(long timeToLive) { + this.timeToLive = timeToLive; + } + + /** Whether tiles are also written to, and read through from, the layer's own blob store, true by default. */ + public boolean isPassthrough() { + return passthrough == null || passthrough; + } + + /** Sets whether tiles are also written to, and read through from, the layer's own blob store. */ + public void setPassthrough(boolean passthrough) { + this.passthrough = passthrough; + } + + /** Seconds between two statistics lines per layer in the log, 300 by default, 0 when turned off. */ + public long getStatsInterval() { + return statsInterval == null ? DEFAULT_STATS_INTERVAL : statsInterval; + } + + /** Sets the seconds between two statistics lines per layer in the log, 0 turns them off. */ + public void setStatsInterval(long statsInterval) { + this.statsInterval = statsInterval; + } + + /** The backend settings, the heap backend with its defaults when absent. */ + public KeyValueStoreInfo getBackend() { + return backend == null ? new HeapKeyValueStoreInfo() : backend; + } + + /** Sets the backend settings, which create the store of the cache. */ + public void setBackend(KeyValueStoreInfo backend) { + this.backend = backend; + } + + /** Equal when the effective settings are, an absent value matching its default. */ + @Override + public boolean equals(Object o) { + return o instanceof MemoryCacheInfo other + && isEnabled() == other.isEnabled() + && getTimeToLive() == other.getTimeToLive() + && isPassthrough() == other.isPassthrough() + && getStatsInterval() == other.getStatsInterval() + && getBackend().equals(other.getBackend()); + } + + @Override + public int hashCode() { + return Objects.hash(isEnabled(), getTimeToLive(), isPassthrough(), getStatsInterval(), getBackend()); + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java new file mode 100644 index 0000000000..ee84784ed3 --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java @@ -0,0 +1,136 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.google.common.base.Ticker; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.LongAdder; +import java.util.logging.Logger; +import org.geotools.util.logging.Logging; + +/** Per-layer read results and failed puts, logged at INFO and reset by the first {@link #report()} of each interval. */ +class MemoryCacheStats { + + private static final Logger LOGGER = Logging.getLogger(MemoryCacheStats.class.getName()); + + /** Outcome of a tile read. */ + enum Result { + /** Served from the cache. */ + HIT, + /** Not in the cache, read through from the store behind. */ + STORE, + /** Neither in the cache nor, with passthrough on, in the store behind. */ + MISS, + /** Served from the cache, but older than the layer's expire server cache, so the layer renders it again. */ + EXPIRED, + /** The cache read failed. */ + ERROR + } + + private final long intervalNanos; + + private final Ticker ticker; + + private final AtomicLong nextReport; + + private final Map layers = new ConcurrentHashMap<>(); + + /** Counters shared by every layer when reports are off, never read. */ + private final LayerStats discarded = new LayerStats(); + + /** No report is ever logged with an interval of 0. */ + MemoryCacheStats(long intervalSeconds, Ticker ticker) { + this.intervalNanos = SECONDS.toNanos(intervalSeconds); + this.ticker = ticker; + this.nextReport = new AtomicLong(ticker.read() + intervalNanos); + } + + LayerStats forLayer(String layerName) { + // never reported, so never pruned: keeping them per layer would only grow with removed and renamed layers + if (intervalNanos <= 0) return discarded; + return layers.computeIfAbsent(layerName, name -> new LayerStats()); + } + + /** + * Logs and resets the counters of every layer with traffic when the interval is over, cheap otherwise. A layer + * without traffic in the interval is dropped, so removed and renamed layers do not stay; a read racing the drop may + * go uncounted. + */ + void report() { + if (intervalNanos <= 0) return; + long now = ticker.read(); + long next = nextReport.get(); + // one caller wins the interval, the others go on serving tiles + if (now - next < 0 || !nextReport.compareAndSet(next, now + intervalNanos)) return; + long elapsedSeconds = NANOSECONDS.toSeconds(now - next + intervalNanos); + layers.forEach((name, stats) -> { + if (!stats.report(name, elapsedSeconds)) layers.remove(name, stats); + }); + } + + /** Counters of one layer, each reset on its own, so a call racing with a report may count in the next interval. */ + static class LayerStats { + + /** Filled in the constructor and never changed after, so reads need no lock. */ + private final Map reads = new EnumMap<>(Result.class); + + private final LongAdder failedPuts = new LongAdder(); + + LayerStats() { + for (Result result : Result.values()) reads.put(result, new LongAdder()); + } + + void read(Result result) { + reads.get(result).increment(); + } + + void failedPut() { + failedPuts.increment(); + } + + /** Logs and resets the counters, returning false, with nothing logged, when there was no traffic. */ + private boolean report(String layerName, long elapsedSeconds) { + Map counts = new EnumMap<>(Result.class); + reads.forEach((result, adder) -> counts.put(result, adder.sumThenReset())); + long total = counts.values().stream().mapToLong(Long::longValue).sum(); + long failed = failedPuts.sumThenReset(); + if (total + failed == 0) return false; + + long hits = counts.get(Result.HIT); + String message = String.format( + Locale.ROOT, + "In-memory tile cache stats for layer %s over %d s: %d reads (hit %d, store %d, miss %d," + + " expired %d, error %d), hit ratio %.1f%%, %d failed puts", + layerName, + elapsedSeconds, + total, + hits, + counts.get(Result.STORE), + counts.get(Result.MISS), + counts.get(Result.EXPIRED), + counts.get(Result.ERROR), + total == 0 ? 0 : 100.0 * hits / total, + failed); + LOGGER.info(message); + return true; + } + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java new file mode 100644 index 0000000000..f5b9998ffa --- /dev/null +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java @@ -0,0 +1,135 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier; +import com.thoughtworks.xstream.io.xml.CompactWriter; +import com.thoughtworks.xstream.io.xml.DomDriver; +import com.thoughtworks.xstream.mapper.CannotResolveClassException; +import com.thoughtworks.xstream.mapper.Mapper; +import com.thoughtworks.xstream.mapper.MapperWrapper; +import java.io.Serial; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.Objects; + +/** + * Backend settings whose class is unknown, as when the backend module was removed: the cache is unusable, and the + * settings are saved back as they were read, so that reinstalling the module restores them. + */ +public class UnresolvedKeyValueStoreInfo implements KeyValueStoreInfo { + + @Serial + private static final long serialVersionUID = 1L; + + private static final String CLASS = "class"; + + private final String alias; + + /** The whole {@code } element. */ + private final String xml; + + UnresolvedKeyValueStoreInfo(String alias, String xml) { + this.alias = alias; + this.xml = xml; + } + + /** The {@code class} attribute of the backend element, null when missing. */ + public String getAlias() { + return alias; + } + + /** Always fails, as the class of these settings is not installed. */ + @Override + public KeyValueStore createStore() { + throw new IllegalStateException("Backend " + alias + " is not installed"); + } + + /** Equal when both hold the same backend element. */ + @Override + public boolean equals(Object o) { + return o instanceof UnresolvedKeyValueStoreInfo other && xml.equals(other.xml); + } + + @Override + public int hashCode() { + return Objects.hash(xml); + } + + /** + * Lets {@code xs} read {@code } with an unknown backend instead of failing the whole configuration. + */ + public static void register(XStream xs) { + // an unknown class attribute fails in the reflection converter, before any converter of the field runs, so + // MemoryCacheInfo gets a reflection converter of its own resolving it to this class + Mapper mapper = new MapperWrapper(xs.getMapper()) { + @Override + public Class realClass(String elementName) { + try { + return super.realClass(elementName); + } catch (CannotResolveClassException e) { + return UnresolvedKeyValueStoreInfo.class; + } + } + + // no class attribute written for this class, the converter writes the original one + @Override + public Class defaultImplementationOf(Class type) { + if (type == KeyValueStoreInfo.class) return UnresolvedKeyValueStoreInfo.class; + return super.defaultImplementationOf(type); + } + }; + xs.registerConverter(new ReflectionConverter(mapper, xs.getReflectionProvider(), MemoryCacheInfo.class)); + xs.registerConverter(new RawConverter()); + } + + /** Copies the backend element as raw XML. */ + private static class RawConverter implements Converter { + + @Override + public boolean canConvert(Class type) { + return type == UnresolvedKeyValueStoreInfo.class; + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { + StringWriter xml = new StringWriter(); + CompactWriter writer = new CompactWriter(xml); + new HierarchicalStreamCopier().copy(reader, writer); + // the writer buffers + writer.flush(); + return new UnresolvedKeyValueStoreInfo(reader.getAttribute(CLASS), xml.toString()); + } + + @Override + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + UnresolvedKeyValueStoreInfo info = (UnresolvedKeyValueStoreInfo) source; + HierarchicalStreamReader reader = new DomDriver().createReader(new StringReader(info.xml)); + if (info.alias != null) writer.addAttribute(CLASS, info.alias); + HierarchicalStreamCopier copier = new HierarchicalStreamCopier(); + while (reader.hasMoreChildren()) { + reader.moveDown(); + copier.copy(reader, writer); + reader.moveUp(); + } + } + } +} diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java index edb120ca9a..90f9d10b82 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java @@ -90,11 +90,15 @@ public Set layerFormats(String layerName) { public String forTile(TileObject obj) { checkNotNull(obj.getLayerName()); + return forTile(obj, layerId(obj.getLayerName())); + } + + /** Same as {@link #forTile(TileObject)}, for a caller that already knows the id of the tile's layer. */ + public String forTile(TileObject obj, String layer) { checkNotNull(obj.getGridSetId()); checkNotNull(obj.getBlobFormat()); checkNotNull(obj.getXYZ()); - String layer = layerId(obj.getLayerName()); String gridset = obj.getGridSetId(); String shortFormat; String parametersId = obj.getParametersId(); diff --git a/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd b/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd index c73d04ea9c..2437d82d7b 100644 --- a/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd +++ b/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd @@ -167,6 +167,15 @@ + + + + + The shared in-memory tile cache, used by the layers that set memoryCached. Layer metadata and parameter + mappings stay in the layer's blob store. + + + @@ -207,6 +216,53 @@ + + + + + Whether the cache is used. Defaults to false. + + + + + + Seconds a tile stays in the cache at most. Defaults to 300. A shorter expireCache on the layer applies + instead. + + + + + + + Whether tiles are also written to, and read through from, the layer's blob store. Defaults to true. When + false, tiles live in the cache only. + + + + + + + Seconds between two statistics lines per layer in the log. Defaults to 300, 0 turns them off. + + + + + + + The backend settings, named by the class attribute. Defaults to class="heapKeyValueStore", which keeps tiles + in the memory of each node, not shared, with maxSizeMB (default 64) as its size limit. + + + + + + + + + + + + @@ -366,6 +422,13 @@ + + + + Whether the tiles of this layer go through the in-memory tile cache, when enabled. Defaults to false. + + + diff --git a/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java b/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java index e921fad229..9e0b345802 100644 --- a/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java +++ b/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -28,6 +29,7 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -40,8 +42,10 @@ import java.io.FileInputStream; import java.io.FilterOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -72,6 +76,9 @@ import org.geowebcache.layer.TileLayer; import org.geowebcache.layer.wms.WMSLayer; import org.geowebcache.storage.UnsuitableStorageException; +import org.geowebcache.storage.memorycache.HeapKeyValueStoreInfo; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; +import org.geowebcache.storage.memorycache.UnresolvedKeyValueStoreInfo; import org.geowebcache.util.TestUtils; import org.junit.Assume; import org.junit.Before; @@ -760,4 +767,86 @@ public void loadFromEmptyReadOnlyDirectoryFails() throws GeoWebCacheException, I roEmptyDir.setWritable(true); } } + + @Test + public void testMemoryCacheAbsentByDefault() { + assertNull(config.getMemoryCache()); + WMSLayer layer = (WMSLayer) + config.getLayer(config.getLayerNames().iterator().next()).get(); + assertFalse(layer.isMemoryCached()); + } + + @Test + public void testSaveMemoryCache() throws Exception { + HeapKeyValueStoreInfo heap = new HeapKeyValueStoreInfo(); + heap.setMaxSizeMB(128); + MemoryCacheInfo memoryCache = new MemoryCacheInfo(); + memoryCache.setEnabled(true); + memoryCache.setTimeToLive(120); + memoryCache.setPassthrough(false); + memoryCache.setStatsInterval(60); + memoryCache.setBackend(heap); + + config.setMemoryCache(memoryCache); + + assertValidAgainstSchema(); + MemoryCacheInfo reloaded = reload().getMemoryCache(); + assertTrue(reloaded.isEnabled()); + assertEquals(120, reloaded.getTimeToLive()); + assertFalse(reloaded.isPassthrough()); + assertEquals(60, reloaded.getStatsInterval()); + assertEquals(128, ((HeapKeyValueStoreInfo) reloaded.getBackend()).getMaxSizeMB()); + } + + @Test + public void testUnknownBackendKeptAsIs() throws Exception { + MemoryCacheInfo memoryCache = new MemoryCacheInfo(); + memoryCache.setEnabled(true); + memoryCache.setBackend(new HeapKeyValueStoreInfo()); + config.setMemoryCache(memoryCache); + // as left by a removed backend module + String xml = Files.readString(configFile.toPath()) + .replaceAll( + "(?s)|>.*?)", + "cache-15701"); + Files.writeString(configFile.toPath(), xml); + + XMLConfiguration reloaded = reload(); + UnresolvedKeyValueStoreInfo backend = + (UnresolvedKeyValueStoreInfo) reloaded.getMemoryCache().getBackend(); + assertEquals("removedTileCache", backend.getAlias()); + + // saved back as it was, so reinstalling the module restores it + reloaded.setMemoryCache(reloaded.getMemoryCache()); + assertValidAgainstSchema(); + String saved = Files.readString(configFile.toPath()); + assertThat(saved, containsString("")); + assertThat(saved, containsString("cache-1")); + assertThat(saved, containsString("5701")); + } + + @Test + public void testSaveMemoryCachedLayer() throws Exception { + String name = config.getLayerNames().iterator().next(); + WMSLayer layer = (WMSLayer) config.getLayer(name).get(); + layer.setMemoryCached(true); + + config.modifyLayer(layer); + + assertValidAgainstSchema(); + assertTrue(reload().getLayer(name).get().isMemoryCached()); + } + + private void assertValidAgainstSchema() throws Exception { + try (InputStream in = new FileInputStream(configFile)) { + XMLConfiguration.validate(XMLConfiguration.loadDocument(in)); + } + } + + private XMLConfiguration reload() throws Exception { + XMLConfiguration reloaded = new XMLConfiguration(null, configDir.getAbsolutePath()); + reloaded.setGridSetBroker(gridSetBroker); + reloaded.afterPropertiesSet(); + return reloaded; + } } diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java new file mode 100644 index 0000000000..03b89a6818 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java @@ -0,0 +1,206 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** {@link KeyValueStore} contract every backend must pass; subclasses provide an empty store. */ +public abstract class AbstractKeyValueStoreTest { + + /** "layer/a0/1" sits right after the "layer/a/" range, as '0' follows '/'. */ + private static final List KEYS = List.of("layer/a/1", "layer/a/2", "layer/a0/1", "layer/ab/1", "other/1"); + + private static final int THREADS = 4; + + private static final int ROUNDS = 200; + + private static final int VALUE_SIZE = 16 * 1024; + + protected KeyValueStore store; + + private final ExecutorService executor = Executors.newCachedThreadPool(); + + /** Released once every task of a test is submitted, so that they start together. */ + private final CountDownLatch go = new CountDownLatch(1); + + /** Returns a store holding no entries. */ + protected abstract KeyValueStore createStore() throws Exception; + + @Before + public void setUpStore() throws Exception { + store = createStore(); + } + + @After + public void closeStore() { + executor.shutdownNow(); + // null when createStore failed, keep that failure as the only one reported + if (store != null) store.close(); + } + + @Test + public void testPutOverwrites() { + store.put("key", new byte[] {1}, 300); + store.put("key", new byte[] {2}, 300); + + assertArrayEquals(new byte[] {2}, store.get("key")); + assertNull(store.get("missing")); + } + + @Test + public void testRemove() { + store.put("key", new byte[] {1}, 300); + + store.remove("key"); + store.remove("key"); + assertNull(store.get("key")); + } + + @Test + public void testRemoveByPrefix() { + putKeys(); + + store.removeByPrefix("layer/a/"); + + assertThat(presentKeys(), containsInAnyOrder("layer/a0/1", "layer/ab/1", "other/1")); + } + + @Test + public void testRemoveMatching() { + putKeys(); + + store.removeMatching("layer/", key -> key.endsWith("/1")); + + assertThat(presentKeys(), containsInAnyOrder("layer/a/2", "other/1")); + } + + @Test + public void testClear() { + putKeys(); + + store.clear(); + + assertThat(presentKeys(), empty()); + } + + @Test + public void testPutIfAbsentKeepsPresentValue() { + store.put("key", new byte[] {1}, 300); + store.putIfAbsent("key", new byte[] {2}, 300); + store.putIfAbsent("other", new byte[] {3}, 300); + + assertArrayEquals(new byte[] {1}, store.get("key")); + assertArrayEquals(new byte[] {3}, store.get("other")); + } + + @Test + public void testConcurrentGetsAndPutsGiveWholeValues() throws Exception { + List> tasks = new ArrayList<>(); + AtomicInteger broken = new AtomicInteger(); + for (int t = 1; t <= THREADS; t++) { + byte[] value = new byte[VALUE_SIZE]; + Arrays.fill(value, (byte) t); + tasks.add(submit(() -> { + for (int i = 0; i < ROUNDS; i++) store.put("key", value.clone(), 300); + })); + tasks.add(submit(() -> { + for (int i = 0; i < ROUNDS; i++) if (!isWhole(store.get("key"))) broken.incrementAndGet(); + })); + } + go.countDown(); + for (Future task : tasks) task.get(60, SECONDS); + + assertEquals(0, broken.get()); + } + + /** Null, or the value of one writer: full length, every byte its id. */ + private static boolean isWhole(byte[] value) { + if (value == null) return true; + if (value.length != VALUE_SIZE || value[0] == 0) return false; + for (byte b : value) if (b != value[0]) return false; + return true; + } + + @Test + public void testRemoveByPrefixDuringPutsLeavesNoEarlierEntry() throws Exception { + AtomicBoolean removing = new AtomicBoolean(); + AtomicBoolean done = new AtomicBoolean(); + Queue before = new ConcurrentLinkedQueue<>(); + CountDownLatch warm = new CountDownLatch(THREADS); + List> writers = new ArrayList<>(); + for (int t = 0; t < THREADS; t++) { + String prefix = "layer/a/" + t + "/"; + writers.add(submit(() -> { + for (int i = 0; !done.get(); i++) { + store.put(prefix + i, new byte[] {1}, 300); + // false after the put returned: it ended before the removal started + if (!removing.get()) before.add(prefix + i); + if (i == ROUNDS / 4) warm.countDown(); + } + })); + } + go.countDown(); + assertTrue(warm.await(60, SECONDS)); + removing.set(true); + store.removeByPrefix("layer/a/"); + done.set(true); + for (Future writer : writers) writer.get(60, SECONDS); + + assertThat(present(before), empty()); + } + + private Future submit(Runnable task) { + return executor.submit((Callable) () -> { + go.await(); + task.run(); + return null; + }); + } + + private void putKeys() { + KEYS.forEach(key -> store.put(key, new byte[] {1}, 300)); + } + + private List presentKeys() { + return present(KEYS); + } + + private List present(Collection keys) { + return keys.stream().filter(key -> store.get(key) != null).toList(); + } +} diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java new file mode 100644 index 0000000000..b81501d954 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java @@ -0,0 +1,1071 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.easymock.EasyMock.anyInt; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.geowebcache.util.TMSKeyBuilder.PARAMETERS_METADATA_OBJECT_PREFIX; +import static org.geowebcache.util.TMSKeyBuilder.PARAMETERS_METADATA_OBJECT_SUFFIX; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.common.base.Ticker; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Predicate; +import java.util.logging.Level; +import org.geowebcache.config.ServerConfiguration; +import org.geowebcache.filter.parameters.ParametersUtils; +import org.geowebcache.io.ByteArrayResource; +import org.geowebcache.layer.TileLayer; +import org.geowebcache.layer.TileLayerDispatcher; +import org.geowebcache.mime.ImageMime; +import org.geowebcache.storage.BlobStore; +import org.geowebcache.storage.BlobStoreAggregator; +import org.geowebcache.storage.CompositeBlobStore; +import org.geowebcache.storage.DefaultStorageFinder; +import org.geowebcache.storage.StorageException; +import org.geowebcache.storage.TileObject; +import org.geowebcache.storage.TileRange; +import org.geowebcache.storage.blobstore.file.FileBlobStore; +import org.geowebcache.util.TMSKeyBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** Tile cache in front of a {@link FileBlobStore}, through {@link CompositeBlobStore} as in production. */ +public class CachingBlobStoreTest { + + private static final String LAYER = "roads"; + + private static final String GRIDSET = "EPSG:4326"; + + private static final String OTHER_GRIDSET = "EPSG:900913"; + + private static final Map STYLE_A = Map.of("STYLES", "a"); + + private static final Map STYLE_B = Map.of("STYLES", "b"); + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + @Rule + public LogLines log = new LogLines(CachingBlobStore.class, Level.FINE); + + @Rule + public LogLines stateLog = new LogLines(GuardedStore.class, Level.INFO); + + private final AtomicLong now = new AtomicLong(); + + private final Ticker ticker = new Ticker() { + @Override + public long read() { + return now.get(); + } + }; + + private final FailingStore kv = new FailingStore(new HeapKeyValueStore(1_000_000, ticker)); + + private int expireCache; + + private boolean memoryCached = true; + + /** The layer's blob store id, null for the default store. */ + private String blobStoreId; + + // volatile: the concurrency tests replace the settings while other threads read them + private volatile MemoryCacheInfo memoryCacheInfo; + + private final ExecutorService executor = Executors.newCachedThreadPool(); + + /** Built by {@link #newCache}, closed after the test. */ + private final List caches = new ArrayList<>(); + + private TileLayer layer; + + private TileLayerDispatcher layers; + + private CompositeBlobStore store; + + @Before + public void setUp() throws Exception { + layer = createNiceMock(TileLayer.class); + expect(layer.getName()).andStubReturn(LAYER); + expect(layer.getId()).andStubReturn("layer-id"); + expect(layer.isMemoryCached()).andStubAnswer(() -> memoryCached); + expect(layer.getBlobStoreId()).andStubAnswer(() -> blobStoreId); + expect(layer.getExpireCache(anyInt())).andStubAnswer(() -> expireCache); + expect(layer.getGridSubsets()).andStubReturn(Set.of(GRIDSET, OTHER_GRIDSET)); + expect(layer.getMimeTypes()).andStubReturn(List.of(ImageMime.png)); + // a standalone layer, whose id is its name + TileLayer renamed = createNiceMock(TileLayer.class); + expect(renamed.getId()).andStubReturn("renamed"); + layers = createNiceMock(TileLayerDispatcher.class); + expect(layers.getTileLayer(LAYER)).andStubReturn(layer); + expect(layers.getTileLayer("renamed")).andStubReturn(renamed); + DefaultStorageFinder storageFinder = createNiceMock(DefaultStorageFinder.class); + expect(storageFinder.getDefaultPath()).andStubReturn(temp.getRoot().getAbsolutePath()); + BlobStoreAggregator aggregator = createNiceMock(BlobStoreAggregator.class); + expect(aggregator.getBlobStores()).andStubReturn(List.of()); + ServerConfiguration serverConfig = createNiceMock(ServerConfiguration.class); + expect(serverConfig.getMemoryCache()).andStubAnswer(() -> memoryCacheInfo); + replay(layer, renamed, layers, storageFinder, aggregator, serverConfig); + + store = new CompositeBlobStore(layers, storageFinder, serverConfig, aggregator); + // tests writing to the store alone first set the settings to null + enableCache(false); + } + + @After + public void tearDown() { + executor.shutdownNow(); + caches.forEach(MemoryCache::close); + } + + @Test + public void testPassthroughOffServesTilesFromCacheOnly() throws Exception { + long before = System.currentTimeMillis(); + store.put(tile(0, 0, 0)); + long after = System.currentTimeMillis(); + + TileObject read = tile(0, 0, 0); + assertTrue(store.get(read)); + assertArrayEquals(new byte[] {1, 2, 3}, ((ByteArrayResource) read.getBlob()).getContents()); + assertThat(read.getCreated(), allOf(greaterThanOrEqualTo(before), lessThanOrEqualTo(after))); + assertFalse(inStore(tile(0, 0, 0))); + } + + @Test + public void testPassthroughOnWritesAndReadsThroughStore() throws Exception { + memoryCacheInfo = null; + store.put(tile(0, 0, 0)); + enableCache(true); + assertTrue(store.get(tile(0, 0, 0))); + + // remove from the store only, the cache still has it + memoryCacheInfo = null; + store.delete(tile(0, 0, 0)); + enableCache(true); + assertTrue(store.get(tile(0, 0, 0))); + + store.put(tile(1, 0, 1)); + assertTrue(inStore(tile(1, 0, 1))); + } + + @Test + public void testNoReadThroughWithPassthroughOff() throws Exception { + memoryCacheInfo = null; + store.put(tile(0, 0, 0)); + enableCache(false); + + assertFalse(store.get(tile(0, 0, 0))); + } + + @Test + public void testLayerExpireCacheSetsTimeToLive() throws Exception { + // shorter than the global time to live, then longer + expireCache = 10; + store.put(tile(0, 0, 0)); + expireCache = 3600; + store.put(tile(1, 0, 1)); + + now.set(SECONDS.toNanos(10)); + assertFalse(store.get(tile(0, 0, 0))); + now.set(SECONDS.toNanos(memoryCacheInfo.getTimeToLive() + 1)); + assertTrue(store.get(tile(1, 0, 1))); + now.set(SECONDS.toNanos(3600)); + assertFalse(store.get(tile(1, 0, 1))); + } + + @Test + public void testDeleteLayer() throws Exception { + store.put(tile(0, 0, 0)); + store.put(tile(OTHER_GRIDSET, STYLE_B, 0, 0, 0)); + + store.delete(LAYER); + + assertFalse(store.get(tile(0, 0, 0))); + assertFalse(store.get(tile(OTHER_GRIDSET, STYLE_B, 0, 0, 0))); + } + + @Test + public void testRenameDropsTilesOnlyWhenIdChanges() throws Exception { + // no parameters, so no mapping file, and no layer directory for the file store rename to trip on + store.put(tile(GRIDSET, null, 0, 0, 0)); + int calls = kv.calls.get(); + + // as in GeoServer: the new name resolves to an id the rename keeps + store.rename("old-name", LAYER); + assertEquals(calls, kv.calls.get()); + assertTrue(store.get(tile(GRIDSET, null, 0, 0, 0))); + + // standalone layer ids are their names, so the old name is the id the tiles were cached under + store.rename("layer-id", "renamed"); + assertFalse(store.get(tile(GRIDSET, null, 0, 0, 0))); + } + + @Test + public void testDeleteGridset() throws Exception { + store.put(tile(0, 0, 0)); + store.put(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)); + + store.deleteByGridsetId(LAYER, GRIDSET); + + assertFalse(store.get(tile(0, 0, 0))); + assertTrue(store.get(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0))); + } + + @Test + public void testDeleteParameters() throws Exception { + store.put(tile(0, 0, 0)); + store.put(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)); + store.put(tile(GRIDSET, STYLE_B, 0, 0, 0)); + + store.deleteByParameters(LAYER, STYLE_A); + + assertFalse(store.get(tile(0, 0, 0))); + assertFalse(store.get(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0))); + assertTrue(store.get(tile(GRIDSET, STYLE_B, 0, 0, 0))); + } + + @Test + public void testTruncateSucceedsOnEmptyStoreWithPassthroughOff() throws Exception { + // no parameters, so no mapping file and no layer directory in the store behind + store.put(tile(GRIDSET, null, 0, 0, 0)); + + assertTrue(store.deleteByGridsetId(LAYER, GRIDSET)); + assertFalse(store.get(tile(GRIDSET, null, 0, 0, 0))); + } + + @Test + public void testTileTruncatesSkipStoreWithPassthroughOff() throws Exception { + enableCache(true); + store.put(tile(0, 0, 1)); + enableCache(false); + + assertTrue(store.delete(tile(0, 0, 1))); + assertTrue(store.delete(range())); + assertTrue(store.deleteByGridsetId(LAYER, GRIDSET)); + + // the store behind was not called: the tile written before passthrough was turned off is still there + assertTrue(inStore(tile(0, 0, 1))); + assertTrue(mappingFile().exists()); + + // a layer truncate still reaches it, removing tiles and mappings + enableCache(false); + store.delete(LAYER); + assertFalse(inStore(tile(0, 0, 1))); + assertFalse(mappingFile().exists()); + } + + @Test + public void testDeleteTile() throws Exception { + store.put(tile(0, 0, 1)); + store.put(tile(1, 0, 1)); + + store.delete(tile(0, 0, 1)); + + assertFalse(store.get(tile(0, 0, 1))); + assertTrue(store.get(tile(1, 0, 1))); + } + + @Test + public void testDeleteRange() throws Exception { + store.put(tile(0, 0, 1)); + store.put(tile(1, 1, 1)); + store.put(tile(10, 10, 2)); + // a key that is not a tile, under a zoom level of the range + String tileKey = key(tile(0, 0, 1)); + String stray = tileKey.substring(0, tileKey.lastIndexOf('/') + 1) + "stray"; + kv.put(stray, new byte[] {1}, 300); + + assertTrue(store.delete(range())); + + // zoom 2 is outside the range, x 1 is outside its bounds at zoom 1 + assertFalse(store.get(tile(0, 0, 1))); + assertTrue(store.get(tile(1, 1, 1))); + assertTrue(store.get(tile(10, 10, 2))); + assertNull(kv.get(stray)); + } + + @Test + public void testReadResultsLogged() throws Exception { + memoryCacheInfo = null; + store.put(tile(0, 0, 0)); + enableCache(true); + expireCache = 10; + // written by a node whose clock is 60 s behind, so already past the layer's expire server cache + kv.put(key(tile(1, 0, 1)), cacheValue((byte) 1, System.currentTimeMillis() - 60_000), 300); + + store.get(tile(2, 0, 1)); + store.get(tile(0, 0, 0)); + store.get(tile(0, 0, 0)); + store.get(tile(1, 0, 1)); + kv.failing = true; + store.get(tile(0, 0, 0)); + + List results = + log.lines.stream().map(line -> line.split(" ")[3]).toList(); + assertThat(results, contains("miss", "store", "hit", "expired", "error")); + assertThat( + log.lines.get(0), + startsWith("In-memory tile cache miss for layer roads, gridset EPSG:4326, z/x/y 1/2/0 in ")); + } + + @Test + public void testReadThroughKeepsOnlyRemainingLifetime() throws Exception { + memoryCacheInfo = null; + long millis = System.currentTimeMillis(); + TileObject old = tile(0, 0, 0); + old.setCreated(millis - 60_000); + store.put(old); + TileObject recent = tile(1, 0, 1); + recent.setCreated(millis - 4_000); + store.put(recent); + enableCache(true); + expireCache = 10; + + assertTrue(store.get(tile(0, 0, 0))); + assertTrue(store.get(tile(1, 0, 1))); + + // the old tile is past the expire server cache, the recent one has at most 6 s left + assertNull(kv.get(key(tile(0, 0, 0)))); + assertNotNull(kv.get(key(tile(1, 0, 1)))); + now.addAndGet(SECONDS.toNanos(6)); + assertNull(kv.get(key(tile(1, 0, 1)))); + } + + @Test + public void testMappingWrittenOnceUntilTruncated() throws Exception { + store.put(tile(0, 0, 0)); + // listed, so that truncates by parameters can still find it + assertThat(store.getParametersMapping(LAYER), hasEntry(ParametersUtils.getId(STYLE_A), Optional.of(STYLE_A))); + assertTrue(mappingFile().delete()); + + store.put(tile(1, 0, 1)); + assertFalse(mappingFile().exists()); + + store.deleteByParameters(LAYER, STYLE_A); + store.put(tile(1, 0, 1)); + assertTrue(mappingFile().exists()); + + // a layer truncate forgets the mappings too + store.delete(LAYER); + store.put(tile(0, 0, 0)); + assertTrue(mappingFile().exists()); + } + + @Test + public void testConcurrentPutsWriteMappingOnce() throws Exception { + MappingCountingStore delegate = new MappingCountingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + List> puts = new ArrayList<>(); + for (int x = 0; x < 16; x++) { + TileObject tile = tile(x, 0, 4); + puts.add(executor.submit(() -> { + cached.put(tile); + return null; + })); + } + for (Future put : puts) put.get(); + + assertEquals(1, delegate.writes.get()); + } + + @Test + public void testFailedMappingWriteCachesTileAndRetries() throws Exception { + MappingCountingStore delegate = new MappingCountingStore(); + delegate.failing = true; + BlobStore cached = newCache().wrap(layer, delegate); + cached.put(tile(0, 0, 0)); + cached.put(tile(1, 0, 1)); + + // cached despite the store outage, which is logged once + assertTrue(cached.get(tile(0, 0, 0))); + assertEquals( + 1, + log.lines.stream().filter(l -> l.contains("could not record")).count()); + + delegate.failing = false; + cached.put(tile(1, 1, 1)); + + assertTrue(mappingFile().exists()); + assertThat(log.lines, hasItem("In-memory tile cache records parameter mappings in the blob stores again")); + } + + @Test + public void testMappingWrittenToNewStore() throws Exception { + MappingCountingStore previous = new MappingCountingStore(); + MappingCountingStore moved = new MappingCountingStore(); + try (MemoryCache cache = new MemoryCache(memoryCacheInfo, layers, ticker)) { + cache.wrap(layer, previous).put(tile(0, 0, 0)); + cache.wrap(layer, previous).put(tile(1, 0, 1)); + + // the layer moved to another store + blobStoreId = "moved"; + cache.wrap(layer, moved).put(tile(1, 1, 1)); + } + + assertEquals(1, previous.writes.get()); + assertEquals(1, moved.writes.get()); + } + + @Test + public void testTruncateOnOtherNodeRewritesMapping() throws Exception { + MappingCountingStore shared = new MappingCountingStore(); + // two nodes, sharing the cache and the blob store + try (MemoryCache node = new MemoryCache(memoryCacheInfo, layers, ticker); + MemoryCache other = new MemoryCache(memoryCacheInfo, layers, ticker)) { + node.wrap(layer, shared).put(tile(0, 0, 0)); + + other.wrap(layer, shared).deleteByParametersId(LAYER, ParametersUtils.getId(STYLE_A)); + node.wrap(layer, shared).put(tile(1, 0, 1)); + } + + // the first node learned of the removal from the cache, not from a local record + assertEquals(2, shared.writes.get()); + assertTrue(mappingFile().exists()); + } + + @Test + public void testFailedRemovalLeavesStoreUntouched() throws Exception { + enableCache(true); + store.put(tile(0, 0, 0)); + store.put(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)); + kv.failRemovals = true; + + StorageException e = assertThrows(StorageException.class, () -> store.deleteByGridsetId(LAYER, GRIDSET)); + + assertThat(e.getMessage(), containsString("not run, retry once it recovers")); + // nothing cleared in the cache, nothing truncated in the store + assertNotNull(kv.get(key(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)))); + assertTrue(inStore(tile(0, 0, 0))); + } + + @Test + public void testTruncateRefusedWhileDown() throws Exception { + enableCache(false); + BlobStore cached = newCache().wrap(layer, new MappingCountingStore()); + cached.put(tile(0, 0, 0)); + kv.failing = true; + cached.get(tile(0, 0, 0)); + int calls = kv.calls.get(); + + // with passthrough off the store holds no tiles, nothing to free + assertThrows(StorageException.class, () -> cached.delete(range())); + assertThrows(StorageException.class, () -> cached.delete(tile(0, 0, 0))); + + // refused before the cache + assertEquals(calls, kv.calls.get()); + kv.failing = false; + assertNotNull(kv.get(key(tile(0, 0, 0)))); + } + + @Test + public void testTileDeletesSkipCacheWhileDown() throws Exception { + enableCache(true); + MappingCountingStore delegate = new MappingCountingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + cached.put(tile(0, 0, 1)); + cached.put(tile(1, 1, 1)); + kv.failing = true; + + // disk quota deletes free the store during the outage + assertTrue(cached.delete(range())); + assertTrue(cached.delete(tile(1, 1, 1))); + + assertFalse(delegate.get(tile(0, 0, 1))); + assertFalse(delegate.get(tile(1, 1, 1))); + String message = "In-memory tile cache is unreachable, tile deletes of layer " + LAYER + + " run on the blob store only, cached copies are served until they expire"; + assertEquals(1, log.lines.stream().filter(message::equals).count()); + } + + @Test + public void testFailedLayerRemovalStillDeletesStore() throws Exception { + enableCache(true); + store.put(tile(0, 0, 0)); + kv.failing = true; + + // a removed layer cannot be truncated again, so its store goes anyway + assertThrows(StorageException.class, () -> store.delete(LAYER)); + + assertFalse(inStore(tile(0, 0, 0))); + } + + @Test + public void testRemovalFailingAfterStoreTruncateThrows() throws Exception { + enableCache(true); + PausingStore delegate = new PausingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + cached.put(tile(0, 0, 0)); + String otherLayer = "other-layer/" + GRIDSET + "/png/default/1/0/0.png"; + kv.put(otherLayer, new byte[] {1}, 300); + delegate.onTruncate = () -> kv.failRemovals = true; + + StorageException e = assertThrows(StorageException.class, () -> cached.delete(LAYER)); + + assertThat(e.getMessage(), containsString("may be stale until they expire")); + // no clear of the whole cache after the failure + kv.failRemovals = false; + assertNotNull(kv.get(otherLayer)); + } + + @Test + public void testDisabledCacheLeavesTilesToStore() throws Exception { + memoryCacheInfo = settings(new TestSettings(), true); + memoryCacheInfo.setEnabled(false); + store.put(tile(0, 0, 0)); + + enableCache(false); + assertFalse(store.get(tile(0, 0, 0))); + assertTrue(inStore(tile(0, 0, 0))); + } + + @Test + public void testLayerNotOptedInBypassesCache() throws Exception { + memoryCached = false; + store.put(tile(0, 0, 0)); + store.get(tile(0, 0, 0)); + store.delete(tile(0, 0, 0)); + + // tile calls never reach the cache, single tile deletes included + assertEquals(0, kv.calls.get()); + memoryCached = true; + assertFalse(store.get(tile(0, 0, 0))); + } + + @Test + public void testTruncateOfLayerNotOptedInClearsCache() throws Exception { + store.put(tile(0, 0, 0)); + // the layer stopped using the cache, or the node running the truncate does not see it using it yet + memoryCached = false; + + store.deleteByGridsetId(LAYER, GRIDSET); + + memoryCached = true; + assertFalse(store.get(tile(0, 0, 0))); + } + + @Test + public void testCacheFailureKeepsTruncateOfLayerNotOptedIn() throws Exception { + enableCache(true); + memoryCached = false; + store.put(tile(0, 0, 0)); + kv.failing = true; + + assertTrue(store.deleteByGridsetId(LAYER, GRIDSET)); + assertFalse(inStore(tile(0, 0, 0))); + } + + @Test + public void testOnlyChangedSettingsCloseStore() throws Exception { + store.put(tile(0, 0, 0)); + + // as a configuration reload with unchanged settings + memoryCacheInfo = settings(memoryCacheInfo.getBackend(), false); + store.get(tile(0, 0, 0)); + assertFalse(kv.closed); + + enableCache(false); + store.get(tile(0, 0, 0)); + assertTrue(kv.closed); + } + + @Test + public void testUninstalledBackendDropsTiles() throws Exception { + UnresolvedKeyValueStoreInfo removed = new UnresolvedKeyValueStoreInfo("removedTileCache", ""); + memoryCacheInfo = settings(removed, false); + + store.put(tile(0, 0, 0)); + + assertFalse(store.get(tile(0, 0, 0))); + assertFalse(inStore(tile(0, 0, 0))); + assertThat(stateLog.lines, hasItem("In-memory tile cache unusable, backend removedTileCache is not installed")); + } + + @Test + public void testUnusableCacheStillTruncatesStore() throws Exception { + memoryCacheInfo = settings(new UnresolvedKeyValueStoreInfo("removedTileCache", ""), true); + store.put(tile(0, 0, 0)); + + // the cache never held a tile, a failure there would fail every truncate until the settings change + assertTrue(store.deleteByGridsetId(LAYER, GRIDSET)); + assertFalse(inStore(tile(0, 0, 0))); + } + + @Test + public void testBackendLinkageErrorDropsTiles() throws Exception { + backendError = new NoClassDefFoundError("com/hazelcast/client/HazelcastClient"); + enableCache(false); + + store.put(tile(0, 0, 0)); + + assertFalse(store.get(tile(0, 0, 0))); + assertFalse(inStore(tile(0, 0, 0))); + assertThat(stateLog.lines, hasItem("In-memory tile cache unusable, could not create backend TestSettings")); + } + + @Test + public void testInvalidTimeToLiveDropsTiles() throws Exception { + memoryCacheInfo.setTimeToLive(-1); + + store.put(tile(0, 0, 0)); + + assertFalse(store.get(tile(0, 0, 0))); + assertFalse(inStore(tile(0, 0, 0))); + } + + @Test + public void testUnknownFormatVersionIsMiss() throws Exception { + kv.put(key(tile(0, 0, 0)), cacheValue((byte) 2, System.currentTimeMillis()), 300); + assertFalse(store.get(tile(0, 0, 0))); + + // truncated values, as written by a broken client, are misses too + kv.put(key(tile(0, 0, 0)), new byte[0], 300); + assertFalse(store.get(tile(0, 0, 0))); + kv.put(key(tile(0, 0, 0)), new byte[] {1, 0, 0}, 300); + assertFalse(store.get(tile(0, 0, 0))); + } + + @Test + public void testCallsSkippedWhileDown() throws Exception { + BlobStore cached = newCache().wrap(layer, new MappingCountingStore()); + kv.failing = true; + cached.get(tile(0, 0, 0)); + cached.put(tile(0, 0, 0)); + // a miss, as the write was dropped + assertFalse(cached.get(tile(0, 0, 0))); + assertEquals(1, kv.calls.get()); + + // after the first retry interval (1 s, plus jitter) one call probes, then calls flow again + kv.failing = false; + now.addAndGet(SECONDS.toNanos(2)); + cached.put(tile(0, 0, 0)); + assertTrue(cached.get(tile(0, 0, 0))); + } + + @Test + public void testOutageLoggedOncePerTransition() throws Exception { + BlobStore cached = newCache().wrap(layer, new MappingCountingStore()); + getAt(cached, 0, true); + getAt(cached, 0, true); + getAt(cached, 2, false); + getAt(cached, 2, false); + // failing again soon after the recovery continues the outage + getAt(cached, 3, true); + getAt(cached, 10, false); + // a recovery held for longer than the longest retry interval ends it + getAt(cached, 50, true); + + assertThat( + stateLog.lines, + contains( + "In-memory tile cache is unreachable, tiles are served without it until it recovers", + "In-memory tile cache is reachable again after 2 s", + "In-memory tile cache is unreachable again", + "In-memory tile cache is reachable again after 10 s", + "In-memory tile cache is unreachable, tiles are served without it until it recovers")); + } + + @Test + public void testReadThroughDuringTruncateDoesNotSurvive() throws Exception { + enableCache(true); + PausingStore delegate = new PausingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + delegate.put(tile(0, 0, 0)); + Future read = executor.submit(() -> cached.get(tile(0, 0, 0))); + assertTrue(delegate.paused.await(10, SECONDS)); + // the read caches its stale tile once the store is truncated, before the last cache removal + delegate.onTruncate = () -> { + delegate.resume.countDown(); + return read.get(10, SECONDS); + }; + + assertTrue(cached.delete(LAYER)); + assertTrue(read.get()); + assertNull(kv.get(key(tile(0, 0, 0)))); + } + + @Test + public void testReadThroughAfterTruncateExpires() throws Exception { + enableCache(true); + // longer than the time to live, which still bounds a tile read through + expireCache = 3600; + PausingStore delegate = new PausingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + delegate.put(tile(0, 0, 0)); + Future read = executor.submit(() -> cached.get(tile(0, 0, 0))); + assertTrue(delegate.paused.await(10, SECONDS)); + + assertTrue(cached.delete(LAYER)); + delegate.resume.countDown(); + assertTrue(read.get(10, SECONDS)); + + // the known window: a read of the store before its truncate, caching after the last removal, leaves a stale + // tile, served no longer than the time to live + assertNotNull(kv.get(key(tile(0, 0, 0)))); + now.set(SECONDS.toNanos(memoryCacheInfo.getTimeToLive() + 1)); + assertNull(kv.get(key(tile(0, 0, 0)))); + } + + @Test + public void testReadThroughKeepsNewerPut() throws Exception { + enableCache(true); + PausingStore delegate = new PausingStore(); + BlobStore cached = newCache().wrap(layer, delegate); + delegate.put(tile(0, 0, 0)); + Future read = executor.submit(() -> cached.get(tile(0, 0, 0))); + assertTrue(delegate.paused.await(10, SECONDS)); + + TileObject newer = tile(0, 0, 0); + newer.setBlob(new ByteArrayResource(new byte[] {4, 5, 6})); + cached.put(newer); + delegate.resume.countDown(); + assertTrue(read.get(10, SECONDS)); + + TileObject served = tile(0, 0, 0); + assertTrue(cached.get(served)); + assertArrayEquals(new byte[] {4, 5, 6}, ((ByteArrayResource) served.getBlob()).getContents()); + } + + @Test + public void testTruncateDuringSeedLeavesNoEarlierTile() throws Exception { + int seeders = 4; + AtomicBoolean truncating = new AtomicBoolean(); + AtomicBoolean done = new AtomicBoolean(); + Queue before = new ConcurrentLinkedQueue<>(); + CountDownLatch seeded = new CountDownLatch(seeders); + List> seeds = new ArrayList<>(); + for (int y = 0; y < seeders; y++) { + long row = y; + seeds.add(executor.submit(() -> { + // new tiles only, a tile written again after the truncate started may stay + for (long x = 0; !done.get(); x++) { + TileObject tile = tile(x, row, 10); + store.put(tile); + // false after the put returned: it ended before the truncate started + if (!truncating.get()) before.add(tile); + if (x == 50) seeded.countDown(); + } + return null; + })); + } + assertTrue(seeded.await(30, SECONDS)); + truncating.set(true); + long[][] bounds = {{0, 0, Integer.MAX_VALUE, seeders - 1, 10}}; + assertTrue(store.delete(new TileRange(LAYER, GRIDSET, 10, 10, bounds, ImageMime.png, STYLE_A))); + done.set(true); + for (Future seed : seeds) seed.get(30, SECONDS); + + List left = + before.stream().filter(tile -> kv.get(key(tile)) != null).toList(); + assertThat(left, empty()); + } + + @Test + public void testSettingsSaveWhileCacheHangsDoesNotStallTiles() throws Exception { + // every call waits, then fails, as with a hung member before the client gives up + kv.hangMillis = 500; + kv.failing = true; + List> requests = new ArrayList<>(); + for (int y = 0; y < 16; y++) { + long row = y; + requests.add(executor.submit(() -> { + for (long x = 0; x < 20; x++) store.get(tile(x, row, 10)); + return null; + })); + } + // the save: new settings rebuild the cache, the stores reload under the configLock write lock + enableCache(false); + requests.add(executor.submit(() -> { + store.setBlobStores(List.of()); + return null; + })); + + // calling the cache on every request, each thread would take 20 x 500 ms + await().atMost(5, SECONDS).until(() -> requests.stream().allMatch(Future::isDone)); + for (Future request : requests) request.get(); + } + + /** A cache with state of its own, as on another node, sharing {@link #kv}. */ + private MemoryCache newCache() { + MemoryCache cache = new MemoryCache(memoryCacheInfo, layers, ticker); + caches.add(cache); + return cache; + } + + private void getAt(BlobStore cached, long seconds, boolean failing) throws StorageException { + now.set(SECONDS.toNanos(seconds)); + kv.failing = failing; + cached.get(tile(0, 0, 0)); + } + + private void enableCache(boolean passthrough) { + memoryCacheInfo = settings(new TestSettings(), passthrough); + } + + private static MemoryCacheInfo settings(KeyValueStoreInfo backend, boolean passthrough) { + MemoryCacheInfo info = new MemoryCacheInfo(); + info.setEnabled(true); + info.setPassthrough(passthrough); + info.setBackend(backend); + return info; + } + + private boolean inStore(TileObject tile) throws StorageException { + memoryCacheInfo = null; + return store.get(tile); + } + + private String key(TileObject tile) { + return new TMSKeyBuilder(null, layers).forTile(tile); + } + + /** Zoom levels 0 and 1 of {@link #STYLE_A}, column and row 0 only. */ + private static TileRange range() { + long[][] bounds = {{0, 0, 0, 0, 0}, {0, 0, 0, 0, 1}}; + return new TileRange(LAYER, GRIDSET, 0, 1, bounds, ImageMime.png, STYLE_A); + } + + /** A cache entry for the tile content of {@link #tile}, as any node writes it. */ + private static byte[] cacheValue(byte version, long created) { + return ByteBuffer.allocate(Byte.BYTES + Long.BYTES + 3) + .put(version) + .putLong(created) + .put(new byte[] {1, 2, 3}) + .array(); + } + + /** The {@link #STYLE_A} mapping the file store keeps next to the layer's tiles. */ + private File mappingFile() { + String name = PARAMETERS_METADATA_OBJECT_PREFIX + ParametersUtils.getId(STYLE_A); + return new File(new File(temp.getRoot(), LAYER), name + PARAMETERS_METADATA_OBJECT_SUFFIX); + } + + private static TileObject tile(long x, long y, long z) { + return tile(GRIDSET, STYLE_A, x, y, z); + } + + private static TileObject tile(String gridset, Map parameters, long x, long y, long z) { + ByteArrayResource blob = new ByteArrayResource(new byte[] {1, 2, 3}); + return TileObject.createCompleteTileObject( + LAYER, new long[] {x, y, z}, gridset, ImageMime.png.getFormat(), parameters, blob); + } + + /** Fails every call, or only removals, on demand. */ + private static class FailingStore implements KeyValueStore { + + private final KeyValueStore delegate; + + volatile boolean failing; + + volatile boolean failRemovals; + + /** How long a failing call waits before it throws. */ + volatile long hangMillis; + + volatile boolean closed; + + final AtomicInteger calls = new AtomicInteger(); + + FailingStore(KeyValueStore delegate) { + this.delegate = delegate; + } + + private void check(boolean removal) { + calls.incrementAndGet(); + if (!failing && !(removal && failRemovals)) return; + sleep(hangMillis); + throw new IllegalStateException("Simulated cache failure"); + } + + @Override + public byte[] get(String key) { + check(false); + return delegate.get(key); + } + + @Override + public void put(String key, byte[] value, long ttlSeconds) { + check(false); + delegate.put(key, value, ttlSeconds); + } + + @Override + public void putIfAbsent(String key, byte[] value, long ttlSeconds) { + check(false); + delegate.putIfAbsent(key, value, ttlSeconds); + } + + @Override + public void remove(String key) { + check(true); + delegate.remove(key); + } + + @Override + public void removeByPrefix(String prefix) { + check(true); + delegate.removeByPrefix(prefix); + } + + @Override + public void removeMatching(String prefix, Predicate filter) { + check(true); + delegate.removeMatching(prefix, filter); + } + + @Override + public void clear() { + check(false); + delegate.clear(); + } + + @Override + public void close() { + closed = true; + delegate.close(); + } + } + + /** Counts mapping writes, slowed down so that concurrent puts overlap, and fails them on demand. */ + private class MappingCountingStore extends FileBlobStore { + + final AtomicInteger writes = new AtomicInteger(); + + volatile boolean failing; + + MappingCountingStore() throws StorageException { + super(temp.getRoot().getAbsolutePath()); + } + + @Override + public void putParametersMetadata(String layerName, String parametersId, Map parameters) + throws StorageException { + if (failing) throw new StorageException("Simulated mapping write failure"); + writes.incrementAndGet(); + sleep(50); + super.putParametersMetadata(layerName, parametersId, parameters); + } + } + + /** + * Reads the whole tile, as the S3 store does, then pauses until resumed, so that a truncate can run between the + * read and the cache write that follows it. + */ + private class PausingStore extends FileBlobStore { + + final CountDownLatch paused = new CountDownLatch(1); + + final CountDownLatch resume = new CountDownLatch(1); + + /** Runs after the layer truncate of the store, when set. */ + volatile Callable onTruncate; + + PausingStore() throws StorageException { + super(temp.getRoot().getAbsolutePath()); + } + + @Override + public boolean get(TileObject obj) throws StorageException { + if (!super.get(obj)) return false; + try (InputStream in = obj.getBlob().getInputStream()) { + obj.setBlob(new ByteArrayResource(in.readAllBytes())); + } catch (IOException e) { + throw new StorageException("Read failed", e); + } + // paused with the file closed: on Windows an open file blocks the rename that starts a layer truncate + paused.countDown(); + try { + if (!resume.await(10, SECONDS)) throw new StorageException("Read never resumed"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new StorageException("Read interrupted", e); + } + return true; + } + + @Override + public boolean delete(String layerName) throws StorageException { + boolean result = super.delete(layerName); + if (onTruncate == null) return result; + try { + onTruncate.call(); + } catch (Exception e) { + throw new StorageException("Truncate hook failed", e); + } + return result; + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** Thrown by {@link TestSettings#createStore} when set. */ + private Error backendError; + + /** Hands the shared {@link FailingStore} to every cache built from these settings. */ + private class TestSettings implements KeyValueStoreInfo { + + @Override + public KeyValueStore createStore() { + if (backendError != null) throw backendError; + return kv; + } + } +} diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/GuardedStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/GuardedStoreTest.java new file mode 100644 index 0000000000..dd94fc95b3 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/GuardedStoreTest.java @@ -0,0 +1,162 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.common.base.Ticker; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import org.geowebcache.storage.memorycache.GuardedStore.UnavailableException; +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; + +/** The outage state machine, on a store driven by a test ticker. */ +public class GuardedStoreTest { + + @Rule + public LogLines log = new LogLines(GuardedStore.class, Level.INFO); + + private final AtomicLong now = new AtomicLong(); + + private final Ticker ticker = new Ticker() { + @Override + public long read() { + return now.get(); + } + }; + + private final ExecutorService executor = Executors.newCachedThreadPool(); + + private final AtomicInteger calls = new AtomicInteger(); + + private final CountDownLatch entered = new CountDownLatch(1); + + private final CountDownLatch release = new CountDownLatch(1); + + private final List reports = new CopyOnWriteArrayList<>(); + + /** + * A heap store whose {@code get} fails on "fail" and waits for {@link #release} on "slow", counting the calls and + * recording the reachability reports. + */ + private final GuardedStore store = new GuardedStore( + new HeapKeyValueStore(1_000_000, ticker) { + @Override + public byte[] get(String key) { + calls.incrementAndGet(); + if (key.equals("fail")) throw new IllegalStateException("Simulated cache failure"); + if (key.equals("slow")) await(); + return super.get(key); + } + + @Override + public void reachable(boolean reachable) { + reports.add(reachable); + } + + private void await() { + entered.countDown(); + try { + assertTrue(release.await(10, SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }, + ticker); + + @After + public void stopExecutor() { + release.countDown(); + executor.shutdownNow(); + } + + @Test + public void testHungProbeLetsNextCallerProbe() throws Exception { + failAt(0); + // the probe, granted after the first retry interval (1 s plus jitter), never answers + now.set(SECONDS.toNanos(2)); + Future probe = executor.submit(() -> store.get("slow")); + assertTrue(entered.await(10, SECONDS)); + assertThrows(UnavailableException.class, () -> store.get("key")); + + // past the probe deadline the next caller probes, and its success ends the outage + now.set(SECONDS.toNanos(4)); + store.get("key"); + store.get("key"); + assertEquals(4, calls.get()); + release.countDown(); + probe.get(10, SECONDS); + } + + @Test + public void testCallStartedBeforeOutageReportsNothing() throws Exception { + Future old = executor.submit(() -> store.get("slow")); + assertTrue(entered.await(10, SECONDS)); + failAt(1); + + // the old call succeeding later does not end the outage + release.countDown(); + old.get(10, SECONDS); + assertThrows(UnavailableException.class, () -> store.get("key")); + assertEquals(2, calls.get()); + } + + @Test + public void testStateChangesReportedOnce() { + failAt(0); + assertThrows(UnavailableException.class, () -> store.get("key")); + // a failed probe leaves it unreachable, nothing new to report + now.set(SECONDS.toNanos(2)); + assertThrows(UnavailableException.class, () -> store.get("fail")); + + now.set(SECONDS.toNanos(10)); + store.get("key"); + store.get("key"); + + assertThat(reports, contains(false, true)); + } + + @Test + public void testUnusableNeverProbes() { + try (GuardedStore unusable = GuardedStore.unusable("backend missing is not installed", null)) { + now.set(SECONDS.toNanos(60)); + for (int i = 0; i < 3; i++) assertThrows(UnavailableException.class, () -> unusable.get("key")); + + assertTrue(unusable.isUnusable()); + } + // logged once on creation, no outage + assertThat(log.lines, contains("In-memory tile cache unusable, backend missing is not installed")); + } + + /** A failing call at {@code seconds}, starting an outage. */ + private void failAt(long seconds) { + now.set(SECONDS.toNanos(seconds)); + assertThrows(UnavailableException.class, () -> store.get("fail")); + } +} diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreTest.java new file mode 100644 index 0000000000..4e7f241296 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreTest.java @@ -0,0 +1,72 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertNull; + +import com.google.common.base.Ticker; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.IntStream; +import org.junit.Test; + +public class HeapKeyValueStoreTest extends AbstractKeyValueStoreTest { + + private final AtomicLong now = new AtomicLong(); + + private final Ticker ticker = new Ticker() { + @Override + public long read() { + return now.get(); + } + }; + + @Override + protected KeyValueStore createStore() { + return new HeapKeyValueStore(1000, ticker); + } + + @Test + public void testPerEntryExpiry() { + store.put("short", new byte[] {1}, 10); + store.put("long", new byte[] {2}, 100); + + now.addAndGet(TimeUnit.SECONDS.toNanos(10)); + + assertNull(store.get("short")); + assertArrayEquals(new byte[] {2}, store.get("long")); + } + + @Test + public void testPutIfAbsentReplacesExpiredValue() { + store.put("key", new byte[] {1}, 10); + now.addAndGet(TimeUnit.SECONDS.toNanos(10)); + + store.putIfAbsent("key", new byte[] {2}, 10); + + assertArrayEquals(new byte[] {2}, store.get("key")); + } + + @Test + public void testWeightBound() { + IntStream.range(0, 20).forEach(i -> store.put("k" + i, new byte[100], 300)); + + long present = + IntStream.range(0, 20).filter(i -> store.get("k" + i) != null).count(); + assertThat(present, lessThanOrEqualTo(10L)); + } +} diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/LogLines.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/LogLines.java new file mode 100644 index 0000000000..49acf93378 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/LogLines.java @@ -0,0 +1,66 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import org.junit.rules.ExternalResource; + +/** Collects the messages one class logs at {@code level} and above during a test. */ +class LogLines extends ExternalResource { + + final List lines = new CopyOnWriteArrayList<>(); + + // a strong reference, java.util.logging forgets the level of a logger nobody holds + private final Logger logger; + + private final Level level; + + private Level previous; + + private final Handler handler = new Handler() { + @Override + public void publish(LogRecord record) { + lines.add(record.getMessage()); + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + + LogLines(Class type, Level level) { + this.logger = Logger.getLogger(type.getName()); + this.level = level; + } + + @Override + protected void before() { + previous = logger.getLevel(); + logger.setLevel(level); + logger.addHandler(handler); + } + + @Override + protected void after() { + logger.removeHandler(handler); + logger.setLevel(previous); + } +} diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/MemoryCacheStatsTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/MemoryCacheStatsTest.java new file mode 100644 index 0000000000..a04538d148 --- /dev/null +++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/MemoryCacheStatsTest.java @@ -0,0 +1,109 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.storage.memorycache; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.HIT; +import static org.geowebcache.storage.memorycache.MemoryCacheStats.Result.MISS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import com.google.common.base.Ticker; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import org.geowebcache.storage.memorycache.MemoryCacheStats.LayerStats; +import org.junit.Rule; +import org.junit.Test; + +public class MemoryCacheStatsTest { + + @Rule + public LogLines log = new LogLines(MemoryCacheStats.class, Level.INFO); + + private final AtomicLong now = new AtomicLong(); + + private final MemoryCacheStats stats = new MemoryCacheStats(300, new Ticker() { + @Override + public long read() { + return now.get(); + } + }); + + @Test + public void testReportOncePerInterval() { + LayerStats roads = stats.forLayer("roads"); + roads.read(HIT); + roads.read(HIT); + roads.read(HIT); + roads.read(MISS); + roads.failedPut(); + + stats.report(); + assertThat(log.lines, empty()); + + now.addAndGet(SECONDS.toNanos(300)); + stats.report(); + stats.report(); + assertThat( + log.lines, + contains("In-memory tile cache stats for layer roads over 300 s: 4 reads (hit 3, store 0, miss 1," + + " expired 0, error 0), hit ratio 75.0%, 1 failed puts")); + } + + @Test + public void testReportResetsCountersAndSkipsIdleLayers() { + stats.forLayer("roads").read(HIT); + stats.forLayer("rivers").read(MISS); + now.addAndGet(SECONDS.toNanos(300)); + stats.report(); + log.lines.clear(); + + stats.forLayer("roads").read(MISS); + now.addAndGet(SECONDS.toNanos(400)); + stats.report(); + + assertThat( + log.lines, + contains("In-memory tile cache stats for layer roads over 400 s: 1 reads (hit 0, store 0, miss 1," + + " expired 0, error 0), hit ratio 0.0%, 0 failed puts")); + } + + @Test + public void testIdleLayerDropped() { + LayerStats removed = stats.forLayer("removed"); + removed.read(HIT); + now.addAndGet(SECONDS.toNanos(300)); + stats.report(); + assertSame(removed, stats.forLayer("removed")); + + // a whole interval without traffic, as for a removed or renamed layer + now.addAndGet(SECONDS.toNanos(300)); + stats.report(); + + assertNotSame(removed, stats.forLayer("removed")); + } + + @Test + public void testZeroIntervalNeverReports() { + MemoryCacheStats off = new MemoryCacheStats(0, Ticker.systemTicker()); + off.forLayer("roads").read(HIT); + + off.report(); + + assertThat(log.lines, empty()); + } +} diff --git a/geowebcache/gcsblob/src/main/java/org/geowebcache/storage/blobstore/gcs/GoogleCloudStorageBlobStore.java b/geowebcache/gcsblob/src/main/java/org/geowebcache/storage/blobstore/gcs/GoogleCloudStorageBlobStore.java index 4eba498d06..758d899fc7 100644 --- a/geowebcache/gcsblob/src/main/java/org/geowebcache/storage/blobstore/gcs/GoogleCloudStorageBlobStore.java +++ b/geowebcache/gcsblob/src/main/java/org/geowebcache/storage/blobstore/gcs/GoogleCloudStorageBlobStore.java @@ -386,7 +386,8 @@ private String getMimeType(TileObject obj) { */ private Map existingParametersMedatata = new ConcurrentHashMap<>(); - void putParametersMetadata(String layerName, String parametersId, Map parameters) { + @Override + public void putParametersMetadata(String layerName, String parametersId, Map parameters) { assert (isNull(parametersId) == isNull(parameters)); if (isNull(parametersId)) { return; diff --git a/geowebcache/hazelcast/pom.xml b/geowebcache/hazelcast/pom.xml new file mode 100644 index 0000000000..d97fd5809d --- /dev/null +++ b/geowebcache/hazelcast/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + org.geowebcache + geowebcache + 1.28-SNAPSHOT + + + + org.geowebcache + gwc-hazelcast + + + + org.geowebcache + gwc-core + ${project.version} + + + com.hazelcast + hazelcast + ${hazelcast.version} + + + + org.geowebcache + gwc-core + tests + test + + + org.awaitility + awaitility + test + + + diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientConnection.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientConnection.java new file mode 100644 index 0000000000..9cd3a6a19c --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientConnection.java @@ -0,0 +1,161 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.client.config.ClientConnectionStrategyConfig; +import com.hazelcast.client.config.ClientConnectionStrategyConfig.ReconnectMode; +import com.hazelcast.client.config.ConnectionRetryConfig; +import com.hazelcast.client.config.XmlClientConfigBuilder; +import com.hazelcast.client.properties.ClientProperty; +import com.hazelcast.core.HazelcastInstance; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.logging.Logger; +import org.geotools.util.logging.Logging; +import org.geowebcache.config.ConfigurationResourceProvider; +import org.geowebcache.hazelcast.HazelcastLockProvider.Target; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.springframework.beans.factory.DisposableBean; + +/** + * Hazelcast client shared by the stores of {@link HazelcastClientKeyValueStoreInfo} and shut down with the application + * context, so connection settings apply on restart, the map name on save. + */ +public class HazelcastClientConnection implements DisposableBean { + + private static final Logger LOGGER = Logging.getLogger(HazelcastClientConnection.class.getName()); + + /** Shortest wait between two client rebuilds, as lock calls reach {@link #running} without the cache backoff. */ + private static final long REBUILD_INTERVAL_MILLIS = 30_000; + + private final ConfigurationResourceProvider clientXml; + + /** The configuration of the first client, reused by its rebuilds, as connection settings apply on restart. */ + private ClientConfig config; + + /** Null until the first store and once destroyed. Written under the lock only. */ + private volatile HazelcastInstance client; + + /** Epoch millis before which a stopped client is not rebuilt. */ + private long rebuildAfter; + + private HazelcastLockProvider lockProvider; + + /** + * Connects as {@code clientXml} says when it exists, replacing every connection setting of + * {@link HazelcastClientKeyValueStoreInfo}; async start, async reconnect and unlimited connection retry are always + * enforced. + */ + public HazelcastClientConnection(ConfigurationResourceProvider clientXml) { + this.clientXml = clientXml; + } + + /** + * Returns a store on the shared client, connecting first if needed. A client that shut down, for example when the + * cluster rejected it, is replaced on a later call. + */ + synchronized KeyValueStore createStore(HazelcastClientKeyValueStoreInfo settings) { + if (client == null) { + config = clientConfig(settings); + client = HazelcastClient.newHazelcastClient(config); + } + String mapName = settings.getMapName(); + // closed when the cache settings change, so a switch to another backend stops the cluster locks + Target locks = lockProvider == null ? null : lockProvider.lockOn(this::running, mapName); + return new HazelcastKeyValueStore(this::running, mapName, locks); + } + + /** The running client; lock free on this path, as every cache call goes through it. */ + private HazelcastInstance running() { + HazelcastInstance current = client; + if (current == null) throw new IllegalStateException("Hazelcast client shut down"); + // retrying forever, a client only stops when the cluster rejects it or on an internal error + if (current.getLifecycleService().isRunning()) return current; + rebuild(current); + throw new IllegalStateException("Hazelcast client stopped, connecting again"); + } + + /** Replaces {@code stopped} unless another call already did, the backend was destroyed, or it is too soon. */ + private synchronized void rebuild(HazelcastInstance stopped) { + long now = System.currentTimeMillis(); + if (client != stopped || now < rebuildAfter) return; + rebuildAfter = now + REBUILD_INTERVAL_MILLIS; + LOGGER.warning("Hazelcast tile cache client stopped, starting a new one"); + client = HazelcastClient.newHazelcastClient(config); + } + + /** Makes {@code lockProvider} lock on the client of the stores created from now on. */ + public synchronized void setLockProvider(HazelcastLockProvider lockProvider) { + this.lockProvider = lockProvider; + } + + /** The client configuration, with the tile cache defaults filled in where the file leaves Hazelcast's own. */ + ClientConfig clientConfig(HazelcastClientKeyValueStoreInfo settings) { + ClientConfig config = clientXml.hasInput() ? readClientXml() : fromSettings(settings); + + // cache calls run under the blob store lock, give up in seconds instead of the default 120 + String timeout = ClientProperty.INVOCATION_TIMEOUT_SECONDS.getName(); + if (config.getProperty(timeout) == null) config.setProperty(timeout, "5"); + + // members drop backup acks for a client not connected to them, which then waits 5 s for each write, past the + // call timeout: have the owner member collect the acks instead, always, as the file cannot tell it was unset + config.setBackupAckToClientEnabled(false); + + // connect in the background and fail calls while offline, the cache is built under the blob store lock + ClientConnectionStrategyConfig strategy = config.getConnectionStrategyConfig(); + strategy.setAsyncStart(true).setReconnectMode(ReconnectMode.ASYNC); + + // a client whose connect timeout runs out shuts down for good, -1 retries forever + ConnectionRetryConfig retry = strategy.getConnectionRetryConfig(); + if (retry.getClusterConnectTimeoutMillis() != -1) { + LOGGER.warning("Ignoring the cluster-connect-timeout of the Hazelcast client configuration," + + " the tile cache client retries forever"); + } + retry.setClusterConnectTimeoutMillis(-1); + + // Hazelcast's multiplier 1.05 without jitter has every node retry in lockstep, kept only when the file sets it + ConnectionRetryConfig defaults = new ConnectionRetryConfig(); + if (retry.getMultiplier() == defaults.getMultiplier()) retry.setMultiplier(2); + if (retry.getJitter() == defaults.getJitter()) retry.setJitter(0.2); + return config; + } + + private ClientConfig readClientXml() { + try (InputStream in = clientXml.in()) { + return new XmlClientConfigBuilder(in).build(); + } catch (IOException e) { + throw new UncheckedIOException("Could not read the Hazelcast client configuration", e); + } + } + + private static ClientConfig fromSettings(HazelcastClientKeyValueStoreInfo settings) { + ClientConfig config = new ClientConfig(); + config.setClusterName(settings.getClusterName()); + config.getNetworkConfig().setAddresses(List.of(settings.getMembers().split("\\s*,\\s*"))); + // retry writes cut by a member leaving too, as reads are: puts and removals can safely run twice + config.getNetworkConfig().setRedoOperation(true); + return config; + } + + /** Shuts the shared client down; stores still using it fail their calls. */ + @Override + public synchronized void destroy() { + if (client != null) client.shutdown(); + client = null; + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientKeyValueStoreInfo.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientKeyValueStoreInfo.java new file mode 100644 index 0000000000..e755100475 --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastClientKeyValueStoreInfo.java @@ -0,0 +1,97 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import java.io.Serial; +import java.util.Objects; +import org.geowebcache.GeoWebCacheExtensions; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.geowebcache.storage.memorycache.KeyValueStoreInfo; + +/** Settings of a store in a Hazelcast cluster reached as a client; an absent element reads as its default. */ +public class HazelcastClientKeyValueStoreInfo implements KeyValueStoreInfo { + + @Serial + private static final long serialVersionUID = 1L; + + static final String DEFAULT_CLUSTER_NAME = "gwc"; + + static final String DEFAULT_MEMBERS = "localhost:5701"; + + static final String DEFAULT_MAP_NAME = "gwc-tiles"; + + private String clusterName; + + private String members; + + private String mapName; + + /** Name of the cluster to join, "gwc" by default, as in the embedded backend example. */ + public String getClusterName() { + return clusterName == null ? DEFAULT_CLUSTER_NAME : clusterName; + } + + /** Sets the name of the cluster to join. */ + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + /** Comma separated {@code host:port} list of members to connect to, "localhost:5701" by default. */ + public String getMembers() { + return members == null ? DEFAULT_MEMBERS : members; + } + + /** Sets the comma separated {@code host:port} list of members to connect to. */ + public void setMembers(String members) { + this.members = members; + } + + /** Name of the map holding the tiles, declared on the cluster; "gwc-tiles" by default. */ + public String getMapName() { + return mapName == null ? DEFAULT_MAP_NAME : mapName; + } + + /** Sets the name of the map holding the tiles. */ + public void setMapName(String mapName) { + this.mapName = mapName; + } + + /** + * Returns a store on the client shared by the application context, connecting first if needed. + * + * @throws IllegalStateException when the context has no {@link HazelcastClientConnection} + */ + @Override + public KeyValueStore createStore() { + HazelcastClientConnection connection = GeoWebCacheExtensions.bean(HazelcastClientConnection.class); + if (connection == null) { + throw new IllegalStateException("No Hazelcast client connection in the application context"); + } + return connection.createStore(this); + } + + /** Equal when the effective settings are, an absent value matching its default. */ + @Override + public boolean equals(Object o) { + return o instanceof HazelcastClientKeyValueStoreInfo other + && getClusterName().equals(other.getClusterName()) + && getMembers().equals(other.getMembers()) + && getMapName().equals(other.getMapName()); + } + + @Override + public int hashCode() { + return Objects.hash(getClusterName(), getMembers(), getMapName()); + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedKeyValueStoreInfo.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedKeyValueStoreInfo.java new file mode 100644 index 0000000000..ef42877626 --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedKeyValueStoreInfo.java @@ -0,0 +1,63 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import java.io.Serial; +import org.geowebcache.GeoWebCacheExtensions; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.geowebcache.storage.memorycache.KeyValueStoreInfo; + +/** Settings of a store in a Hazelcast cluster this node is a member of; an absent element reads as its default. */ +public class HazelcastEmbeddedKeyValueStoreInfo implements KeyValueStoreInfo { + + @Serial + private static final long serialVersionUID = 1L; + + private String mapName; + + /** Name of the map holding the tiles, declared in {@code hazelcast.xml}; "gwc-tiles" by default. */ + public String getMapName() { + return mapName == null ? HazelcastClientKeyValueStoreInfo.DEFAULT_MAP_NAME : mapName; + } + + /** Sets the name of the map holding the tiles. */ + public void setMapName(String mapName) { + this.mapName = mapName; + } + + /** + * Returns a store on the member shared by the application context, starting it first if needed. + * + * @throws IllegalStateException when the context has no {@link HazelcastEmbeddedMember}, or when + * {@code hazelcast.xml} is missing or does not declare the map + */ + @Override + public KeyValueStore createStore() { + HazelcastEmbeddedMember member = GeoWebCacheExtensions.bean(HazelcastEmbeddedMember.class); + if (member == null) throw new IllegalStateException("No embedded Hazelcast member in the application context"); + return member.createStore(this); + } + + /** Equal when the effective settings are, an absent value matching its default. */ + @Override + public boolean equals(Object o) { + return o instanceof HazelcastEmbeddedKeyValueStoreInfo other + && getMapName().equals(other.getMapName()); + } + + @Override + public int hashCode() { + return getMapName().hashCode(); + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedMember.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedMember.java new file mode 100644 index 0000000000..92a2011566 --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastEmbeddedMember.java @@ -0,0 +1,145 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import com.hazelcast.config.Config; +import com.hazelcast.config.XmlConfigBuilder; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.Executor; +import java.util.logging.Logger; +import org.geotools.util.logging.Logging; +import org.geowebcache.config.ConfigurationResourceProvider; +import org.geowebcache.hazelcast.HazelcastLockProvider.Target; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.springframework.beans.factory.DisposableBean; + +/** + * Hazelcast member making this node part of the cluster configured by {@code hazelcast.xml}, shared by the stores of + * {@link HazelcastEmbeddedKeyValueStoreInfo} and shut down with the application context, so the file applies on + * restart. + */ +public class HazelcastEmbeddedMember implements DisposableBean { + + private static final Logger LOGGER = Logging.getLogger(HazelcastEmbeddedMember.class.getName()); + + /** Shortest wait between two member starts, as lock calls reach {@link #running} without the cache backoff. */ + private static final long RESTART_INTERVAL_MILLIS = 30_000; + + /** One short-lived daemon thread per member start, at most one every {@link #RESTART_INTERVAL_MILLIS}. */ + private static final Executor START = task -> { + Thread thread = new Thread(task, "gwc-hazelcast-member-start"); + thread.setDaemon(true); + thread.start(); + }; + + private final ConfigurationResourceProvider memberXml; + + /** The member configuration, read once. */ + private Config config; + + /** The member, joining its cluster in the background; null once destroyed. Written under the lock only. */ + private volatile CompletableFuture member; + + /** Epoch millis before which a failed or stopped member is not started again. */ + private long restartAfter; + + private HazelcastLockProvider lockProvider; + + /** Starts the member from {@code memberXml}, which must exist and declare the tile map. */ + public HazelcastEmbeddedMember(ConfigurationResourceProvider memberXml) { + this.memberXml = memberXml; + } + + /** + * Returns a store on the member, starting it first if needed. Returns at once: the store fails its calls until the + * member has joined its cluster, and a member that failed to start or stopped is started again on the next call. + * + * @throws IllegalStateException when the file is missing or does not declare the map + */ + synchronized KeyValueStore createStore(HazelcastEmbeddedKeyValueStoreInfo settings) { + String mapName = settings.getMapName(); + if (config == null) config = memberConfig(); + // an undeclared map would get the defaults: no eviction, no size bound, tiles filling the heap of every node + if (config.getMapConfigOrNull(mapName) == null) { + throw new IllegalStateException("Map " + mapName + " is not declared in hazelcast.xml in " + + memberXml.getId() + ", declare it with eviction and a maximum size"); + } + if (member == null) start(); + // closed when the cache settings change, so a switch to another backend stops the cluster locks + Target locks = lockProvider == null ? null : lockProvider.lockOn(this::running, mapName); + return new HazelcastKeyValueStore(this::running, mapName, locks); + } + + /** Makes {@code lockProvider} lock on the member of the stores created from now on. */ + public synchronized void setLockProvider(HazelcastLockProvider lockProvider) { + this.lockProvider = lockProvider; + } + + /** Starts the member on its own thread, as joining takes seconds and callers hold the blob store lock. */ + private void start() { + member = CompletableFuture.supplyAsync(() -> Hazelcast.newHazelcastInstance(config), START); + } + + /** The joined member; lock free on this path, as every cache call goes through it. */ + private HazelcastInstance running() { + CompletableFuture current = member; + if (current == null) throw new IllegalStateException("Embedded Hazelcast member shut down"); + if (!current.isDone()) throw new IllegalStateException("Embedded Hazelcast member still joining"); + HazelcastInstance joined; + try { + joined = current.join(); + } catch (CompletionException e) { + restart(current); + throw new IllegalStateException("Embedded Hazelcast member failed to start, starting again", e.getCause()); + } + // stopped by an out of memory error, or by a cluster shutdown from another member + if (joined.getLifecycleService().isRunning()) return joined; + restart(current); + throw new IllegalStateException("Embedded Hazelcast member stopped, starting again"); + } + + /** Starts a new member unless another call already did, the member was destroyed, or it is too soon. */ + private synchronized void restart(CompletableFuture failed) { + long now = System.currentTimeMillis(); + if (member != failed || now < restartAfter) return; + restartAfter = now + RESTART_INTERVAL_MILLIS; + LOGGER.warning("Embedded Hazelcast member failed to start or stopped, starting a new one"); + start(); + } + + private Config memberConfig() { + if (!memberXml.hasInput()) { + throw new IllegalStateException( + "The embedded Hazelcast tile cache needs hazelcast.xml in " + memberXml.getId() + ", none found"); + } + try (InputStream in = memberXml.in()) { + return new XmlConfigBuilder(in).build(); + } catch (IOException e) { + throw new UncheckedIOException("Could not read hazelcast.xml in " + memberXml.getId(), e); + } + } + + /** Shuts the member down, leaving the cluster, or once it has joined if still joining; stores fail their calls. */ + @Override + public synchronized void destroy() { + if (member != null) member.thenAccept(HazelcastInstance::shutdown); + member = null; + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStore.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStore.java new file mode 100644 index 0000000000..8530dbeefa --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStore.java @@ -0,0 +1,330 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.google.common.collect.Lists; +import com.hazelcast.aggregation.Aggregators; +import com.hazelcast.cluster.Member; +import com.hazelcast.config.IndexType; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.OperationTimeoutException; +import com.hazelcast.map.IMap; +import com.hazelcast.query.Predicates; +import com.hazelcast.query.QueryConstants; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import org.geotools.util.logging.Logging; +import org.geowebcache.GeoWebCacheExtensions; +import org.geowebcache.hazelcast.HazelcastLockProvider.Target; +import org.geowebcache.storage.memorycache.KeyValueStore; + +/** {@link KeyValueStore} over one Hazelcast map shared by every node; the map and its client outlive {@link #close}. */ +public class HazelcastKeyValueStore implements KeyValueStore { + + private static final String KEY = QueryConstants.KEY_ATTRIBUTE_NAME.value(); + + private static final Logger LOGGER = Logging.getLogger(HazelcastKeyValueStore.class.getName()); + + /** Keys per removeAll call, so one bounding box truncate does not build a single huge request. */ + static final int REMOVE_BATCH = 1000; + + /** Keys {@link #removeMatching} reads back at most, about 10-20 MB on this node. */ + static final long MATCHING_LIMIT = 100_000; + + /** System property, web.xml parameter or environment variable replacing {@link #MATCHING_LIMIT}. */ + static final String MATCHING_LIMIT_PROPERTY = "GWC_MEMORYCACHE_MATCHING_LIMIT"; + + /** Milliseconds a tile read or write waits for the cluster before failing. */ + static final long CALL_TIMEOUT = 2000; + + /** System property, web.xml parameter or environment variable replacing {@link #CALL_TIMEOUT}. */ + static final String CALL_TIMEOUT_PROPERTY = "GWC_MEMORYCACHE_CALL_TIMEOUT"; + + /** Milliseconds a truncate or clear call waits for the cluster before failing, long enough for a large removal. */ + static final long BULK_TIMEOUT = 10_000; + + /** System property, web.xml parameter or environment variable replacing {@link #BULK_TIMEOUT}. */ + static final String BULK_TIMEOUT_PROPERTY = "GWC_MEMORYCACHE_BULK_TIMEOUT"; + + /** Bulk calls running at once per store, a few truncates; more are refused, failing at once. */ + static final int BULK_THREADS = 4; + + /** Read through copies written at once per store; more are skipped, as all threads waiting means a stall. */ + static final int PUT_THREADS = 16; + + private final Supplier instance; + + private final String mapName; + + private final long matchingLimit; + + private final long callTimeout; + + private final long bulkTimeout; + + /** Runs the bulk calls, which have no asynchronous variant, so that their caller can stop waiting. */ + private final ExecutorService bulkPool; + + /** Runs {@link #putIfAbsent}, which has no asynchronous variant either. */ + private final ExecutorService putPool; + + /** The cluster locks following this store, null without a lock provider. */ + @Nullable + private final Target locks; + + /** Members seen when the index was last checked; the index lives on while one of them does. */ + private volatile Set indexedOn = Set.of(); + + /** Whether a bounding box truncate was widened already, so that only the first one logs a warning. */ + private final AtomicBoolean widened = new AtomicBoolean(); + + /** Whether adding the key index failed since it last succeeded, so that a failing index logs one warning. */ + private final AtomicBoolean indexFailing = new AtomicBoolean(); + + /** + * Stores in the named map; never contacts the cluster, so it can be built while the cluster is down. Calls fail + * with the exception {@code instance} throws while the instance is not ready. Its reachability is passed on to + * {@code locks}, which {@link #close} stops. + */ + public HazelcastKeyValueStore(Supplier instance, String mapName, @Nullable Target locks) { + this( + instance, + mapName, + property(MATCHING_LIMIT_PROPERTY, MATCHING_LIMIT, 0), + property(CALL_TIMEOUT_PROPERTY, CALL_TIMEOUT, 1), + property(BULK_TIMEOUT_PROPERTY, BULK_TIMEOUT, 1), + locks); + } + + /** The value of {@code name}, {@code fallback} when unset, not a number or below {@code min}. */ + private static long property(String name, long fallback, long min) { + String value = GeoWebCacheExtensions.getProperty(name); + if (value == null) return fallback; + long parsed; + try { + parsed = Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + parsed = min - 1; + } + if (parsed >= min) return parsed; + LOGGER.warning("Ignoring " + name + " " + value + ", not a number >= " + min); + return fallback; + } + + HazelcastKeyValueStore( + Supplier instance, + String mapName, + long matchingLimit, + long callTimeout, + long bulkTimeout, + @Nullable Target locks) { + this.instance = instance; + this.mapName = mapName; + this.matchingLimit = matchingLimit; + this.callTimeout = callTimeout; + this.bulkTimeout = bulkTimeout; + this.locks = locks; + this.bulkPool = pool(BULK_THREADS, "gwc-hazelcast-bulk"); + this.putPool = pool(PUT_THREADS, "gwc-hazelcast-put"); + } + + /** Up to {@code threads} daemon threads, refusing a task when all are busy. */ + private static ExecutorService pool(int threads, String name) { + // no queue: a call waiting for a thread would only use up its deadline + return new ThreadPoolExecutor(0, threads, 60, SECONDS, new SynchronousQueue<>(), task -> { + Thread thread = new Thread(task, name); + thread.setDaemon(true); + return thread; + }); + } + + /** The first lookup creates the map on the cluster and fails while offline, later ones return the cached proxy. */ + private IMap map() { + return instance.get().getMap(mapName); + } + + /** + * {@inheritDoc} Fails after {@link #CALL_TIMEOUT_PROPERTY} milliseconds, so a stalled member reads as an outage. + */ + @Override + public byte[] get(String key) { + return await(map().getAsync(key), callTimeout); + } + + /** {@inheritDoc} Fails after {@link #CALL_TIMEOUT_PROPERTY} milliseconds; the write may still land later. */ + @Override + public void put(String key, byte[] value, long ttlSeconds) { + // set does not return the previous value, put would send it back over the wire + await(map().setAsync(key, value, ttlSeconds, SECONDS), callTimeout); + } + + /** + * {@inheritDoc} Fails after {@link #CALL_TIMEOUT_PROPERTY} milliseconds; the write may still land later. Skipped + * without failing while {@link #PUT_THREADS} earlier ones still wait for the cluster. + */ + @Override + public void putIfAbsent(String key, byte[] value, long ttlSeconds) { + IMap map = map(); + CompletableFuture call; + try { + // returns the value already there over the wire, no variant goes without it + call = CompletableFuture.supplyAsync(() -> map.putIfAbsent(key, value, ttlSeconds, SECONDS), putPool); + } catch (RejectedExecutionException e) { + // a read through copy is optional: a later request reads the tile through again + return; + } + await(call, callTimeout); + } + + // the client invocation timeout only bounds retries after an error: a connected member that does not answer + // keeps a synchronous call waiting until the heartbeat timeout, 60 s by default, under the blob store lock + private static T await(CompletionStage call, long timeout) { + try { + return call.toCompletableFuture().get(timeout, MILLISECONDS); + } catch (TimeoutException e) { + throw new OperationTimeoutException("In-memory tile cache call got no answer in " + timeout + " ms"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for the in-memory tile cache", e); + } catch (ExecutionException e) { + if (e.getCause() instanceof RuntimeException cause) throw cause; + throw new IllegalStateException(e.getCause()); + } + } + + /** {@inheritDoc} Fails after {@link #CALL_TIMEOUT_PROPERTY} milliseconds; the removal may still land later. */ + @Override + public void remove(String key) { + // sends the old tile back over the wire, deleteAsync avoids it but is missing in Hazelcast 5.3 + await(map().removeAsync(key), callTimeout); + } + + /** {@inheritDoc} Each cluster call fails after {@link #BULK_TIMEOUT_PROPERTY} milliseconds. */ + @Override + public void removeByPrefix(String prefix) { + IMap map = indexedMap(); + bulk(() -> map.removeAll(keyRange(prefix))); + } + + /** Runs {@code call} on the bulk pool, failing after {@link #BULK_TIMEOUT_PROPERTY} milliseconds. */ + private void bulk(Runnable call) { + await(CompletableFuture.runAsync(call, bulkPool), bulkTimeout); + } + + /** Returns what {@code call} returns, run on the bulk pool and failing after {@link #BULK_TIMEOUT_PROPERTY}. */ + private T bulkGet(Supplier call) { + return await(CompletableFuture.supplyAsync(call, bulkPool), bulkTimeout); + } + + /** + * {@inheritDoc} Removes the whole prefix when it holds more keys than {@link #MATCHING_LIMIT_PROPERTY} allows. Each + * cluster call fails after {@link #BULK_TIMEOUT_PROPERTY} milliseconds. + */ + @Override + public void removeMatching(String prefix, Predicate remove) { + IMap map = indexedMap(); + var range = keyRange(prefix); + // keys are read back to this node: past the limit, their memory costs more than re-rendering extra tiles + long count = bulkGet(() -> map.aggregate(Aggregators.count(), range)); + if (count > matchingLimit) { + bulk(() -> map.removeAll(range)); + String message = "In-memory tile cache removed all the " + count + " tiles under " + prefix + + " instead of the requested ones, as they are more than " + matchingLimit + " (" + + MATCHING_LIMIT_PROPERTY + ")"; + // a warning the first time, as production logging hides INFO; then INFO, as each zoom level may widen + LOGGER.log(widened.getAndSet(true) ? Level.INFO : Level.WARNING, message); + return; + } + // the predicate cannot run on the members, nothing of GWC is installed there + List keys = + bulkGet(() -> map.keySet(range)).stream().filter(remove).toList(); + for (List batch : Lists.partition(keys, REMOVE_BATCH)) { + bulk(() -> map.removeAll(Predicates.in(KEY, batch.toArray(String[]::new)))); + } + } + + /** Returns the map, with a sorted key index when it could be added, so a key range is a lookup, not a scan. */ + private IMap indexedMap() { + HazelcastInstance hz = instance.get(); + IMap map = hz.getMap(mapName); + // a full cluster restart drops the index; adding it is idempotent but a cluster wide call + Set members = hz.getCluster().getMembers(); + if (!Collections.disjoint(members, indexedOn)) return map; + try { + bulk(() -> map.addIndex(IndexType.SORTED, KEY)); + indexedOn = members; + indexFailing.set(false); + } catch (OperationTimeoutException e) { + // a cluster this slow fails the removal too, going on would only double the wait + throw e; + } catch (RuntimeException e) { + // a key range then reads every entry on the members: slower, still correct; the next truncate tries again + Level level = indexFailing.getAndSet(true) ? Level.FINE : Level.WARNING; + LOGGER.log( + level, + "In-memory tile cache could not add the key index to map " + mapName + ", truncating without it", + e); + } + return map; + } + + /** {@inheritDoc} Fails after {@link #BULK_TIMEOUT_PROPERTY} milliseconds. */ + @Override + public void clear() { + IMap map = map(); + bulk(map::clear); + } + + /** {@inheritDoc} While unreachable, cluster locks give way to local ones. */ + @Override + public void reachable(boolean reachable) { + if (locks != null) locks.reachable(reachable); + } + + /** + * {@inheritDoc} Leaves the shared client to its connection, and stops the cluster locks of this store. Bulk calls + * and writes still running end on their own. + */ + @Override + public void close() { + bulkPool.shutdown(); + putPool.shutdown(); + if (locks != null) locks.stop(); + } + + /** Keys starting with the prefix are exactly those between it and the prefix with its last char incremented. */ + private static com.hazelcast.query.Predicate keyRange(String prefix) { + int last = prefix.length() - 1; + String end = prefix.substring(0, last) + (char) (prefix.charAt(last) + 1); + return Predicates.and(Predicates.greaterEqual(KEY, prefix), Predicates.lessThan(KEY, end)); + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreConfigProvider.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreConfigProvider.java new file mode 100644 index 0000000000..458bcab414 --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreConfigProvider.java @@ -0,0 +1,35 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import com.thoughtworks.xstream.XStream; +import org.geowebcache.config.Info; +import org.geowebcache.config.XMLConfigurationProvider; + +/** Maps the Hazelcast backend settings to their {@code } name in {@code geowebcache.xml}. */ +public class HazelcastKeyValueStoreConfigProvider implements XMLConfigurationProvider { + + @Override + public XStream getConfiguredXStream(XStream xs) { + xs.alias("hazelcastClientKeyValueStore", HazelcastClientKeyValueStoreInfo.class); + xs.alias("hazelcastEmbeddedKeyValueStore", HazelcastEmbeddedKeyValueStoreInfo.class); + return xs; + } + + /** Backend settings are saved with {@code }, never as a standalone info. */ + @Override + public boolean canSave(Info i) { + return false; + } +} diff --git a/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastLockProvider.java b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastLockProvider.java new file mode 100644 index 0000000000..2d10c8da3e --- /dev/null +++ b/geowebcache/hazelcast/src/main/java/org/geowebcache/hazelcast/HazelcastLockProvider.java @@ -0,0 +1,129 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.map.IMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.geotools.util.logging.Logging; +import org.geowebcache.GeoWebCacheException; +import org.geowebcache.locks.LockProvider; +import org.geowebcache.locks.MemoryLockProvider; + +/** + * {@link LockProvider} shared by every node of the Hazelcast tile cache, so a metatile is rendered once in the cluster. + * When the cluster cannot be reached, the tile cache finds it down, or a lock is not acquired in time, it falls back to + * a local lock: the worst case is a tile rendered once per node, never a failed request. A lock must be released by the + * thread that acquired it. + */ +public class HazelcastLockProvider implements LockProvider { + + private static final Logger LOGGER = Logging.getLogger(HazelcastLockProvider.class.getName()); + + private final MemoryLockProvider local = new MemoryLockProvider(); + + private final AtomicBoolean warnedNoCluster = new AtomicBoolean(); + + /** Seconds to wait for a lock, also the lease freeing a lock its holder never released. */ + private final int timeout; + + /** Where to lock, null while no store of a Hazelcast tile cache backend is in use. */ + private final AtomicReference locks = new AtomicReference<>(); + + /** Waits for a lock, and keeps it at most, {@link LockProvider#GWC_LOCK_TIMEOUT} seconds. */ + public HazelcastLockProvider() { + this(GWC_LOCK_TIMEOUT); + } + + HazelcastLockProvider(int timeout) { + this.timeout = timeout; + } + + /** + * Locks on {@code instance} from now on, in a map named after the tile map, until the returned target stops or + * another call takes over. + */ + Target lockOn(Supplier instance, String tileMap) { + // map locks create no entries, so this map needs no declaration on the cluster + String name = tileMap + ".locks"; + Target target = new Target(() -> instance.get().getMap(name)); + locks.set(target); + warnedNoCluster.set(false); + return target; + } + + /** The lock map of one tile cache store, skipped while the cache finds that store unreachable. */ + public final class Target { + + private final Supplier> map; + + private volatile boolean reachable = true; + + private Target(Supplier> map) { + this.map = map; + } + + void reachable(boolean reachable) { + this.reachable = reachable; + } + + /** Back to local locks, unless another store took over. */ + void stop() { + locks.compareAndSet(this, null); + } + } + + /** {@inheritDoc} */ + @Override + public Lock getLock(String lockKey) throws GeoWebCacheException { + Target current = locks.get(); + if (current == null) { + if (warnedNoCluster.compareAndSet(false, true)) { + LOGGER.warning("Hazelcast locking needs the tile cache enabled with a Hazelcast backend," + + " using local locks until then"); + } + return local.getLock(lockKey); + } + // the cache logged the outage already, and waiting on a silent cluster would cost every metatile a timeout + if (!current.reachable) return local.getLock(lockKey); + try { + IMap map = current.map.get(); + // map locks rather than the CP FencedLock, which has no consistency guarantee without CP members + if (map.tryLock(lockKey, timeout, SECONDS, timeout, SECONDS)) return () -> release(map, lockKey); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new GeoWebCacheException("Interrupted while acquiring lock " + lockKey, e); + } catch (RuntimeException e) { + // fails at once while the client is offline, the tile cache already logs the outage + LOGGER.log(Level.FINE, e, () -> "Hazelcast unreachable, local lock for " + lockKey); + return local.getLock(lockKey); + } + LOGGER.warning("Lock " + lockKey + " not acquired in " + timeout + " s, continuing with a local lock"); + return local.getLock(lockKey); + } + + private void release(IMap map, String lockKey) { + try { + map.unlock(lockKey); + } catch (RuntimeException e) { + LOGGER.log(Level.WARNING, "Could not release lock " + lockKey + ", it expires within " + timeout + " s", e); + } + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastClientXmlTest.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastClientXmlTest.java new file mode 100644 index 0000000000..bfdc2706a9 --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastClientXmlTest.java @@ -0,0 +1,139 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static com.hazelcast.client.properties.ClientProperty.INVOCATION_TIMEOUT_SECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.geowebcache.hazelcast.HazelcastTestMembers.CLUSTER; +import static org.geowebcache.hazelcast.HazelcastTestMembers.freePort; +import static org.geowebcache.hazelcast.HazelcastTestMembers.start; +import static org.geowebcache.hazelcast.HazelcastTestMembers.xml; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import com.hazelcast.client.HazelcastClientOfflineException; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.client.config.ConnectionRetryConfig; +import com.hazelcast.core.HazelcastInstance; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** The client backend with a {@code hazelcast-client.xml}: the file wins over the settings, except for recovery. */ +public class HazelcastClientXmlTest { + + /** Blocking start, no reconnect and a short connect timeout: all overridden by the backend. */ + private static final String CLIENT_XML = + """ + + %s + + +

127.0.0.1:%d
+ + + + + 1000 + + + + """; + + /** Sets what the backend otherwise fills in. */ + private static final String TUNED_XML = + """ + + + 20 + + + + 1.5 + 0.5 + + + + """; + + private static HazelcastInstance member; + + private static int port; + + /** Default settings point to localhost:5701 in cluster "gwc", reaching the member only through the file. */ + private final HazelcastClientKeyValueStoreInfo settings = new HazelcastClientKeyValueStoreInfo(); + + private HazelcastClientConnection backend; + + @BeforeClass + public static void startMember() { + port = freePort(); + member = start(port); + } + + @AfterClass + public static void stopMember() { + member.shutdown(); + } + + @After + public void destroyBackend() { + backend.destroy(); + } + + @Test + public void testFileReplacesSettings() { + backend = new HazelcastClientConnection(xml(CLIENT_XML.formatted(CLUSTER, port))); + + try (KeyValueStore store = backend.createStore(settings)) { + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + store.put("key", new byte[] {1}, 300); + + assertArrayEquals(new byte[] {1}, store.get("key")); + } + } + + @Test + public void testDefaultsUnlessFileSetsThem() { + backend = new HazelcastClientConnection(xml(CLIENT_XML.formatted(CLUSTER, port))); + ClientConfig config = backend.clientConfig(settings); + assertEquals("5", config.getProperty(INVOCATION_TIMEOUT_SECONDS.getName())); + ConnectionRetryConfig retry = config.getConnectionStrategyConfig().getConnectionRetryConfig(); + assertEquals(2, retry.getMultiplier(), 0); + assertEquals(0.2, retry.getJitter(), 0); + + config = new HazelcastClientConnection(xml(TUNED_XML)).clientConfig(settings); + assertEquals("20", config.getProperty(INVOCATION_TIMEOUT_SECONDS.getName())); + retry = config.getConnectionStrategyConfig().getConnectionRetryConfig(); + assertEquals(1.5, retry.getMultiplier(), 0); + assertEquals(0.5, retry.getJitter(), 0); + } + + @Test + public void testRecoveryEnforced() { + backend = new HazelcastClientConnection(xml(CLIENT_XML.formatted(CLUSTER, 1))); + + // async start enforced: with the file's blocking start this would wait, then fail + try (KeyValueStore store = backend.createStore(settings)) { + // past the file's 1 s connect timeout the client still retries instead of shutting down + await().pollDelay(2, SECONDS) + .atMost(5, SECONDS) + .untilAsserted(() -> assertThrows(HazelcastClientOfflineException.class, () -> store.get("key"))); + } + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastEmbeddedMemberTest.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastEmbeddedMemberTest.java new file mode 100644 index 0000000000..ab814b485a --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastEmbeddedMemberTest.java @@ -0,0 +1,179 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.geowebcache.hazelcast.HazelcastTestMembers.CLUSTER; +import static org.geowebcache.hazelcast.HazelcastTestMembers.NO_FILE; +import static org.geowebcache.hazelcast.HazelcastTestMembers.freePort; +import static org.geowebcache.hazelcast.HazelcastTestMembers.xml; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.util.Objects; +import org.geowebcache.locks.LockProvider.Lock; +import org.geowebcache.storage.memorycache.AbstractKeyValueStoreTest; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** Runs the store on a member embedded in the test JVM, configured as an admin would in {@code hazelcast.xml}. */ +public class HazelcastEmbeddedMemberTest extends AbstractKeyValueStoreTest { + + private static final String MEMBER_XML = + """ + + %s + + false + false + + + %d + + + + + + 127.0.0.1 + + + + + + + """; + + private static final byte[] TILE = {1}; + + private static HazelcastEmbeddedMember backend; + + @BeforeClass + public static void createBackend() { + backend = new HazelcastEmbeddedMember(xml(MEMBER_XML.formatted(CLUSTER, freePort()))); + } + + @AfterClass + public static void destroyBackend() { + backend.destroy(); + } + + @Override + protected KeyValueStore createStore() { + KeyValueStore created = backend.createStore(new HazelcastEmbeddedKeyValueStoreInfo()); + // the member joins in the background, calls fail until then + await().atMost(30, SECONDS).ignoreExceptions().untilAsserted(created::clear); + return created; + } + + @Test + public void testStoppedMemberStartedAgain() { + int port = freePort(); + String memberXml = MEMBER_XML.formatted(CLUSTER, port); + HazelcastEmbeddedMember own = new HazelcastEmbeddedMember(xml(memberXml)); + try (KeyValueStore restarted = own.createStore(new HazelcastEmbeddedKeyValueStoreInfo())) { + await().atMost(30, SECONDS).ignoreExceptions().untilAsserted(() -> restarted.put("key", TILE, 300)); + + // as an out of memory error or a cluster shutdown would + Hazelcast.getAllHazelcastInstances().stream() + .filter(m -> m.getCluster().getLocalMember().getAddress().getPort() == port) + .forEach(m -> m.getLifecycleService().terminate()); + IllegalStateException e = assertThrows(IllegalStateException.class, () -> restarted.get("key")); + assertThat(e.getMessage(), containsString("stopped")); + + // the same store works again once the new member has joined + await().atMost(30, SECONDS).ignoreExceptions().untilAsserted(() -> restarted.put("key", TILE, 300)); + } finally { + own.destroy(); + } + } + + @Test + public void testFailedMemberNotStartedAgainAtOnce() throws Exception { + // the member cannot bind its port, so every start fails at once + ServerSocket taken = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + HazelcastEmbeddedMember own = + new HazelcastEmbeddedMember(xml(MEMBER_XML.formatted(CLUSTER, taken.getLocalPort()))); + try (taken; + KeyValueStore store = own.createStore(new HazelcastEmbeddedKeyValueStoreInfo())) { + // the first failure starts a new member right away + Throwable first = await().atMost(30, SECONDS).until(() -> failedStart(store), Objects::nonNull); + Throwable second = await().atMost(30, SECONDS) + .until(() -> failedStart(store), cause -> cause != null && cause != first); + + // within the interval the same failure is reported, as lock calls would otherwise start a member each + assertSame(second, failedStart(store)); + } finally { + own.destroy(); + } + } + + /** The cause of the failed start {@code store} reports, null while the member is still joining. */ + private static Throwable failedStart(KeyValueStore store) { + IllegalStateException e = assertThrows(IllegalStateException.class, () -> store.get("key")); + return e.getMessage().contains("failed to start") ? e.getCause() : null; + } + + @Test + public void testMissingFile() { + HazelcastEmbeddedMember missing = new HazelcastEmbeddedMember(NO_FILE); + HazelcastEmbeddedKeyValueStoreInfo settings = new HazelcastEmbeddedKeyValueStoreInfo(); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> missing.createStore(settings)); + + assertThat(e.getMessage(), containsString("hazelcast.xml")); + } + + @Test + public void testLockProviderLocksOnMember() throws Exception { + int port = freePort(); + HazelcastEmbeddedMember own = new HazelcastEmbeddedMember(xml(MEMBER_XML.formatted(CLUSTER, port))); + HazelcastLockProvider locks = new HazelcastLockProvider(); + own.setLockProvider(locks); + try (KeyValueStore store = own.createStore(new HazelcastEmbeddedKeyValueStoreInfo())) { + await().atMost(30, SECONDS).ignoreExceptions().untilAsserted(store::clear); + HazelcastInstance member = Hazelcast.getAllHazelcastInstances().stream() + .filter(m -> m.getCluster().getLocalMember().getAddress().getPort() == port) + .findFirst() + .orElseThrow(); + + Lock lock = locks.getLock("key"); + assertTrue(member.getMap("gwc-tiles.locks").isLocked("key")); + lock.release(); + assertFalse(member.getMap("gwc-tiles.locks").isLocked("key")); + } finally { + own.destroy(); + } + } + + @Test + public void testUndeclaredMap() { + HazelcastEmbeddedKeyValueStoreInfo settings = new HazelcastEmbeddedKeyValueStoreInfo(); + settings.setMapName("undeclared"); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> backend.createStore(settings)); + + assertThat(e.getMessage(), containsString("undeclared")); + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreTest.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreTest.java new file mode 100644 index 0000000000..d9f5b3719a --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastKeyValueStoreTest.java @@ -0,0 +1,319 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.geowebcache.hazelcast.HazelcastTestMembers.CLUSTER; +import static org.geowebcache.hazelcast.HazelcastTestMembers.NO_FILE; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; + +import com.hazelcast.client.HazelcastClientOfflineException; +import com.hazelcast.core.HazelcastException; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.OperationTimeoutException; +import com.hazelcast.map.IMap; +import com.hazelcast.map.MapInterceptor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.concurrent.CountDownLatch; +import java.util.function.UnaryOperator; +import java.util.stream.IntStream; +import org.geowebcache.storage.memorycache.AbstractKeyValueStoreTest; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; + +/** Runs the store against a member started in the test JVM, reached through the client backend. */ +public class HazelcastKeyValueStoreTest extends AbstractKeyValueStoreTest { + + private static HazelcastInstance member; + + private static HazelcastClientKeyValueStoreInfo settings; + + private final HazelcastClientConnection backend = new HazelcastClientConnection(NO_FILE); + + private final HazelcastClientConnection otherBackend = new HazelcastClientConnection(NO_FILE); + + @BeforeClass + public static void startMember() { + int port = HazelcastTestMembers.freePort(); + member = HazelcastTestMembers.start(port); + settings = HazelcastTestMembers.clientSettings(port); + } + + @AfterClass + public static void stopMember() { + member.shutdown(); + } + + @After + public void shutdownClients() { + backend.destroy(); + otherBackend.destroy(); + } + + @Override + protected KeyValueStore createStore() { + KeyValueStore created = connectedStore(backend); + created.clear(); + return created; + } + + /** The client starts in the background, calls fail until it connects. */ + private static KeyValueStore connectedStore(HazelcastClientConnection backend) { + KeyValueStore created = backend.createStore(settings); + await().atMost(30, SECONDS).ignoreExceptions().until(() -> created.get("probe") == null); + return created; + } + + @Test + public void testExpiry() { + store.put("key", new byte[] {1}, 1); + + await().atMost(10, SECONDS).until(() -> store.get("key") == null); + } + + @Test + public void testOtherClientSeesRemoval() { + try (KeyValueStore other = connectedStore(otherBackend)) { + store.put("layer/a/1", new byte[] {1}, 300); + assertArrayEquals(new byte[] {1}, other.get("layer/a/1")); + + store.removeByPrefix("layer/"); + + assertNull(other.get("layer/a/1")); + } + } + + @Test + public void testUnreachableClusterFailsFast() { + HazelcastClientKeyValueStoreInfo unreachable = new HazelcastClientKeyValueStoreInfo(); + unreachable.setClusterName(CLUSTER); + unreachable.setMembers("127.0.0.1:1"); + + try (KeyValueStore offline = otherBackend.createStore(unreachable)) { + assertThrows(HazelcastClientOfflineException.class, () -> offline.get("key")); + } + } + + @Test + public void testCloseKeepsSharedClient() { + store.put("key", new byte[] {1}, 300); + + store.close(); + + assertArrayEquals(new byte[] {1}, backend.createStore(settings).get("key")); + } + + @Test + public void testRemoveMatchingInBatches() { + int count = HazelcastKeyValueStore.REMOVE_BATCH * 2 + 1; + IntStream.range(0, count).forEach(i -> store.put("layer/" + i, new byte[] {1}, 300)); + + store.removeMatching("layer/", key -> !key.equals("layer/0")); + + long present = IntStream.range(0, count) + .filter(i -> store.get("layer/" + i) != null) + .count(); + assertEquals(1, present); + } + + @Test + public void testRemoveMatchingWidenedPastLimit() { + try (KeyValueStore limited = new HazelcastKeyValueStore( + () -> member, + settings.getMapName(), + 3, + HazelcastKeyValueStore.CALL_TIMEOUT, + HazelcastKeyValueStore.BULK_TIMEOUT, + null)) { + IntStream.range(0, 3).forEach(i -> store.put("layer/1/" + i, new byte[] {1}, 300)); + store.put("layer/2/0", new byte[] {1}, 300); + + // at the limit, only the matching keys go + limited.removeMatching("layer/1/", key -> key.equals("layer/1/0")); + assertNull(store.get("layer/1/0")); + assertNotNull(store.get("layer/1/1")); + + // past it, every key under the prefix goes, and only those + IntStream.range(3, 5).forEach(i -> store.put("layer/1/" + i, new byte[] {1}, 300)); + limited.removeMatching("layer/1/", key -> key.equals("layer/1/3")); + assertNull(store.get("layer/1/1")); + assertNull(store.get("layer/1/4")); + assertNotNull(store.get("layer/2/0")); + } + } + + @Test + public void testStalledMemberFailsWithinCallTimeout() { + // own map, as the stalled partition thread holds every call on its partition + IMap map = member.getMap("stalled-tiles"); + map.set("tile", Stall.VALUE); + String interceptor = map.addInterceptor(new Stall()); + try (KeyValueStore stalled = new HazelcastKeyValueStore( + () -> member, "stalled-tiles", HazelcastKeyValueStore.MATCHING_LIMIT, 200, 200, null)) { + assertFailsFast(() -> stalled.get("tile")); + assertFailsFast(() -> stalled.put("other", Stall.VALUE, 300)); + assertFailsFast(() -> stalled.putIfAbsent("absent", Stall.VALUE, 300)); + assertFailsFast(() -> stalled.remove("tile")); + } finally { + map.removeInterceptor(interceptor); + } + } + + @Test + public void testRefusedIndexKeepsTruncating() { + HazelcastInstance refusing = wrapMaps(map -> proxy(IMap.class, (s, m, a) -> refuseIndex(m, map, a))); + try (KeyValueStore unindexed = new HazelcastKeyValueStore( + () -> refusing, "unindexed-tiles", HazelcastKeyValueStore.MATCHING_LIMIT, 2000, 2000, null)) { + unindexed.put("layer/a/1", new byte[] {1}, 300); + unindexed.put("other/a/1", new byte[] {1}, 300); + + unindexed.removeByPrefix("layer/"); + unindexed.removeMatching("other/", key -> key.endsWith("/1")); + + assertNull(unindexed.get("layer/a/1")); + assertNull(unindexed.get("other/a/1")); + } + } + + @Test + public void testStalledBulkCallFailsWithinBulkTimeout() { + CountDownLatch release = new CountDownLatch(1); + HazelcastInstance stalling = + wrapMaps(map -> proxy(IMap.class, (s, m, a) -> hold("removeAll", m, map, a, release))); + try (KeyValueStore stalled = new HazelcastKeyValueStore( + () -> stalling, "bulk-tiles", HazelcastKeyValueStore.MATCHING_LIMIT, 200, 200, null)) { + assertFailsFast(() -> stalled.removeByPrefix("layer/")); + } finally { + release.countDown(); + } + } + + @Test + public void testPutIfAbsentSkippedWhileThreadsStalled() { + CountDownLatch release = new CountDownLatch(1); + HazelcastInstance stalling = + wrapMaps(map -> proxy(IMap.class, (s, m, a) -> hold("putIfAbsent", m, map, a, release))); + try (KeyValueStore stalled = new HazelcastKeyValueStore( + () -> stalling, "put-tiles", HazelcastKeyValueStore.MATCHING_LIMIT, 50, 50, null)) { + for (int i = 0; i < HazelcastKeyValueStore.PUT_THREADS; i++) { + String key = "tile" + i; + assertThrows(OperationTimeoutException.class, () -> stalled.putIfAbsent(key, Stall.VALUE, 300)); + } + // every put thread still waits: the next copy is dropped without failing + stalled.putIfAbsent("skipped", Stall.VALUE, 300); + } finally { + release.countDown(); + } + assertNull(member.getMap("put-tiles").get("skipped")); + } + + /** Calls {@code method} on {@code map}, {@code name} calls waiting for {@code release} as on a stalled member. */ + private static Object hold(String name, Method method, IMap map, Object[] args, CountDownLatch release) + throws Throwable { + if (method.getName().equals(name)) release.await(); + return call(method, map, args); + } + + /** The test member, with each of its maps seen through {@code wrap}. */ + private static HazelcastInstance wrapMaps(UnaryOperator> wrap) { + return proxy(HazelcastInstance.class, (self, method, args) -> { + Object result = call(method, member, args); + return result instanceof IMap map ? wrap.apply(map) : result; + }); + } + + /** Calls {@code method} on {@code map}, refusing to add an index, as a cluster denying it would. */ + private static Object refuseIndex(Method method, IMap map, Object[] args) throws Throwable { + if (method.getName().equals("addIndex")) throw new HazelcastException("Index refused"); + return call(method, map, args); + } + + @SuppressWarnings("unchecked") + private static T proxy(Class type, InvocationHandler handler) { + return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, handler); + } + + private static Object call(Method method, Object target, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + private static void assertFailsFast(ThrowingRunnable call) { + long start = System.nanoTime(); + assertThrows(OperationTimeoutException.class, call); + assertThat(NANOSECONDS.toMillis(System.nanoTime() - start), lessThan(Stall.MILLIS)); + } + + /** Holds the member partition thread on every read or write of {@link #VALUE}, as a stalled member does. */ + static class Stall implements MapInterceptor { + + static final byte[] VALUE = {42}; + + static final long MILLIS = 1500; + + @Override + public Object interceptGet(Object value) { + stallOn(value); + return null; + } + + @Override + public Object interceptPut(Object oldValue, Object newValue) { + stallOn(newValue); + return null; + } + + private static void stallOn(Object value) { + if (!(value instanceof byte[] bytes) || !Arrays.equals(bytes, VALUE)) return; + try { + Thread.sleep(MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void afterGet(Object value) {} + + @Override + public Object interceptRemove(Object removedValue) { + return null; + } + + @Override + public void afterPut(Object value) {} + + @Override + public void afterRemove(Object oldValue) {} + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastLockProviderTest.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastLockProviderTest.java new file mode 100644 index 0000000000..6017324a46 --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastLockProviderTest.java @@ -0,0 +1,204 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.geowebcache.hazelcast.HazelcastClientKeyValueStoreInfo.DEFAULT_MAP_NAME; +import static org.geowebcache.hazelcast.HazelcastTestMembers.NO_FILE; +import static org.geowebcache.hazelcast.HazelcastTestMembers.clientSettings; +import static org.geowebcache.hazelcast.HazelcastTestMembers.freePort; +import static org.geowebcache.hazelcast.HazelcastTestMembers.start; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.map.IMap; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.geowebcache.locks.LockProvider.Lock; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.After; +import org.junit.Test; + +/** Locks shared by nodes connected as clients to the same members, with their fallbacks to local locks. */ +public class HazelcastLockProviderTest { + + private static final String KEY = "gwc_metatile_test"; + + private final List backends = new ArrayList<>(); + + private final ExecutorService executor = Executors.newCachedThreadPool(); + + @After + public void shutdown() { + executor.shutdownNow(); + backends.forEach(HazelcastClientConnection::destroy); + Hazelcast.shutdownAll(); + } + + /** A node with its own client, connected, waiting for and leasing locks {@code timeout} seconds. */ + private HazelcastLockProvider node(int port, int timeout) { + HazelcastLockProvider locks = new HazelcastLockProvider(timeout); + connect(locks, port); + return locks; + } + + /** The store of a new client locking through {@code locks}, once connected. */ + private KeyValueStore connect(HazelcastLockProvider locks, int port) { + HazelcastClientConnection backend = new HazelcastClientConnection(NO_FILE); + backend.setLockProvider(locks); + backends.add(backend); + KeyValueStore store = backend.createStore(clientSettings(port)); + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + return store; + } + + private static IMap locks(HazelcastInstance member) { + return member.getMap(DEFAULT_MAP_NAME + ".locks"); + } + + @Test + public void testLockExcludesOtherNodes() throws Exception { + int port = freePort(); + HazelcastInstance member = start(port); + HazelcastLockProvider first = node(port, 60); + HazelcastLockProvider second = node(port, 60); + Lock held = first.getLock(KEY); + + // released on the thread that acquired it, as Hazelcast requires + Future waiting = executor.submit(() -> { + Lock lock = second.getLock(KEY); + boolean onCluster = locks(member).isLocked(KEY); + lock.release(); + return onCluster; + }); + + // past the 5 s client invocation timeout, which must not cut a waiting lock short + await().during(7, SECONDS).atMost(10, SECONDS).until(() -> !waiting.isDone()); + held.release(); + assertTrue(waiting.get(10, SECONDS)); + assertFalse(locks(member).isLocked(KEY)); + } + + @Test + public void testLeaseFreesLockNeverReleased() throws Exception { + int port = freePort(); + HazelcastInstance member = start(port); + Lock stale = node(port, 2).getLock(KEY); + HazelcastLockProvider second = node(port, 30); + + long start = System.nanoTime(); + Lock lock = second.getLock(KEY); + assertThat(NANOSECONDS.toSeconds(System.nanoTime() - start), lessThan(10L)); + + // a late release by the first holder is logged, and leaves the lock of the second one alone + stale.release(); + assertTrue(locks(member).isLocked(KEY)); + lock.release(); + assertFalse(locks(member).isLocked(KEY)); + } + + @Test + public void testTimeoutFallsBackToLocalLock() throws Exception { + int port = freePort(); + start(port); + Lock held = node(port, 60).getLock(KEY); + HazelcastLockProvider impatient = node(port, 1); + + long start = System.nanoTime(); + impatient.getLock(KEY).release(); + assertThat(NANOSECONDS.toSeconds(System.nanoTime() - start), lessThan(5L)); + held.release(); + } + + @Test + public void testClusterDownFallsBackToLocalLock() throws Exception { + int port = freePort(); + HazelcastInstance member = start(port); + HazelcastLockProvider locks = node(port, 60); + + member.shutdown(); + + // once the client knows, locks fall back at once instead of waiting on the cluster + await().atMost(30, SECONDS).until(() -> lockMillis(locks) < 1000); + // and still exclude other threads of this node + Lock held = locks.getLock(KEY); + Future waiting = executor.submit(() -> { + locks.getLock(KEY).release(); + return null; + }); + await().during(1, SECONDS).atMost(2, SECONDS).until(() -> !waiting.isDone()); + held.release(); + waiting.get(10, SECONDS); + } + + @Test + @SuppressWarnings("PMD.CloseResource") // closes the stores by hand, in the order under test + public void testClosedStoreStopsClusterLocks() throws Exception { + int port = freePort(); + HazelcastInstance member = start(port); + HazelcastLockProvider locks = new HazelcastLockProvider(60); + HazelcastClientConnection backend = new HazelcastClientConnection(NO_FILE); + backend.setLockProvider(locks); + backends.add(backend); + KeyValueStore first = backend.createStore(clientSettings(port)); + await().atMost(30, SECONDS).ignoreExceptions().until(() -> first.get("probe") == null); + + // settings saved again: the new store is built before the old one is closed, and keeps the cluster locks + KeyValueStore second = backend.createStore(clientSettings(port)); + first.close(); + assertTrue(lockedOnCluster(locks, member)); + + // the cache switched to another backend + second.close(); + assertFalse(lockedOnCluster(locks, member)); + } + + @Test + public void testUnreachableStoreLocksLocally() throws Exception { + int port = freePort(); + HazelcastInstance member = start(port); + HazelcastLockProvider locks = new HazelcastLockProvider(60); + try (KeyValueStore store = connect(locks, port)) { + // the tile cache found the cluster down: locks skip it until the cache finds it back + store.reachable(false); + assertFalse(lockedOnCluster(locks, member)); + store.reachable(true); + assertTrue(lockedOnCluster(locks, member)); + } + } + + private static boolean lockedOnCluster(HazelcastLockProvider locks, HazelcastInstance member) throws Exception { + Lock lock = locks.getLock(KEY); + try { + return locks(member).isLocked(KEY); + } finally { + lock.release(); + } + } + + private static long lockMillis(HazelcastLockProvider locks) throws Exception { + long start = System.nanoTime(); + locks.getLock(KEY).release(); + return NANOSECONDS.toMillis(System.nanoTime() - start); + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastRecoveryTest.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastRecoveryTest.java new file mode 100644 index 0000000000..ee673da38d --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastRecoveryTest.java @@ -0,0 +1,129 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.geowebcache.hazelcast.HazelcastTestMembers.NO_FILE; +import static org.geowebcache.hazelcast.HazelcastTestMembers.clientSettings; +import static org.geowebcache.hazelcast.HazelcastTestMembers.freePort; +import static org.geowebcache.hazelcast.HazelcastTestMembers.start; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertThrows; + +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.HazelcastClientOfflineException; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.util.stream.IntStream; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.After; +import org.junit.Test; + +/** Outages behind a client store: fast failures while down, recovery on reconnect, or by a new client once stopped. */ +public class HazelcastRecoveryTest { + + private static final byte[] TILE = {1}; + + private final HazelcastClientConnection backend = new HazelcastClientConnection(NO_FILE); + + @After + public void shutdown() { + backend.destroy(); + Hazelcast.shutdownAll(); + } + + @Test + public void testMemberRestart() { + int port = freePort(); + HazelcastInstance member = start(port); + HazelcastClientKeyValueStoreInfo settings = clientSettings(port); + try (KeyValueStore store = backend.createStore(settings)) { + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + + member.shutdown(); + + // once the client knows, calls fail without waiting for the invocation timeout + await().atMost(10, SECONDS).ignoreExceptions().until(() -> isOffline(store)); + long start = System.nanoTime(); + assertThrows(HazelcastClientOfflineException.class, () -> store.get("layer/a/1")); + assertThat(NANOSECONDS.toMillis(System.nanoTime() - start), lessThan(1000L)); + + // same store, no rebuild; the new member starts without the index, the next truncate adds it + HazelcastInstance restarted = start(port); + await().atMost(60, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + store.put("layer/a/1", TILE, 300); + assertArrayEquals(TILE, store.get("layer/a/1")); + store.removeByPrefix("layer/"); + int indexes = restarted + .getMap(settings.getMapName()) + .getLocalMapStats() + .getIndexStats() + .size(); + assertThat(indexes, greaterThan(0)); + } + } + + @Test + public void testStoppedClientRebuilt() { + int port = freePort(); + start(port); + try (KeyValueStore store = backend.createStore(clientSettings(port))) { + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + store.put("layer/a/1", TILE, 300); + + // as when the cluster rejects the client + HazelcastClient.getAllHazelcastClients().forEach(HazelcastInstance::shutdown); + + // the first call finds it stopped and starts a new one, the same store then goes through it + assertThrows(IllegalStateException.class, () -> store.get("layer/a/1")); + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("layer/a/1") != null); + } + } + + private static boolean isOffline(KeyValueStore store) { + try { + store.get("probe"); + return false; + } catch (HazelcastClientOfflineException e) { + return true; + } + } + + @Test + public void testMemberLossKeepsTiles() { + int port = freePort(); + int otherPort = freePort(); + HazelcastInstance member = start(port, otherPort); + HazelcastInstance other = start(otherPort, port); + await().atMost(30, SECONDS).until(() -> member.getCluster().getMembers().size() == 2); + try (KeyValueStore store = backend.createStore(clientSettings(port, otherPort))) { + await().atMost(30, SECONDS).ignoreExceptions().until(() -> store.get("probe") == null); + // enough keys to land on partitions owned by both members + IntStream.range(0, 100).forEach(i -> store.put("layer/" + i, TILE, 300)); + + other.getLifecycleService().terminate(); + + // writes cut by the member leaving may fail past the call timeout, then succeed once the cluster recovers + await().atMost(30, SECONDS).ignoreExceptions().untilAsserted(() -> store.put("written", TILE, 300)); + // backups are promoted on the surviving member, every tile is still there + await().atMost(30, SECONDS).ignoreExceptions().until(() -> IntStream.range(0, 100) + .allMatch(i -> store.get("layer/" + i) != null)); + } + } +} diff --git a/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastTestMembers.java b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastTestMembers.java new file mode 100644 index 0000000000..36f550e297 --- /dev/null +++ b/geowebcache/hazelcast/src/test/java/org/geowebcache/hazelcast/HazelcastTestMembers.java @@ -0,0 +1,86 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.hazelcast; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.stream.Collectors.joining; + +import com.hazelcast.config.Config; +import com.hazelcast.config.JoinConfig; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.ServerSocket; +import java.util.stream.IntStream; +import org.geowebcache.config.ConfigurationResourceProvider; +import org.geowebcache.config.MockConfigurationResourceProvider; + +/** Members started in the test JVM on loopback, at fixed ports so a restarted member is found again by the client. */ +final class HazelcastTestMembers { + + static final String CLUSTER = "gwc-hazelcast-test"; + + /** A Hazelcast configuration file that does not exist. */ + static final ConfigurationResourceProvider NO_FILE = new MockConfigurationResourceProvider(null) { + @Override + public boolean hasInput() { + return false; + } + }; + + private HazelcastTestMembers() {} + + static int freePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** Starts a member on {@code port}, joining the members at {@code ports} as well. */ + @SuppressWarnings("PMD.AvoidUsingHardCodedIP") // loopback only, test members never join a real cluster + static HazelcastInstance start(int port, int... ports) { + Config config = new Config().setClusterName(CLUSTER); + config.setProperty("hazelcast.phone.home.enabled", "false"); + // loopback only, otherwise the member may announce a VPN or virtual adapter address the client cannot reach + config.setProperty("hazelcast.socket.bind.any", "false"); + NetworkConfig network = config.getNetworkConfig(); + network.setPort(port).setPortAutoIncrement(false); + network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + + JoinConfig join = network.getJoin(); + join.getMulticastConfig().setEnabled(false); + join.getAutoDetectionConfig().setEnabled(false); + IntStream.of(ports) + .forEach(peer -> join.getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + peer)); + return Hazelcast.newHazelcastInstance(config); + } + + /** A Hazelcast configuration file holding {@code content}. */ + static ConfigurationResourceProvider xml(String content) { + return new MockConfigurationResourceProvider(() -> new ByteArrayInputStream(content.getBytes(UTF_8))); + } + + /** Client settings reaching the members at {@code ports}. */ + static HazelcastClientKeyValueStoreInfo clientSettings(int... ports) { + HazelcastClientKeyValueStoreInfo settings = new HazelcastClientKeyValueStoreInfo(); + settings.setClusterName(CLUSTER); + settings.setMembers(IntStream.of(ports).mapToObj(p -> "127.0.0.1:" + p).collect(joining(","))); + return settings; + } +} diff --git a/geowebcache/pom.xml b/geowebcache/pom.xml index d10508441b..a0b6910221 100644 --- a/geowebcache/pom.xml +++ b/geowebcache/pom.xml @@ -28,6 +28,7 @@ swiftblob mbtiles gcsblob + hazelcast diff --git a/geowebcache/rest/src/main/java/org/geowebcache/rest/controller/MemoryCacheController.java b/geowebcache/rest/src/main/java/org/geowebcache/rest/controller/MemoryCacheController.java new file mode 100644 index 0000000000..d2e2cce3b5 --- /dev/null +++ b/geowebcache/rest/src/main/java/org/geowebcache/rest/controller/MemoryCacheController.java @@ -0,0 +1,88 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.rest.controller; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import javax.servlet.http.HttpServletResponse; +import org.geowebcache.config.XMLConfiguration; +import org.geowebcache.rest.exception.RestException; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; +import org.geowebcache.storage.memorycache.UnresolvedKeyValueStoreInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** Reads and replaces the {@code } settings of {@code geowebcache.xml}. */ +@Component +@RestController +@RequestMapping(path = "${gwc.context.suffix:}/rest/memorycache") +public class MemoryCacheController { + + private final XMLConfiguration config; + + /** Serves the settings of {@code config}. */ + @Autowired + public MemoryCacheController(XMLConfiguration config) { + this.config = config; + } + + /** The saved settings, an absent value meaning its default. */ + @RequestMapping( + method = RequestMethod.GET, + produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE}) + public MemoryCacheInfo memoryCacheGet() { + MemoryCacheInfo memoryCache = config.getMemoryCache(); + return memoryCache == null ? new MemoryCacheInfo() : memoryCache; + } + + /** + * Replaces the settings, an absent value taking its default. A change rebuilds the cache, which starts empty. + * + * @throws RestException 400 when the cache could not be built from them + */ + @RequestMapping( + method = RequestMethod.PUT, + consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE}) + public void memoryCachePut(@RequestBody MemoryCacheInfo memoryCache) throws IOException { + // saved as is, the cache would only log its failure and drop every tile + if (memoryCache.getTimeToLive() < 1) { + String message = "Time to live must be at least 1 second, got " + memoryCache.getTimeToLive(); + throw new RestException(message, HttpStatus.BAD_REQUEST); + } + if (memoryCache.getBackend() instanceof UnresolvedKeyValueStoreInfo unresolved) { + String message = "Backend " + unresolved.getAlias() + " is not installed"; + throw new RestException(message, HttpStatus.BAD_REQUEST); + } + // the same settings must not rebuild, and empty, the cache + if (!memoryCache.equals(config.getMemoryCache())) config.setMemoryCache(memoryCache); + } + + /** Answers with the status and message of the exception, as plain text. */ + @ExceptionHandler(RestException.class) + public void handleRestException(RestException e, HttpServletResponse response, OutputStream os) throws IOException { + // local, as in GeoServer its catch-all REST advice can run before the GWC one and answer 500 + response.setStatus(e.getStatus().value()); + response.setContentType(MediaType.TEXT_PLAIN_VALUE); + StreamUtils.copy(e.getMessage(), StandardCharsets.UTF_8, os); + } +} diff --git a/geowebcache/rest/src/main/java/org/geowebcache/rest/converter/GWCConverter.java b/geowebcache/rest/src/main/java/org/geowebcache/rest/converter/GWCConverter.java index 1ba08adcba..5bcc8fb7ec 100644 --- a/geowebcache/rest/src/main/java/org/geowebcache/rest/converter/GWCConverter.java +++ b/geowebcache/rest/src/main/java/org/geowebcache/rest/converter/GWCConverter.java @@ -36,6 +36,7 @@ import org.geowebcache.io.GeoWebCacheXStream; import org.geowebcache.layer.TileLayer; import org.geowebcache.rest.exception.RestException; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; import org.geowebcache.util.ApplicationContextProvider; import org.json.JSONArray; import org.json.JSONException; @@ -54,7 +55,8 @@ * Spring MVC Converter for GeoWebCache * *

Supports conversion of {@link BlobStoreInfo}, {@link GridSet}, {@link TileLayer}, {@link ServerConfigurationPOJO}, - * and {@link XStreamListAliasWrapper} containing lists of those classes to and from JSON and XML via XStream + * {@link MemoryCacheInfo} and {@link XStreamListAliasWrapper} containing lists of those classes to and from JSON and + * XML via XStream * * @param */ @@ -62,8 +64,8 @@ public class GWCConverter extends AbstractHttpMessageConverter implements private final WebApplicationContext context; - public final List supportedClasses = Collections.unmodifiableList( - Arrays.asList(BlobStoreInfo.class, GridSet.class, TileLayer.class, ServerConfigurationPOJO.class)); + public final List supportedClasses = Collections.unmodifiableList(Arrays.asList( + BlobStoreInfo.class, GridSet.class, TileLayer.class, ServerConfigurationPOJO.class, MemoryCacheInfo.class)); public GWCConverter(ApplicationContextProvider appCtx) { super(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML); @@ -78,6 +80,7 @@ public GWCConverter(ApplicationContextProvider appCtx) { */ private XStream configureXStream(XStream xs) { xs.alias("global", ServerConfigurationPOJO.class); + xs.alias("memoryCache", MemoryCacheInfo.class); return xs; } diff --git a/geowebcache/rest/src/test/java/org/geowebcache/rest/controller/MemoryCacheControllerTest.java b/geowebcache/rest/src/test/java/org/geowebcache/rest/controller/MemoryCacheControllerTest.java new file mode 100644 index 0000000000..487edd3c96 --- /dev/null +++ b/geowebcache/rest/src/test/java/org/geowebcache/rest/controller/MemoryCacheControllerTest.java @@ -0,0 +1,122 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.rest.controller; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath; + +import java.util.List; +import org.geowebcache.config.DefaultGridsets; +import org.geowebcache.config.XMLConfiguration; +import org.geowebcache.grid.GridSetBroker; +import org.geowebcache.rest.converter.GWCConverter; +import org.geowebcache.storage.memorycache.HeapKeyValueStoreInfo; +import org.geowebcache.storage.memorycache.MemoryCacheInfo; +import org.geowebcache.util.ApplicationContextProvider; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class MemoryCacheControllerTest { + + private static final String SETTINGS = + """ + + true + 60 + + 16 + + """; + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private XMLConfiguration config; + + private MockMvc mockMvc; + + @Before + public void setUp() throws Exception { + config = loadConfig(); + mockMvc = MockMvcBuilders.standaloneSetup(new MemoryCacheController(config)) + .setMessageConverters(new GWCConverter<>(new ApplicationContextProvider())) + .setControllerAdvice(new RestExceptionHandler()) + .build(); + } + + private XMLConfiguration loadConfig() throws Exception { + XMLConfiguration loaded = new XMLConfiguration(null, temp.getRoot().getAbsolutePath()); + loaded.setGridSetBroker(new GridSetBroker(List.of(new DefaultGridsets(false, false)))); + loaded.afterPropertiesSet(); + return loaded; + } + + @Test + public void testPutSavesSettings() throws Exception { + putSettings(SETTINGS).andExpect(status().isOk()); + + MemoryCacheInfo saved = loadConfig().getMemoryCache(); + assertEquals(60, saved.getTimeToLive()); + assertEquals(16, ((HeapKeyValueStoreInfo) saved.getBackend()).getMaxSizeMB()); + mockMvc.perform(get("/rest/memorycache").accept(MediaType.APPLICATION_XML)) + .andExpect(status().isOk()) + .andExpect(xpath("/memoryCache/enabled").string("true")) + .andExpect(xpath("/memoryCache/backend/@class").string("heapKeyValueStore")) + .andExpect(xpath("/memoryCache/backend/maxSizeMB").string("16")); + } + + @Test + public void testPutSameSettingsKeepsCache() throws Exception { + putSettings(SETTINGS); + MemoryCacheInfo saved = config.getMemoryCache(); + + putSettings(SETTINGS).andExpect(status().isOk()); + // the cache is rebuilt, and emptied, when the settings instance changes + assertSame(saved, config.getMemoryCache()); + } + + @Test + public void testPutRejectsTimeToLive() throws Exception { + putSettings("0") + .andExpect(status().isBadRequest()) + .andExpect(content().string(containsString("Time to live must be at least 1 second, got 0"))); + assertNull(config.getMemoryCache()); + } + + @Test + public void testPutRejectsUnknownBackend() throws Exception { + putSettings("") + .andExpect(status().isBadRequest()) + .andExpect(content().string(containsString("Backend missingStore is not installed"))); + assertNull(config.getMemoryCache()); + } + + private ResultActions putSettings(String xml) throws Exception { + return mockMvc.perform( + put("/rest/memorycache").contentType(MediaType.APPLICATION_XML).content(xml)); + } +} diff --git a/geowebcache/s3storage/src/main/java/org/geowebcache/s3/S3BlobStore.java b/geowebcache/s3storage/src/main/java/org/geowebcache/s3/S3BlobStore.java index 982a18dbec..42468786e5 100644 --- a/geowebcache/s3storage/src/main/java/org/geowebcache/s3/S3BlobStore.java +++ b/geowebcache/s3storage/src/main/java/org/geowebcache/s3/S3BlobStore.java @@ -410,7 +410,8 @@ private Properties getLayerMetadata(String layerName) { return s3Ops.getProperties(key); } - private void putParametersMetadata(String layerName, String parametersId, Map parameters) { + @Override + public void putParametersMetadata(String layerName, String parametersId, Map parameters) { if (isNull(parameters)) { return; } diff --git a/geowebcache/web/pom.xml b/geowebcache/web/pom.xml index 02bdf24ad5..b38b29f564 100644 --- a/geowebcache/web/pom.xml +++ b/geowebcache/web/pom.xml @@ -90,6 +90,11 @@ gwc-swift ${project.version} + + org.geowebcache + gwc-hazelcast + ${project.version} + org.springframework.security @@ -118,6 +123,11 @@ spring-test test + + org.awaitility + awaitility + test + org.xmlunit xmlunit-legacy diff --git a/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-hazelcast-context.xml b/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-hazelcast-context.xml new file mode 100644 index 0000000000..3d4ba8a92e --- /dev/null +++ b/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-hazelcast-context.xml @@ -0,0 +1,39 @@ + + + + + Bean configuration file for the gwc-hazelcast module + + + + + Contributes XStream configuration settings to org.geowebcache.config.XMLConfiguration to encode the Hazelcast tile cache backend settings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-servlet.xml b/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-servlet.xml index 15dc6e685b..a025dd5428 100644 --- a/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-servlet.xml +++ b/geowebcache/web/src/main/webapp/WEB-INF/geowebcache-servlet.xml @@ -22,6 +22,7 @@ + diff --git a/geowebcache/web/src/test/java/org/geowebcache/jetty/HazelcastLockIntegrationTest.java b/geowebcache/web/src/test/java/org/geowebcache/jetty/HazelcastLockIntegrationTest.java new file mode 100644 index 0000000000..a6f5b2fa43 --- /dev/null +++ b/geowebcache/web/src/test/java/org/geowebcache/jetty/HazelcastLockIntegrationTest.java @@ -0,0 +1,98 @@ +/** + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General + * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + *

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see + * . + * + *

Copyright 2026 + */ +package org.geowebcache.jetty; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import com.hazelcast.config.Config; +import com.hazelcast.config.JoinConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.map.IMap; +import java.io.File; +import java.io.IOException; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.geowebcache.GeoWebCacheExtensions; +import org.geowebcache.config.XMLConfiguration; +import org.geowebcache.hazelcast.HazelcastClientKeyValueStoreInfo; +import org.geowebcache.locks.LockProvider; +import org.geowebcache.locks.LockProvider.Lock; +import org.geowebcache.storage.memorycache.KeyValueStore; +import org.junit.ClassRule; +import org.junit.Test; + +/** Runs GWC with {@code hazelcastLock} as lock provider, as {@code geowebcache.xml} would name it on a cluster. */ +public class HazelcastLockIntegrationTest { + + private static final String CLUSTER = "gwc-lock-test"; + + @ClassRule + public static JettyRule jetty = new JettyRule(dir -> {}, HazelcastLockIntegrationTest::writeConfig); + + /** The template configuration, naming the Hazelcast locks. */ + private static void writeConfig(File cacheDir) throws IOException { + String template = IOUtils.toString(XMLConfiguration.class.getResource("/geowebcache.xml"), UTF_8); + String backendTimeout = "120"; + String config = template.replace(backendTimeout, backendTimeout + "hazelcastLock"); + FileUtils.writeStringToFile(new File(cacheDir, "geowebcache.xml"), config, UTF_8); + } + + @Test + @SuppressWarnings("PMD.UnusedLocalVariable") // the store is opened only to make the client lock on the cluster + public void testLocksOnCluster() throws Exception { + LockProvider locks = GeoWebCacheExtensions.bean(XMLConfiguration.class).getLockProvider(); + assertSame(GeoWebCacheExtensions.bean("hazelcastLock"), locks); + + HazelcastInstance member = Hazelcast.newHazelcastInstance(memberConfig()); + HazelcastClientKeyValueStoreInfo settings = new HazelcastClientKeyValueStoreInfo(); + settings.setClusterName(CLUSTER); + settings.setMembers( + "127.0.0.1:" + member.getCluster().getLocalMember().getAddress().getPort()); + // the store the cache would build, which makes the client connection lock on its cluster + try (KeyValueStore store = settings.createStore()) { + IMap clusterLocks = member.getMap("gwc-tiles.locks"); + // the client connects in the background, locks stay local until then + await().atMost(30, SECONDS).untilAsserted(() -> { + Lock lock = locks.getLock("metatile"); + try { + assertTrue(clusterLocks.isLocked("metatile")); + } finally { + lock.release(); + } + }); + assertFalse(clusterLocks.isLocked("metatile")); + } finally { + member.shutdown(); + } + } + + /** A member on the loopback interface only, finding no other member. */ + @SuppressWarnings("PMD.AvoidUsingHardCodedIP") + private static Config memberConfig() { + Config config = new Config().setClusterName(CLUSTER); + config.setProperty("hazelcast.phone.home.enabled", "false"); + config.setProperty("hazelcast.socket.bind.any", "false"); + config.getNetworkConfig().getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + JoinConfig join = config.getNetworkConfig().getJoin(); + join.getAutoDetectionConfig().setEnabled(false); + join.getMulticastConfig().setEnabled(false); + return config; + } +} diff --git a/geowebcache/web/src/test/java/org/geowebcache/jetty/RestIntegrationTest.java b/geowebcache/web/src/test/java/org/geowebcache/jetty/RestIntegrationTest.java index f3861bdf2a..22a3c7146d 100644 --- a/geowebcache/web/src/test/java/org/geowebcache/jetty/RestIntegrationTest.java +++ b/geowebcache/web/src/test/java/org/geowebcache/jetty/RestIntegrationTest.java @@ -1201,6 +1201,29 @@ public void testNewFileBlobstoreDontDeleteExistingContent() throws Exception { /* Utility methods ***************************************************************************/ + @Test + public void testPutMemoryCacheHazelcastBackend() throws Exception { + // disabled, so that no client starts on the unreachable member + String settings = + """ + + false + + tiles + localhost:1 + + """; + URI memoryCache = URI.create("/geowebcache/rest/memorycache"); + try (CloseableHttpResponse response = handlePut(memoryCache, admin.getClient(), settings)) { + assertEquals(200, response.getStatusLine().getStatusCode()); + } + + doGetXML("rest/memorycache.xml", admin.getClient(), equalTo(200), doc -> { + assertThat(doc, hasXPath("/memoryCache/backend/@class", equalTo("hazelcastClientKeyValueStore"))); + assertThat(doc, hasXPath("/memoryCache/backend/members", equalTo("localhost:1"))); + }); + } + private Document getResponseEntityAsXML(CloseableHttpResponse response) throws Exception { Document doc =