Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,49 +18,73 @@

import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.distributed.cache.client.AtomicCacheEntry;
import org.apache.nifi.distributed.cache.client.AtomicDistributedMapCacheClient;
import org.apache.nifi.distributed.cache.client.Deserializer;
import org.apache.nifi.distributed.cache.client.Serializer;
import org.apache.nifi.redis.RedisConnectionPool;
import org.apache.nifi.redis.RedisType;
import org.apache.nifi.util.Tuple;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.connection.SetCondition;
import org.springframework.data.redis.core.types.Expiration;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static org.apache.nifi.redis.util.RedisUtils.REDIS_CONNECTION_POOL;
import java.nio.charset.StandardCharsets;

@Tags({ "redis", "distributed", "cache", "map" })
@CapabilityDescription("An implementation of DistributedMapCacheClient that uses Redis as the backing cache. This service relies on " +
"the WATCH, MULTI, and EXEC commands in Redis, which are not fully supported when Redis is clustered. As a result, this service " +
"can only be used with a Redis Connection Pool that is configured for standalone or sentinel mode. Sentinel mode can be used to " +
"provide high-availability configurations.")
@CapabilityDescription("An implementation of AtomicDistributedMapCacheClient that uses Redis as the backing cache, including " +
Comment thread
alberttwong marked this conversation as resolved.
Resolved
"Redis Enterprise Software and Redis Cloud. Atomic operations use single-key Lua scripts and require permission to execute EVAL. " +
"Use standalone mode for a Redis Enterprise or Redis Cloud database endpoint, or cluster mode for an endpoint with the Redis Cluster API enabled. " +
"Atomicity applies to the Redis endpoint and does not provide coordination across Active-Active regions.")
public class RedisDistributedMapCacheClientService extends SimpleRedisDistributedMapCacheClientService implements AtomicDistributedMapCacheClient<byte[]> {

@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
final List<ValidationResult> results = new ArrayList<>();
private static final byte[] GET_AND_PUT_IF_ABSENT_SCRIPT = """
local current = redis.call('GET', KEYS[1])
if current then
return current
end
if tonumber(ARGV[2]) > 0 then
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
else
redis.call('SET', KEYS[1], ARGV[1])
end
return false
""".getBytes(StandardCharsets.UTF_8);

private static final byte[] REPLACE_SCRIPT = """
local current = redis.call('GET', KEYS[1])
if ARGV[1] == '0' then
if current then
return 0
end
elseif current ~= ARGV[2] then
return 0
end
if tonumber(ARGV[4]) > 0 then
redis.call('SET', KEYS[1], ARGV[3], 'EX', ARGV[4])
else
redis.call('SET', KEYS[1], ARGV[3])
end
return 1
""".getBytes(StandardCharsets.UTF_8);

final RedisConnectionPool redisConnectionPool = validationContext.getProperty(REDIS_CONNECTION_POOL).asControllerService(RedisConnectionPool.class);
if (redisConnectionPool != null) {
final RedisType redisType = redisConnectionPool.getRedisType();
if (redisType != null && redisType == RedisType.CLUSTER) {
results.add(new ValidationResult.Builder()
.subject(REDIS_CONNECTION_POOL.getDisplayName())
.valid(false)
.explanation(REDIS_CONNECTION_POOL.getDisplayName()
+ " is configured in clustered mode, and this service requires a non-clustered Redis")
.build());
}
}
@Override
public <K, V> boolean putIfAbsent(final K key, final V value, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws IOException {
return withConnection(redisConnection -> {
final Tuple<byte[], byte[]> kv = serialize(key, value, keySerializer, valueSerializer);
return Boolean.TRUE.equals(redisConnection.stringCommands().set(kv.getKey(), kv.getValue(),
SetCondition.ifAbsent(), Expiration.seconds(getTtl())));
});
}

return results;
@Override
public <K, V> V getAndPutIfAbsent(final K key, final V value, final Serializer<K> keySerializer,
final Serializer<V> valueSerializer, final Deserializer<V> valueDeserializer) throws IOException {
return withConnection(redisConnection -> {
final Tuple<byte[], byte[]> kv = serialize(key, value, keySerializer, valueSerializer);
final byte[] previous = redisConnection.scriptingCommands().eval(GET_AND_PUT_IF_ABSENT_SCRIPT, ReturnType.VALUE, 1,
kv.getKey(), kv.getValue(), getTtl().toString().getBytes(StandardCharsets.UTF_8));
return previous == null ? null : valueDeserializer.deserialize(previous);
});
}

@Override
Expand All @@ -81,50 +105,13 @@ public <K, V> AtomicCacheEntry<K, V, byte[]> fetch(final K key, final Serializer
@Override
public <K, V> boolean replace(final AtomicCacheEntry<K, V, byte[]> entry, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws IOException {
return withConnection(redisConnection -> {
final ByteArrayOutputStream out = new ByteArrayOutputStream();

keySerializer.serialize(entry.getKey(), out);
final byte[] k = out.toByteArray();
out.reset();

valueSerializer.serialize(entry.getValue(), out);
final byte[] newVal = out.toByteArray();

// the revision of the cache entry holds the value of the key from a previous fetch
final byte[] prevVal = entry.getRevision().orElse(null);

boolean replaced = false;

// start a watch on the key and retrieve the current value
redisConnection.watch(k);
final byte[] currValue = redisConnection.stringCommands().get(k);

// start a transaction
redisConnection.multi();

// compare-and-set
if (Arrays.equals(prevVal, currValue)) {
// if we use set(k, newVal) then the results list will always have size == 0 b/c when convertPipelineAndTxResults is set to true,
// status responses like "OK" are skipped over, so by using getSet we can rely on the results list to know if the transaction succeeded
redisConnection.stringCommands().getSet(k, newVal);

// set the TTL if specified
final long ttl = getTtl();
if (ttl != -1L) {
redisConnection.keyCommands().expire(k, ttl);
}
}

// execute the transaction
final List<Object> results = redisConnection.exec();

// if we have a result then the replace succeeded
if (results != null && !results.isEmpty()) {
replaced = true;
}

return replaced;
final Tuple<byte[], byte[]> kv = serialize(entry.getKey(), entry.getValue(), keySerializer, valueSerializer);
// Keep the existing raw-value revision format, including the distinction between an absent key and an empty value.
final byte[] previous = entry.getRevision().orElse(null);
final Long result = redisConnection.scriptingCommands().eval(REPLACE_SCRIPT, ReturnType.INTEGER, 1,
kv.getKey(), (previous == null ? "0" : "1").getBytes(StandardCharsets.UTF_8),
previous == null ? new byte[0] : previous, kv.getValue(), getTtl().toString().getBytes(StandardCharsets.UTF_8));
return Long.valueOf(1).equals(result);
});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!DOCTYPE html>
Comment thread
alberttwong marked this conversation as resolved.
Resolved
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">
<head><meta charset="UTF-8"><title>Redis Distributed Map Cache</title></head>
<body>
<h2>Redis Enterprise Software and Redis Cloud</h2>
<p>Configure a RedisConnectionPoolService and select it as the Redis Connection Pool for this service.</p>
<table>
<tr><th>Connection pool property</th><th>Value</th></tr>
<tr><td>Redis Mode</td><td>Standalone for a database endpoint that routes commands through the Redis proxy, including sharded databases.
Select Cluster only if the endpoint exposes the Redis Cluster API and its advertised nodes are reachable from NiFi.</td></tr>
<tr><td>Connection String</td><td>The database endpoint as hostname:port. Use the database endpoint, not a management console or REST API endpoint.
Do not include a redis:// or rediss:// scheme.</td></tr>
<tr><td>Database Index</td><td>0. Redis Enterprise Software and Redis Cloud identify databases by endpoint.</td></tr>
<tr><td>Username</td><td>The database ACL user, or default when using the default user.</td></tr>
<tr><td>Password</td><td>The database user's password, supplied through a sensitive parameter.</td></tr>
<tr><td>SSL Context Service</td><td>Configure this when the database endpoint requires TLS.
Trust the database CA, and supply a client certificate and private key when mutual TLS is required.</td></tr>
</table>
<p>Standalone describes the client connection topology. It does not require an unsharded Redis server and does not disable
the availability or sharding provided by the Redis database endpoint.</p>
<h2>Atomic operations and permissions</h2>
<p>Conditional insert and replace operations act on one key at a time. The get-and-insert and compare-and-set operations use EVAL
with a single explicitly declared key, keeping the read, conditional write, and TTL update together on the server.
WATCH, MULTI, and EXEC are not required. Scripts and values are binary safe. Existing keys, values, and raw-value revisions
retain their format.</p>
<p>The Redis user needs permission for EVAL and the commands executed by these scripts (GET and SET), as well as commands
used by the cache operations the flow calls (including EXISTS, DEL, MSET, and EXPIRE). Configure key permissions for the
serialized cache keys. A server configured to prohibit scripting cannot use this atomic cache service.</p>
<p>TTL is applied when an entry is inserted or successfully replaced. A failed comparison or an insert against an existing key
leaves the value and its expiration unchanged. A TTL of 0 secs creates entries without expiration.</p>
<h2>Deployment considerations</h2>
<p>Single-key atomicity applies at the endpoint executing the operation. Redis Active-Active replication does not provide a
globally serialized compare-and-set across regions. Flows that require global coordination, such as duplicate detection or
Wait/Notify, should use one authoritative database rather than independent writable Active-Active regions.</p>
<p>Bulk putAll retains its existing MSET behavior; it does not promise a transaction across multiple hash slots.
Follow the database's multi-key command restrictions and use a common hash tag when a deployment requires keys in one slot.</p>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.redis.service;

/**
* Runs the atomic cache contract against the Redis Cluster API, with all hash slots assigned to one node.
* This exercises cluster command routing without requiring fixed Docker host ports or a multi-node network.
*/
public class ITRedisClusterDistributedMapCacheClientService extends ITRedisDistributedMapCacheClientService {
Comment thread
alberttwong marked this conversation as resolved.
Resolved

@Override
protected String getRedisMode() {
return "Cluster";
}
}
Loading
Loading