summaryrefslogtreecommitdiff
path: root/src/server.c
diff options
context:
space:
mode:
authorranshid <88133677+ranshid@users.noreply.github.com>2023-01-01 23:35:42 +0200
committerGitHub <noreply@github.com>2023-01-01 23:35:42 +0200
commit383d902ce68131cf40d6122ce09e305e672e8555 (patch)
tree8a5b6760cecfe99f9eaad0881a386f4c86680979 /src/server.c
parentaf0a4fe20771603f0eab75a1f60748d124cf33c3 (diff)
downloadredis-383d902ce68131cf40d6122ce09e305e672e8555.tar.gz
reprocess command when client is unblocked on keys (#11012)
*TL;DR* --------------------------------------- Following the discussion over the issue [#7551](https://github.com/redis/redis/issues/7551) We decided to refactor the client blocking code to eliminate some of the code duplications and to rebuild the infrastructure better for future key blocking cases. *In this PR* --------------------------------------- 1. reprocess the command once a client becomes unblocked on key (instead of running custom code for the unblocked path that's different than the one that would have run if blocking wasn't needed) 2. eliminate some (now) irrelevant code for handling unblocking lists/zsets/streams etc... 3. modify some tests to intercept the error in cases of error on reprocess after unblock (see details in the notes section below) 4. replace '$' on the client argv with current stream id. Since once we reprocess the stream XREAD we need to read from the last msg and not wait for new msg in order to prevent endless block loop. 5. Added statistics to the info "Clients" section to report the: * `total_blocking_keys` - number of blocking keys * `total_blocking_keys_on_nokey` - number of blocking keys which have at least 1 client which would like to be unblocked on when the key is deleted. 6. Avoid expiring unblocked key during unblock. Previously we used to lookup the unblocked key which might have been expired during the lookup. Now we lookup the key using NOTOUCH and NOEXPIRE to avoid deleting it at this point, so propagating commands in blocked.c is no longer needed. 7. deprecated command flags. We decided to remove the CMD_CALL_STATS and CMD_CALL_SLOWLOG and make an explicit verification in the call() function in order to decide if stats update should take place. This should simplify the logic and also mitigate existing issues: for example module calls which are triggered as part of AOF loading might still report stats even though they are called during AOF loading. *Behavior changes* --------------------------------------------------- 1. As this implementation prevents writing dedicated code handling unblocked streams/lists/zsets, since we now re-process the command once the client is unblocked some errors will be reported differently. The old implementation used to issue ``UNBLOCKED the stream key no longer exists`` in the following cases: - The stream key has been deleted (ie. calling DEL) - The stream and group existed but the key type was changed by overriding it (ie. with set command) - The key not longer exists after we swapdb with a db which does not contains this key - After swapdb when the new db has this key but with different type. In the new implementation the reported errors will be the same as if the command was processed after effect: **NOGROUP** - in case key no longer exists, or **WRONGTYPE** in case the key was overridden with a different type. 2. Reprocessing the command means that some checks will be reevaluated once the client is unblocked. For example, ACL rules might change since the command originally was executed and will fail once the client is unblocked. Another example is OOM condition checks which might enable the command to run and block but fail the command reprocess once the client is unblocked. 3. One of the changes in this PR is that no command stats are being updated once the command is blocked (all stats will be updated once the client is unblocked). This implies that when we have many clients blocked, users will no longer be able to get that information from the command stats. However the information can still be gathered from the client list. **Client blocking** --------------------------------------------------- the blocking on key will still be triggered the same way as it is done today. in order to block the current client on list of keys, the call to blockForKeys will still need to be made which will perform the same as it is today: * add the client to the list of blocked clients on each key * keep the key with a matching list node (position in the global blocking clients list for that key) in the client private blocking key dict. * flag the client with CLIENT_BLOCKED * update blocking statistics * register the client on the timeout table **Key Unblock** --------------------------------------------------- Unblocking a specific key will be triggered (same as today) by calling signalKeyAsReady. the implementation in that part will stay the same as today - adding the key to the global readyList. The reason to maintain the readyList (as apposed to iterating over all clients blocked on the specific key) is in order to keep the signal operation as short as possible, since it is called during the command processing. The main change is that instead of going through a dedicated code path that operates the blocked command we will just call processPendingCommandsAndResetClient. **ClientUnblock (keys)** --------------------------------------------------- 1. Unblocking clients on keys will be triggered after command is processed and during the beforeSleep 8. the general schema is: 9. For each key *k* in the readyList: ``` For each client *c* which is blocked on *k*: in case either: 1. *k* exists AND the *k* type matches the current client blocking type OR 2. *k* exists and *c* is blocked on module command OR 3. *k* does not exists and *c* was blocked with the flag unblock_on_deleted_key do: 1. remove the client from the list of clients blocked on this key 2. remove the blocking list node from the client blocking key dict 3. remove the client from the timeout list 10. queue the client on the unblocked_clients list 11. *NEW*: call processCommandAndResetClient(c); ``` *NOTE:* for module blocked clients we will still call the moduleUnblockClientByHandle which will queue the client for processing in moduleUnblockedClients list. **Process Unblocked clients** --------------------------------------------------- The process of all unblocked clients is done in the beforeSleep and no change is planned in that part. The general schema will be: For each client *c* in server.unblocked_clients: * remove client from the server.unblocked_clients * set back the client readHandler * continue processing the pending command and input buffer. *Some notes regarding the new implementation* --------------------------------------------------- 1. Although it was proposed, it is currently difficult to remove the read handler from the client while it is blocked. The reason is that a blocked client should be unblocked when it is disconnected, or we might consume data into void. 2. While this PR mainly keep the current blocking logic as-is, there might be some future additions to the infrastructure that we would like to have: - allow non-preemptive blocking of client - sometimes we can think that a new kind of blocking can be expected to not be preempt. for example lets imagine we hold some keys on disk and when a command needs to process them it will block until the keys are uploaded. in this case we will want the client to not disconnect or be unblocked until the process is completed (remove the client read handler, prevent client timeout, disable unblock via debug command etc...). - allow generic blocking based on command declared keys - we might want to add a hook before command processing to check if any of the declared keys require the command to block. this way it would be easier to add new kinds of key-based blocking mechanisms. Co-authored-by: Oran Agra <oran@redislabs.com> Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Diffstat (limited to 'src/server.c')
-rw-r--r--src/server.c134
1 files changed, 82 insertions, 52 deletions
diff --git a/src/server.c b/src/server.c
index 380b20d32..eaad37c07 100644
--- a/src/server.c
+++ b/src/server.c
@@ -92,6 +92,10 @@ const char *replstateToString(int replstate);
/*============================ Utility functions ============================ */
+/* This macro tells if we are in the context of loading an AOF. */
+#define isAOFLoadingContext() \
+ ((server.current_client && server.current_client->id == CLIENT_ID_AOF) ? 1 : 0)
+
/* We use a private localtime implementation which is fork-safe. The logging
* function of Redis may be called from other threads. */
void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst);
@@ -3374,8 +3378,6 @@ int incrCommandStatsOnError(struct redisCommand *cmd, int flags) {
*
* The following flags can be passed:
* CMD_CALL_NONE No flags.
- * CMD_CALL_SLOWLOG Check command speed and log in the slow log if needed.
- * CMD_CALL_STATS Populate command stats.
* CMD_CALL_PROPAGATE_AOF Append command to AOF if it modified the dataset
* or if the client flags are forcing propagation.
* CMD_CALL_PROPAGATE_REPL Send command to slaves if it modified the dataset
@@ -3411,6 +3413,15 @@ void call(client *c, int flags) {
long long dirty;
uint64_t client_old_flags = c->flags;
struct redisCommand *real_cmd = c->realcmd;
+ /* When call() is issued during loading the AOF we don't want commands called
+ * from module, exec or LUA to go into the slowlog or to populate statistics. */
+ int update_command_stats = !isAOFLoadingContext();
+
+ /* We want to be aware of a client which is making a first time attempt to execute this command
+ * and a client which is reprocessing command again (after being unblocked).
+ * Blocked clients can be blocked in different places and not always it means the call() function has been
+ * called. For example this is required for avoiding double logging to monitors.*/
+ int reprocessing_command = ((!server.execution_nesting) && (c->flags & CLIENT_EXECUTING_COMMAND)) ? 1 : 0;
/* Initialization: clear the flags that must be set by the command on
* demand, and initialize the array for additional commands propagation. */
@@ -3429,10 +3440,11 @@ void call(client *c, int flags) {
const long long call_timer = ustime();
- /* Update cache time, in case we have nested calls we want to
- * update only on the first call */
+ /* Update cache time, and indicate we are starting command execution.
+ * in case we have nested calls we want to update only on the first call */
if (server.execution_nesting++ == 0) {
updateCachedTimeWithUs(0,call_timer);
+ c->flags |= CLIENT_EXECUTING_COMMAND;
}
monotime monotonic_start = 0;
@@ -3440,7 +3452,13 @@ void call(client *c, int flags) {
monotonic_start = getMonotonicUs();
c->cmd->proc(c);
- server.execution_nesting--;
+
+ if (--server.execution_nesting == 0) {
+ /* In case client is blocked after trying to execute the command,
+ * it means the execution is not yet completed and we MIGHT reprocess the command in the future. */
+ if (!(c->flags & CLIENT_BLOCKED))
+ c->flags &= ~(CLIENT_EXECUTING_COMMAND);
+ }
/* In order to avoid performance implication due to querying the clock using a system call 3 times,
* we use a monotonic clock, when we are sure its cost is very low, and fall back to non-monotonic call otherwise. */
@@ -3450,7 +3468,7 @@ void call(client *c, int flags) {
else
duration = ustime() - call_timer;
- c->duration = duration;
+ c->duration += duration;
dirty = server.dirty-dirty;
if (dirty < 0) dirty = 0;
@@ -3471,11 +3489,6 @@ void call(client *c, int flags) {
c->flags |= CLIENT_CLOSE_AFTER_REPLY;
}
- /* When EVAL is called loading the AOF we don't want commands called
- * from Lua to go into the slowlog or to populate statistics. */
- if (server.loading && c->flags & CLIENT_SCRIPT)
- flags &= ~(CMD_CALL_SLOWLOG | CMD_CALL_STATS);
-
/* If the caller is Lua, we want to force the EVAL caller to propagate
* the script if the command flag or client flag are forcing the
* propagation. */
@@ -3493,7 +3506,7 @@ void call(client *c, int flags) {
/* Record the latency this command induced on the main thread.
* unless instructed by the caller not to log. (happens when processing
* a MULTI-EXEC from inside an AOF). */
- if (flags & CMD_CALL_SLOWLOG) {
+ if (update_command_stats) {
char *latency_event = (real_cmd->flags & CMD_FAST) ?
"fast-command" : "command";
latencyAddSampleIfNeeded(latency_event,duration/1000);
@@ -3501,12 +3514,15 @@ void call(client *c, int flags) {
/* Log the command into the Slow log if needed.
* If the client is blocked we will handle slowlog when it is unblocked. */
- if ((flags & CMD_CALL_SLOWLOG) && !(c->flags & CLIENT_BLOCKED))
- slowlogPushCurrentCommand(c, real_cmd, duration);
-
- /* Send the command to clients in MONITOR mode if applicable.
- * Administrative commands are considered too dangerous to be shown. */
- if (!(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN))) {
+ if (update_command_stats && !(c->flags & CLIENT_BLOCKED))
+ slowlogPushCurrentCommand(c, real_cmd, c->duration);
+
+ /* Send the command to clients in MONITOR mode if applicable,
+ * since some administrative commands are considered too dangerous to be shown.
+ * Other exceptions is a client which is unblocked and retring to process the command
+ * or we are currently in the process of loading AOF. */
+ if (update_command_stats && !reprocessing_command &&
+ !(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN))) {
robj **argv = c->original_argv ? c->original_argv : c->argv;
int argc = c->original_argv ? c->original_argc : c->argc;
replicationFeedMonitors(c,server.monitors,c->db->id,argv,argc);
@@ -3517,13 +3533,13 @@ void call(client *c, int flags) {
if (!(c->flags & CLIENT_BLOCKED))
freeClientOriginalArgv(c);
- /* populate the per-command statistics that we show in INFO commandstats. */
- if (flags & CMD_CALL_STATS) {
- real_cmd->microseconds += duration;
+ /* populate the per-command statistics that we show in INFO commandstats.
+ * If the client is blocked we will handle latency stats and duration when it is unblocked. */
+ if (update_command_stats && !(c->flags & CLIENT_BLOCKED)) {
real_cmd->calls++;
- /* If the client is blocked we will handle latency stats when it is unblocked. */
+ real_cmd->microseconds += c->duration;
if (server.latency_tracking_enabled && !(c->flags & CLIENT_BLOCKED))
- updateCommandLatencyHistogram(&(real_cmd->latency_histogram), duration*1000);
+ updateCommandLatencyHistogram(&(real_cmd->latency_histogram), c->duration*1000);
}
/* Propagate the command into the AOF and replication link.
@@ -3584,7 +3600,8 @@ void call(client *c, int flags) {
}
}
- server.stat_numcommands++;
+ if (!(c->flags & CLIENT_BLOCKED))
+ server.stat_numcommands++;
/* Record peak memory after each command and before the eviction that runs
* before the next command. */
@@ -3735,6 +3752,10 @@ int processCommand(client *c) {
moduleCallCommandFilters(c);
+ /* in case we are starting to ProcessCommand and we already have a command we assume
+ * this is a reprocessing of this command, so we do not want to perform some of the actions again. */
+ int client_reprocessing_command = c->cmd ? 1 : 0;
+
/* Handle possible security attacks. */
if (!strcasecmp(c->argv[0]->ptr,"host:") || !strcasecmp(c->argv[0]->ptr,"post")) {
securityWarningCommand(c);
@@ -3746,36 +3767,40 @@ int processCommand(client *c) {
if (server.busy_module_yield_flags != BUSY_MODULE_YIELD_NONE &&
!(server.busy_module_yield_flags & BUSY_MODULE_YIELD_CLIENTS))
{
- c->bpop.timeout = 0;
- blockClient(c,BLOCKED_POSTPONE);
+ blockPostponeClient(c);
return C_OK;
}
/* Now lookup the command and check ASAP about trivial error conditions
- * such as wrong arity, bad command name and so forth. */
- c->cmd = c->lastcmd = c->realcmd = lookupCommand(c->argv,c->argc);
- sds err;
- if (!commandCheckExistence(c, &err)) {
- rejectCommandSds(c, err);
- return C_OK;
- }
- if (!commandCheckArity(c, &err)) {
- rejectCommandSds(c, err);
- return C_OK;
- }
-
- /* Check if the command is marked as protected and the relevant configuration allows it */
- if (c->cmd->flags & CMD_PROTECTED) {
- if ((c->cmd->proc == debugCommand && !allowProtectedAction(server.enable_debug_cmd, c)) ||
- (c->cmd->proc == moduleCommand && !allowProtectedAction(server.enable_module_cmd, c)))
- {
- rejectCommandFormat(c,"%s command not allowed. If the %s option is set to \"local\", "
- "you can run it from a local connection, otherwise you need to set this option "
- "in the configuration file, and then restart the server.",
- c->cmd->proc == debugCommand ? "DEBUG" : "MODULE",
- c->cmd->proc == debugCommand ? "enable-debug-command" : "enable-module-command");
+ * such as wrong arity, bad command name and so forth.
+ * In case we are reprocessing a command after it was blocked,
+ * we do not have to repeat the same checks */
+ if (!client_reprocessing_command) {
+ c->cmd = c->lastcmd = c->realcmd = lookupCommand(c->argv,c->argc);
+ sds err;
+ if (!commandCheckExistence(c, &err)) {
+ rejectCommandSds(c, err);
+ return C_OK;
+ }
+ if (!commandCheckArity(c, &err)) {
+ rejectCommandSds(c, err);
return C_OK;
+ }
+
+ /* Check if the command is marked as protected and the relevant configuration allows it */
+ if (c->cmd->flags & CMD_PROTECTED) {
+ if ((c->cmd->proc == debugCommand && !allowProtectedAction(server.enable_debug_cmd, c)) ||
+ (c->cmd->proc == moduleCommand && !allowProtectedAction(server.enable_module_cmd, c)))
+ {
+ rejectCommandFormat(c,"%s command not allowed. If the %s option is set to \"local\", "
+ "you can run it from a local connection, otherwise you need to set this option "
+ "in the configuration file, and then restart the server.",
+ c->cmd->proc == debugCommand ? "DEBUG" : "MODULE",
+ c->cmd->proc == debugCommand ? "enable-debug-command" : "enable-module-command");
+ return C_OK;
+
+ }
}
}
@@ -4028,8 +4053,7 @@ int processCommand(client *c) {
((isPausedActions(PAUSE_ACTION_CLIENT_ALL)) ||
((isPausedActions(PAUSE_ACTION_CLIENT_WRITE)) && is_may_replicate_command)))
{
- c->bpop.timeout = 0;
- blockClient(c,BLOCKED_POSTPONE);
+ blockPostponeClient(c);
return C_OK;
}
@@ -5444,7 +5468,9 @@ sds genRedisInfoString(dict *section_dict, int all_sections, int everything) {
/* Clients */
if (all_sections || (dictFind(section_dict,"clients") != NULL)) {
size_t maxin, maxout;
+ unsigned long blocking_keys, blocking_keys_on_nokey;
getExpansiveClientsInfo(&maxin,&maxout);
+ totalNumberOfBlockingKeys(&blocking_keys, &blocking_keys_on_nokey);
if (sections++) info = sdscat(info,"\r\n");
info = sdscatprintf(info,
"# Clients\r\n"
@@ -5455,14 +5481,18 @@ sds genRedisInfoString(dict *section_dict, int all_sections, int everything) {
"client_recent_max_output_buffer:%zu\r\n"
"blocked_clients:%d\r\n"
"tracking_clients:%d\r\n"
- "clients_in_timeout_table:%llu\r\n",
+ "clients_in_timeout_table:%llu\r\n"
+ "total_blocking_keys:%lu\r\n"
+ "total_blocking_keys_on_nokey:%lu\r\n",
listLength(server.clients)-listLength(server.slaves),
getClusterConnectionsCount(),
server.maxclients,
maxin, maxout,
server.blocked_clients,
server.tracking_clients,
- (unsigned long long) raxSize(server.clients_timeout_table));
+ (unsigned long long) raxSize(server.clients_timeout_table),
+ blocking_keys,
+ blocking_keys_on_nokey);
}
/* Memory */