Unverified Commit 64f61596 authored by Oran Agra's avatar Oran Agra Committed by GitHub
Browse files

Merge Redis Functions PR (#9780)

# Redis Function
This PR added the Redis Functions capabilities that were suggested on #8693.
The PR also introduce a big refactoring to the current Lua implementation
(i.e `scripting.c`). The main purpose of the refactoring is to have better
code sharing between the Lua implementation that exists today on Redis
(`scripting.c`) and the new Lua engine that is introduced on this PR.
The refactoring includes code movements and file name changes as well as some
logic changes that need to be carefully reviewed. To make the review easier,
the PR was split into multiple commits. Each commit is deeply described later on
but the main concept is that some commits are just moving code around without
making any logical changes, those commits are less likely to cause any issues
or regressions and can be reviewed fast. Other commits, which perform code and
logic changes, need to be reviewed carefully, but those commits were created
after the code movements so it's pretty easy to see what was changed. To sum up,
it is highly recommended to review this PR commit by commit as it will be easier
to see the changes, it is also recommended to read each commit description
(written below) to understand what was changed on the commit and whether or not
it's just a huge code movement or a logic changes.

## Terminology
Currently, the terminology in Redis is not clearly defined. Scripts refer to Lua
scripts and eval also refers only to Lua. Introducing Redis Function requires
redefining those terms to be able to clearly understand what is been discussed
on each context.
* eval - legacy Lua script implementation.
* Function - new scripting implementation (currently implemented in Lua but in
  the future, it might be other languages like javascript).
* Engine - the component that is responsible for executing functions.
* Script - Function or legacy Lua (executed with `eval` or `evalsha`)

## Refactoring New Structure
Today, the entire scripting logic is located on `scripting.c`. This logic can
be split into 3 main groups:
1. Script management - responsible for storing the scripts that were sent to
   Redis and retrieving them when they need to be run (base on the script sha
   on the current implementation).
2. Script invocation - invoke the script given on `eval` or `evalsha` command
   (this part includes finding the relevant script, preparing the arguments, ..)
3. Interact back with Redis (command invocation)

Those 3 groups are tightly coupled on `scripting.c`. Redis Functions also need
to use those groups logics, for example,  to interact back with Redis or to
execute Lua code. The refactoring attempts to split those 3 groups and define
APIs so that we can reuse the code both on legacy Lua scripts and Redis Functions.

In order to do so we define the following units:
1. script.c: responsible for interaction with Redis from within a script.
2. script_lua.c: responsible to execute Lua code, uses `script.c` to interact
   with Redis from within the Lua code.
3. function_lua.c: contains the Lua engine implementation, uses `script_lua.c`
   to execute the Lua code.
4. functions.c: Contains Redis Functions implementation (`FUNCTION` command,),
   uses `functions_lua.c` if the function it wants to invoke needs the Lua
   engine.
4. eval.c: the original `scripting.c` contains the Lua legacy implementation and
   was refactored to use `script_lua.c` to invoke the Lua code.

## Commits breakdown
Notice: Some small commits are omitted from this list as they are small and
insignificant (for example build fixes)

### First commit - code movements
This commit rename `scripting.c` -> `eval.c` and introduce the new `script_lua.c`
unit. The commit moves relevant code from `eval.c` (`scripting.c`) to
`script_lua.c`, the purpose of moving the code is so that later we will be able
to re-use the code on the Lua engine (`function_lua.c`). The commit only moves
the code without modifying even a single line, so there is a very low risk of
breaking anything and it also makes it much easier to see the changes on the
following commits.
Because the commit does not change the code (only moves it), it does not compile.
But we do not care about it as the only purpose here is to make the review
processes simpler.

### Second commit - move legacy Lua variables into `eval.c`
Today, all Lua-related variables are located on the server struct. The commit
attempt to identify those variable and take them out from the server struct,
leaving only script related variables (variables that later need to be used
also by engines)
The following variable where renamed and left on the server struct:
   * lua_caller 			-> script_caller
   * lua_time_limit 		-> script_time_limit
   * lua_timedout 		-> script_timedout
   * lua_oom 			-> script_oom
   * lua_disable_deny_script 	-> script_disable_deny_script
   * in_eval			-> in_script

The following variables where moved to lctx under eval.c
   * lua
   * lua_client
   * lua_cur_script
   * lua_scripts
   * lua_scripts_mem
   * lua_replicate_commands
   * lua_write_dirty
   * lua_random_dirty
   * lua_multi_emitted
   * lua_repl
   * lua_kill
   * lua_time_start
   * lua_time_snapshot

This commit is in a low risk of introducing any issues and it is just moving
variables around and not changing any logic.

### Third commit - introducing script unit
This commit introduces the `script.c` unit. Its purpose (as described above) is
to provide an API for scripts to interact with Redis. Interaction includes
mostly executing commands, but also other functionalities. The interaction is
done using a `ScriptRunCtx` object that needs to be created by the user and
initialized using `scriptPrepareForRun`. A detailed list of functionalities
expose by the unit:
1. Calling commands (including all the validation checks such as
   acl, cluster, read only run, ...)
2. Set Resp
3. Set Replication method (AOF/REPLICATION/NONE)
4. Call Redis back on long-running scripts to allow Redis to reply to clients
   and perform script kill

The commit introduces the new unit and uses it on eval commands to interact with
Redis.

### Fourth commit - Moved functionality of invoke Lua code to `script_lua.c`
This commit moves the logic of invoking the Lua code into `script_lua.c` so
later it can be used also by Lua engine (`function_lua.c`). The code is located
on `callFunction` function and assumes the Lua function already located on the
top of the Lua stack. This commit also change `eval.c` to use the new
functionality to invoke Lua code.

### Fith commit - Added Redis Functions unit (`functions.c`) and Lua engine
(`function_lua.c`)
Added Redis Functions unit under `functions.c`, included:
1. FUNCTION command:
     * FUNCTION CREATE
     * FUNCTION CALL
     * FUNCTION DELETE
     * FUNCTION KILL
     * FUNCTION INFO
     * FUNCTION STATS
2. Register engines

In addition, this commit introduces the first engine that uses the Redis
Functions capabilities, the Lua engine (`function_lua.c`)

## API Changes
### `lua-time-limit`
configuration was renamed to `script-time-limit` (keep `lua-time-limit` as alias
for backward compatibility).

### Error log changes
When integrating with Redis from within a Lua script, the `Lua` term was removed
from all the error messages and instead we write only `script`. For example:
`Wrong number of args calling Redis command From Lua script` -> `Wrong number
of args calling Redis command From script`

### `info memory` changes:
Before stating all the changes made to memory stats we will try to explain the
reason behind them and what we want to see on those metrics:
* memory metrics should show both totals (for all scripting frameworks), as well
  as a breakdown per framework / vm.
* The totals metrics should have "human" metrics while the breakdown shouldn't.
* We did try to maintain backward compatibility in some way, that said we did
  make some repurpose to existing metrics where it looks reasonable.
* We separate between memory used by the script framework (part of redis's
  used_memory), and memory used by the VM (not part of redis's used_memory)

A full breakdown of `info memory` changes:
* `used_memory_lua` and `used_memory_lua_human` was deprecated,
  `used_memory_vm_eval` has the same meaning as `used_memory_lua`
* `used_memory_scripts` was renamed to `used_memory_scripts_eval`
* `used_memory_scripts` and `used_memory_scripts_human` were repurposed and now
  return the total memory used by functions and eval (not including vm memory,
  only code cache, and structs).
* `used_memory_vm_function` was added and represents the total memory used by
  functions vm's
* `used_memory_functions` was added and represents the total memory by functions
  (not including vm memory, only code cache, and structs)
* `used_memory_vm_total` and `used_memory_vm_total_human` was added and
  represents the total memory used by vm's (functions and eval combined)

### `functions.caches`
`functions.caches` field was added to `memory stats`, representing the memory
used by engines that are not functions (this memory includes data structures
like dictionaries, arrays, ...)

## New API
### FUNCTION CREATE

Usage: FUNCTION CREATE `ENGINE` `NAME` `[REPLACE]` `[DESC <DESCRIPTION>]` `<CODE>`

* `ENGINE` - The name of the engine to use to create the script.
* `NAME` - the name of the function that can be used later to call the function
  using `FUNCTION CALL` command.
* `REPLACE` - if given, replace the given function with the existing function
  (if exists).
* `DESCRIPTION` - optional argument describing the function and what it does
* `CODE` - function code.

The command will return `OK` if created successfully or error in the following
cases:
* The given engine name does not exist
* The function name is already taken and `REPLACE` was not used.
* The given function failed on the compilation.

### FCALL and FCALL_RO

Usage: FCALL/FCALL_RO `NAME` `NUM_KEYS key1 key2` … ` arg1 arg2`

Call and execute the function specified by `NAME`. The function will receive
all arguments given after `NUM_KEYS`. The return value from the function will
be returned to the user as a result.

* `NAME` - Name of the function to run.
* The rest is as today with EVALSHA command.

The command will return an error in the following cases:
* `NAME` does not exist
* The function itself returned an error.

The `FCALL_RO` is equivalent to `EVAL_RO` and allows only read-only commands to
be invoked from the script.

### FUNCTION DELETE

Usage: FUNCTION DELETE `NAME`

Delete a function identified by `NAME`. Return `OK` on success or error on one
of the following:
* The given function does not exist

### FUNCTION INFO

Usage: FUNCTION INFO `NAME` [WITHCODE]

Return information about a function by function name:
* Function name
* Engine name
* Description
* Raw code (only if WITHCODE argument is given)

### FUNCTION LIST

Usage: FUNCTION LIST

Return general information about all the functions:
* Function name
* Engine name
* Description

### FUNCTION STATS

Usage: FUNCTION STATS

Return information about the current running function:
* Function name
* Command that was used to invoke the function
* Duration in MS that the function is already running

If no function is currently running, this section is just a RESP nil.

Additionally, return a list of all the available engines.

### FUNCTION KILL

Usage: `FUNCTION KILL`

Kill the currently executing function. The command will fail if the function
already initiated a write command.

## Notes
Note: Function creation/deletion is replicated to AOF but AOFRW is not
implemented sense its going to be removed: #9794
parents e57a4db5 cbd46317
/*
* Copyright (c) 2009-2021, Redis Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SCRIPT_H_
#define __SCRIPT_H_
/*
* Script.c unit provides an API for functions and eval
* to interact with Redis. Interaction includes mostly
* executing commands, but also functionalities like calling
* Redis back on long scripts or check if the script was killed.
*
* The interaction is done using a scriptRunCtx object that
* need to be created by the user and initialized using scriptPrepareForRun.
*
* Detailed list of functionalities expose by the unit:
* 1. Calling commands (including all the validation checks such as
* acl, cluster, read only run, ...)
* 2. Set Resp
* 3. Set Replication method (AOF/REPLICATION/NONE)
* 4. Call Redis back to on long running scripts to allow Redis reply
* to clients and perform script kill
*/
/*
* scriptInterrupt function will return one of those value,
*
* - SCRIPT_KILL - kill the current running script.
* - SCRIPT_CONTINUE - keep running the current script.
*/
#define SCRIPT_KILL 1
#define SCRIPT_CONTINUE 2
/* runCtx flags */
#define SCRIPT_WRITE_DIRTY (1ULL<<0) /* indicate that the current script already performed a write command */
#define SCRIPT_RANDOM_DIRTY (1ULL<<1) /* indicate that the current script already performed a random reply command.
Thanks to this flag we'll raise an error every time a write command
is called after a random command and prevent none deterministic
replication or AOF. */
#define SCRIPT_MULTI_EMMITED (1ULL<<2) /* indicate that we already wrote a multi command to replication/aof */
#define SCRIPT_TIMEDOUT (1ULL<<3) /* indicate that the current script timedout */
#define SCRIPT_KILLED (1ULL<<4) /* indicate that the current script was marked to be killed */
#define SCRIPT_READ_ONLY (1ULL<<5) /* indicate that the current script should only perform read commands */
#define SCRIPT_EVAL_REPLICATION (1ULL<<6) /* mode for eval, indicate that we replicate the
script invocation and not the effects */
#define SCRIPT_EVAL_MODE (1ULL<<7) /* Indicate that the current script called from legacy Lua */
typedef struct scriptRunCtx scriptRunCtx;
struct scriptRunCtx {
const char *funcname;
client *c;
client *original_client;
int flags;
int repl_flags;
monotime start_time;
mstime_t snapshot_time;
};
void scriptPrepareForRun(scriptRunCtx *r_ctx, client *engine_client, client *caller, const char *funcname);
void scriptResetRun(scriptRunCtx *r_ctx);
int scriptSetResp(scriptRunCtx *r_ctx, int resp);
int scriptSetRepl(scriptRunCtx *r_ctx, int repl);
void scriptCall(scriptRunCtx *r_ctx, robj **argv, int argc, sds *err);
int scriptInterrupt(scriptRunCtx *r_ctx);
void scriptKill(client *c, int is_eval);
int scriptIsRunning();
const char* scriptCurrFunction();
int scriptIsEval();
int scriptIsTimedout();
client* scriptGetClient();
client* scriptGetCaller();
mstime_t scriptTimeSnapshot();
long long scriptRunDuration();
#endif /* __SCRIPT_H_ */
This diff is collapsed.
/*
* Copyright (c) 2009-2021, Redis Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SCRIPT_LUA_H_
#define __SCRIPT_LUA_H_
/*
* script_lua.c unit provides shared functionality between
* eval.c and function_lua.c. Functionality provided:
*
* * Execute Lua code, assuming that the code is located on
* the top of the Lua stack. In addition, parsing the execution
* result and convert it to the resp and reply ot the client.
*
* * Run Redis commands from within the Lua code (Including
* parsing the reply and create a Lua object out of it).
*
* * Register Redis API to the Lua interpreter. Only shared
* API are registered (API that is only relevant on eval.c
* (like debugging) are registered on eval.c).
*
* Uses script.c for interaction back with Redis.
*/
#include "server.h"
#include "script.h"
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#define REGISTRY_RUN_CTX_NAME "__RUN_CTX__"
void luaRegisterRedisAPI(lua_State* lua);
void luaEnableGlobalsProtection(lua_State *lua, int is_eval);
void luaSaveOnRegistry(lua_State* lua, const char* name, void* ptr);
void* luaGetFromRegistry(lua_State* lua, const char* name);
void luaCallFunction(scriptRunCtx* r_ctx, lua_State *lua, robj** keys, size_t nkeys, robj** args, size_t nargs, int debug_enabled);
unsigned long luaMemory(lua_State *lua);
#endif /* __SCRIPT_LUA_H_ */
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
#include "latency.h" #include "latency.h"
#include "atomicvar.h" #include "atomicvar.h"
#include "mt19937-64.h" #include "mt19937-64.h"
#include "functions.h"
#include <time.h> #include <time.h>
#include <signal.h> #include <signal.h>
...@@ -471,6 +472,31 @@ struct redisCommand scriptSubcommands[] = { ...@@ -471,6 +472,31 @@ struct redisCommand scriptSubcommands[] = {
{NULL}, {NULL},
}; };
struct redisCommand functionSubcommands[] = {
{"create",functionsCreateCommand,-5,
"may-replicate no-script @scripting"},
{"delete",functionsDeleteCommand,3,
"may-replicate no-script @scripting"},
{"kill",functionsKillCommand,2,
"no-script @scripting"},
{"info",functionsInfoCommand,-3,
"no-script @scripting"},
{"list",functionsListCommand,2,
"no-script @scripting"},
{"stats",functionsStatsCommand,2,
"no-script @scripting"},
{"help",functionsHelpCommand,2,
"ok-loading ok-stale @scripting"},
{NULL},
};
struct redisCommand clientSubcommands[] = { struct redisCommand clientSubcommands[] = {
{"caching",clientCommand,3, {"caching",clientCommand,3,
"no-script ok-loading ok-stale @connection"}, "no-script ok-loading ok-stale @connection"},
...@@ -2032,7 +2058,25 @@ struct redisCommand redisCommandTable[] = { ...@@ -2032,7 +2058,25 @@ struct redisCommand redisCommandTable[] = {
"no-auth no-script ok-stale ok-loading fast @connection"}, "no-auth no-script ok-stale ok-loading fast @connection"},
{"failover",failoverCommand,-1, {"failover",failoverCommand,-1,
"admin no-script ok-stale"} "admin no-script ok-stale"},
{"function",NULL,-2,
"",
.subcommands=functionSubcommands},
{"fcall",fcallCommand,-3,
"no-script no-monitor may-replicate no-mandatory-keys @scripting",
{{"read write", /* We pass both read and write because these flag are worst-case-scenario */
KSPEC_BS_INDEX,.bs.index={2},
KSPEC_FK_KEYNUM,.fk.keynum={0,1,1}}},
functionGetKeys},
{"fcall_ro",fcallCommandReadOnly,-3,
"no-script no-monitor no-mandatory-keys @scripting",
{{"read",
KSPEC_BS_INDEX,.bs.index={2},
KSPEC_FK_KEYNUM,.fk.keynum={0,1,1}}},
functionGetKeys},
}; };
/*============================ Utility functions ============================ */ /*============================ Utility functions ============================ */
...@@ -2208,6 +2252,11 @@ void dictSdsDestructor(dict *d, void *val) ...@@ -2208,6 +2252,11 @@ void dictSdsDestructor(dict *d, void *val)
sdsfree(val); sdsfree(val);
} }
void *dictSdsDup(dict *d, const void *key) {
UNUSED(d);
return sdsdup((const sds) key);
}
int dictObjKeyCompare(dict *d, const void *key1, int dictObjKeyCompare(dict *d, const void *key1,
const void *key2) const void *key2)
{ {
...@@ -2994,7 +3043,7 @@ void cronUpdateMemoryStats() { ...@@ -2994,7 +3043,7 @@ void cronUpdateMemoryStats() {
/* LUA memory isn't part of zmalloc_used, but it is part of the process RSS, /* LUA memory isn't part of zmalloc_used, but it is part of the process RSS,
* so we must deduct it in order to be able to calculate correct * so we must deduct it in order to be able to calculate correct
* "allocator fragmentation" ratio */ * "allocator fragmentation" ratio */
size_t lua_memory = lua_gc(server.lua,LUA_GCCOUNT,0)*1024LL; size_t lua_memory = evalMemory();
server.cron_malloc_stats.allocator_resident = server.cron_malloc_stats.process_rss - lua_memory; server.cron_malloc_stats.allocator_resident = server.cron_malloc_stats.process_rss - lua_memory;
} }
if (!server.cron_malloc_stats.allocator_active) if (!server.cron_malloc_stats.allocator_active)
...@@ -3516,8 +3565,10 @@ void createSharedObjects(void) { ...@@ -3516,8 +3565,10 @@ void createSharedObjects(void) {
"-NOSCRIPT No matching script. Please use EVAL.\r\n")); "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
shared.loadingerr = createObject(OBJ_STRING,sdsnew( shared.loadingerr = createObject(OBJ_STRING,sdsnew(
"-LOADING Redis is loading the dataset in memory\r\n")); "-LOADING Redis is loading the dataset in memory\r\n"));
shared.slowscripterr = createObject(OBJ_STRING,sdsnew( shared.slowevalerr = createObject(OBJ_STRING,sdsnew(
"-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
shared.slowscripterr = createObject(OBJ_STRING,sdsnew(
"-BUSY Redis is busy running a script. You can only call FUNCTION KILL or SHUTDOWN NOSAVE.\r\n"));
shared.masterdownerr = createObject(OBJ_STRING,sdsnew( shared.masterdownerr = createObject(OBJ_STRING,sdsnew(
"-MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no'.\r\n")); "-MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no'.\r\n"));
shared.bgsaveerr = createObject(OBJ_STRING,sdsnew( shared.bgsaveerr = createObject(OBJ_STRING,sdsnew(
...@@ -4247,7 +4298,7 @@ void initServer(void) { ...@@ -4247,7 +4298,7 @@ void initServer(void) {
server.pubsub_channels = dictCreate(&keylistDictType); server.pubsub_channels = dictCreate(&keylistDictType);
server.pubsub_patterns = dictCreate(&keylistDictType); server.pubsub_patterns = dictCreate(&keylistDictType);
server.cronloops = 0; server.cronloops = 0;
server.in_eval = 0; server.in_script = 0;
server.in_exec = 0; server.in_exec = 0;
server.propagate_in_transaction = 0; server.propagate_in_transaction = 0;
server.client_pause_in_transaction = 0; server.client_pause_in_transaction = 0;
...@@ -4344,6 +4395,7 @@ void initServer(void) { ...@@ -4344,6 +4395,7 @@ void initServer(void) {
if (server.cluster_enabled) clusterInit(); if (server.cluster_enabled) clusterInit();
replicationScriptCacheInit(); replicationScriptCacheInit();
scriptingInit(1); scriptingInit(1);
functionsInit();
slowlogInit(); slowlogInit();
latencyMonitorInit(); latencyMonitorInit();
...@@ -4931,17 +4983,17 @@ void call(client *c, int flags) { ...@@ -4931,17 +4983,17 @@ void call(client *c, int flags) {
/* When EVAL is called loading the AOF we don't want commands called /* When EVAL is called loading the AOF we don't want commands called
* from Lua to go into the slowlog or to populate statistics. */ * from Lua to go into the slowlog or to populate statistics. */
if (server.loading && c->flags & CLIENT_LUA) if (server.loading && c->flags & CLIENT_SCRIPT)
flags &= ~(CMD_CALL_SLOWLOG | CMD_CALL_STATS); flags &= ~(CMD_CALL_SLOWLOG | CMD_CALL_STATS);
/* If the caller is Lua, we want to force the EVAL caller to propagate /* 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 * the script if the command flag or client flag are forcing the
* propagation. */ * propagation. */
if (c->flags & CLIENT_LUA && server.lua_caller) { if (c->flags & CLIENT_SCRIPT && server.script_caller) {
if (c->flags & CLIENT_FORCE_REPL) if (c->flags & CLIENT_FORCE_REPL)
server.lua_caller->flags |= CLIENT_FORCE_REPL; server.script_caller->flags |= CLIENT_FORCE_REPL;
if (c->flags & CLIENT_FORCE_AOF) if (c->flags & CLIENT_FORCE_AOF)
server.lua_caller->flags |= CLIENT_FORCE_AOF; server.script_caller->flags |= CLIENT_FORCE_AOF;
} }
/* Note: the code below uses the real command that was executed /* Note: the code below uses the real command that was executed
...@@ -5070,8 +5122,8 @@ void call(client *c, int flags) { ...@@ -5070,8 +5122,8 @@ void call(client *c, int flags) {
/* If the client has keys tracking enabled for client side caching, /* If the client has keys tracking enabled for client side caching,
* make sure to remember the keys it fetched via this command. */ * make sure to remember the keys it fetched via this command. */
if (c->cmd->flags & CMD_READONLY) { if (c->cmd->flags & CMD_READONLY) {
client *caller = (c->flags & CLIENT_LUA && server.lua_caller) ? client *caller = (c->flags & CLIENT_SCRIPT && server.script_caller) ?
server.lua_caller : c; server.script_caller : c;
if (caller->flags & CLIENT_TRACKING && if (caller->flags & CLIENT_TRACKING &&
!(caller->flags & CLIENT_TRACKING_BCAST)) !(caller->flags & CLIENT_TRACKING_BCAST))
{ {
...@@ -5172,14 +5224,14 @@ void populateCommandMovableKeys(struct redisCommand *cmd) { ...@@ -5172,14 +5224,14 @@ void populateCommandMovableKeys(struct redisCommand *cmd) {
* other operations can be performed by the caller. Otherwise * other operations can be performed by the caller. Otherwise
* if C_ERR is returned the client was destroyed (i.e. after QUIT). */ * if C_ERR is returned the client was destroyed (i.e. after QUIT). */
int processCommand(client *c) { int processCommand(client *c) {
if (!server.lua_timedout) { if (!scriptIsTimedout()) {
/* Both EXEC and EVAL call call() directly so there should be /* Both EXEC and EVAL call call() directly so there should be
* no way in_exec or in_eval or propagate_in_transaction is 1. * no way in_exec or in_eval or propagate_in_transaction is 1.
* That is unless lua_timedout, in which case client may run * That is unless lua_timedout, in which case client may run
* some commands. */ * some commands. */
serverAssert(!server.propagate_in_transaction); serverAssert(!server.propagate_in_transaction);
serverAssert(!server.in_exec); serverAssert(!server.in_exec);
serverAssert(!server.in_eval); serverAssert(!server.in_script);
} }
moduleCallCommandFilters(c); moduleCallCommandFilters(c);
...@@ -5273,8 +5325,8 @@ int processCommand(client *c) { ...@@ -5273,8 +5325,8 @@ int processCommand(client *c) {
* 2) The command has no key arguments. */ * 2) The command has no key arguments. */
if (server.cluster_enabled && if (server.cluster_enabled &&
!(c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_MASTER) &&
!(c->flags & CLIENT_LUA && !(c->flags & CLIENT_SCRIPT &&
server.lua_caller->flags & CLIENT_MASTER) && server.script_caller->flags & CLIENT_MASTER) &&
!(!c->cmd->movablekeys && c->cmd->key_specs_num == 0 && !(!c->cmd->movablekeys && c->cmd->key_specs_num == 0 &&
c->cmd->proc != execCommand)) c->cmd->proc != execCommand))
{ {
...@@ -5309,7 +5361,7 @@ int processCommand(client *c) { ...@@ -5309,7 +5361,7 @@ int processCommand(client *c) {
* the event loop since there is a busy Lua script running in timeout * the event loop since there is a busy Lua script running in timeout
* condition, to avoid mixing the propagation of scripts with the * condition, to avoid mixing the propagation of scripts with the
* propagation of DELs due to eviction. */ * propagation of DELs due to eviction. */
if (server.maxmemory && !server.lua_timedout) { if (server.maxmemory && !scriptIsTimedout()) {
int out_of_memory = (performEvictions() == EVICT_FAIL); int out_of_memory = (performEvictions() == EVICT_FAIL);
/* performEvictions may evict keys, so we need flush pending tracking /* performEvictions may evict keys, so we need flush pending tracking
...@@ -5345,7 +5397,7 @@ int processCommand(client *c) { ...@@ -5345,7 +5397,7 @@ int processCommand(client *c) {
* until first write within script, memory used by lua stack and * until first write within script, memory used by lua stack and
* arguments might interfere. */ * arguments might interfere. */
if (c->cmd->proc == evalCommand || c->cmd->proc == evalShaCommand) { if (c->cmd->proc == evalCommand || c->cmd->proc == evalShaCommand) {
server.lua_oom = out_of_memory; server.script_oom = out_of_memory;
} }
} }
...@@ -5432,7 +5484,7 @@ int processCommand(client *c) { ...@@ -5432,7 +5484,7 @@ int processCommand(client *c) {
* the MULTI plus a few initial commands refused, then the timeout * the MULTI plus a few initial commands refused, then the timeout
* condition resolves, and the bottom-half of the transaction gets * condition resolves, and the bottom-half of the transaction gets
* executed, see Github PR #7022. */ * executed, see Github PR #7022. */
if (server.lua_timedout && if (scriptIsTimedout() &&
c->cmd->proc != authCommand && c->cmd->proc != authCommand &&
c->cmd->proc != helloCommand && c->cmd->proc != helloCommand &&
c->cmd->proc != replconfCommand && c->cmd->proc != replconfCommand &&
...@@ -5447,9 +5499,15 @@ int processCommand(client *c) { ...@@ -5447,9 +5499,15 @@ int processCommand(client *c) {
tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&
!(c->cmd->proc == scriptCommand && !(c->cmd->proc == scriptCommand &&
c->argc == 2 && c->argc == 2 &&
tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) tolower(((char*)c->argv[1]->ptr)[0]) == 'k') &&
!(c->cmd->proc == functionsKillCommand) &&
!(c->cmd->proc == functionsStatsCommand))
{ {
rejectCommand(c, shared.slowscripterr); if (scriptIsEval()) {
rejectCommand(c, shared.slowevalerr);
} else {
rejectCommand(c, shared.slowscripterr);
}
return C_OK; return C_OK;
} }
...@@ -6280,13 +6338,15 @@ sds genRedisInfoString(const char *section) { ...@@ -6280,13 +6338,15 @@ sds genRedisInfoString(const char *section) {
char peak_hmem[64]; char peak_hmem[64];
char total_system_hmem[64]; char total_system_hmem[64];
char used_memory_lua_hmem[64]; char used_memory_lua_hmem[64];
char used_memory_vm_total_hmem[64];
char used_memory_scripts_hmem[64]; char used_memory_scripts_hmem[64];
char used_memory_rss_hmem[64]; char used_memory_rss_hmem[64];
char maxmemory_hmem[64]; char maxmemory_hmem[64];
size_t zmalloc_used = zmalloc_used_memory(); size_t zmalloc_used = zmalloc_used_memory();
size_t total_system_mem = server.system_memory_size; size_t total_system_mem = server.system_memory_size;
const char *evict_policy = evictPolicyToString(); const char *evict_policy = evictPolicyToString();
long long memory_lua = server.lua ? (long long)lua_gc(server.lua,LUA_GCCOUNT,0)*1024 : 0; long long memory_lua = evalMemory();
long long memory_functions = functionsMemory();
struct redisMemOverhead *mh = getMemoryOverheadData(); struct redisMemOverhead *mh = getMemoryOverheadData();
/* Peak memory is updated from time to time by serverCron() so it /* Peak memory is updated from time to time by serverCron() so it
...@@ -6300,7 +6360,8 @@ sds genRedisInfoString(const char *section) { ...@@ -6300,7 +6360,8 @@ sds genRedisInfoString(const char *section) {
bytesToHuman(peak_hmem,server.stat_peak_memory); bytesToHuman(peak_hmem,server.stat_peak_memory);
bytesToHuman(total_system_hmem,total_system_mem); bytesToHuman(total_system_hmem,total_system_mem);
bytesToHuman(used_memory_lua_hmem,memory_lua); bytesToHuman(used_memory_lua_hmem,memory_lua);
bytesToHuman(used_memory_scripts_hmem,mh->lua_caches); bytesToHuman(used_memory_vm_total_hmem,memory_functions + memory_lua);
bytesToHuman(used_memory_scripts_hmem,mh->lua_caches + mh->functions_caches);
bytesToHuman(used_memory_rss_hmem,server.cron_malloc_stats.process_rss); bytesToHuman(used_memory_rss_hmem,server.cron_malloc_stats.process_rss);
bytesToHuman(maxmemory_hmem,server.maxmemory); bytesToHuman(maxmemory_hmem,server.maxmemory);
...@@ -6323,11 +6384,18 @@ sds genRedisInfoString(const char *section) { ...@@ -6323,11 +6384,18 @@ sds genRedisInfoString(const char *section) {
"allocator_resident:%zu\r\n" "allocator_resident:%zu\r\n"
"total_system_memory:%lu\r\n" "total_system_memory:%lu\r\n"
"total_system_memory_human:%s\r\n" "total_system_memory_human:%s\r\n"
"used_memory_lua:%lld\r\n" "used_memory_lua:%lld\r\n" /* deprecated, renamed to used_memory_vm_eval */
"used_memory_lua_human:%s\r\n" "used_memory_vm_eval:%lld\r\n"
"used_memory_lua_human:%s\r\n" /* deprecated */
"used_memory_scripts_eval:%lld\r\n"
"number_of_cached_scripts:%lu\r\n"
"number_of_functions:%lu\r\n"
"used_memory_vm_functions:%lld\r\n"
"used_memory_vm_total:%lld\r\n"
"used_memory_vm_total_human:%s\r\n"
"used_memory_functions:%lld\r\n"
"used_memory_scripts:%lld\r\n" "used_memory_scripts:%lld\r\n"
"used_memory_scripts_human:%s\r\n" "used_memory_scripts_human:%s\r\n"
"number_of_cached_scripts:%lu\r\n"
"maxmemory:%lld\r\n" "maxmemory:%lld\r\n"
"maxmemory_human:%s\r\n" "maxmemory_human:%s\r\n"
"maxmemory_policy:%s\r\n" "maxmemory_policy:%s\r\n"
...@@ -6366,10 +6434,17 @@ sds genRedisInfoString(const char *section) { ...@@ -6366,10 +6434,17 @@ sds genRedisInfoString(const char *section) {
(unsigned long)total_system_mem, (unsigned long)total_system_mem,
total_system_hmem, total_system_hmem,
memory_lua, memory_lua,
memory_lua,
used_memory_lua_hmem, used_memory_lua_hmem,
(long long) mh->lua_caches, (long long) mh->lua_caches,
dictSize(evalScriptsDict()),
functionsNum(),
memory_functions,
memory_functions + memory_lua,
used_memory_vm_total_hmem,
(long long) mh->functions_caches,
(long long) mh->lua_caches + (long long) mh->functions_caches,
used_memory_scripts_hmem, used_memory_scripts_hmem,
dictSize(server.lua_scripts),
server.maxmemory, server.maxmemory,
maxmemory_hmem, maxmemory_hmem,
evict_policy, evict_policy,
......
...@@ -260,7 +260,7 @@ extern int configOOMScoreAdjValuesDefaults[CONFIG_OOM_COUNT]; ...@@ -260,7 +260,7 @@ extern int configOOMScoreAdjValuesDefaults[CONFIG_OOM_COUNT];
#define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */ #define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */
#define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in #define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in
server.unblocked_clients */ server.unblocked_clients */
#define CLIENT_LUA (1<<8) /* This is a non connected client used by Lua */ #define CLIENT_SCRIPT (1<<8) /* This is a non connected client used by Lua */
#define CLIENT_ASKING (1<<9) /* Client issued the ASKING command */ #define CLIENT_ASKING (1<<9) /* Client issued the ASKING command */
#define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */ #define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */
#define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */ #define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */
...@@ -822,6 +822,19 @@ typedef struct redisDb { ...@@ -822,6 +822,19 @@ typedef struct redisDb {
clusterSlotToKeyMapping *slots_to_keys; /* Array of slots to keys. Only used in cluster mode (db 0). */ clusterSlotToKeyMapping *slots_to_keys; /* Array of slots to keys. Only used in cluster mode (db 0). */
} redisDb; } redisDb;
/* forward declaration for functions ctx */
typedef struct functionsCtx functionsCtx;
/* Holding object that need to be populated during
* rdb loading. On loading end it is possible to decide
* whether not to set those objects on their rightful place.
* For example: dbarray need to be set as main database on
* successful loading and dropped on failure. */
typedef struct rdbLoadingCtx {
redisDb* dbarray;
functionsCtx* functions_ctx;
}rdbLoadingCtx;
/* Client MULTI/EXEC state */ /* Client MULTI/EXEC state */
typedef struct multiCmd { typedef struct multiCmd {
robj **argv; robj **argv;
...@@ -1122,7 +1135,7 @@ struct sharedObjectsStruct { ...@@ -1122,7 +1135,7 @@ struct sharedObjectsStruct {
robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space, robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
*queued, *null[4], *nullarray[4], *emptymap[4], *emptyset[4], *queued, *null[4], *nullarray[4], *emptymap[4], *emptyset[4],
*emptyarray, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr, *emptyarray, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
*outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *bgsaveerr, *outofrangeerr, *noscripterr, *loadingerr, *slowevalerr, *slowscripterr, *bgsaveerr,
*masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr, *masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr,
*busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk, *busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk,
*unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *unlink, *unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *unlink,
...@@ -1203,6 +1216,7 @@ struct redisMemOverhead { ...@@ -1203,6 +1216,7 @@ struct redisMemOverhead {
size_t clients_normal; size_t clients_normal;
size_t aof_buffer; size_t aof_buffer;
size_t lua_caches; size_t lua_caches;
size_t functions_caches;
size_t overhead_total; size_t overhead_total;
size_t dataset; size_t dataset;
size_t total_keys; size_t total_keys;
...@@ -1334,7 +1348,7 @@ struct redisServer { ...@@ -1334,7 +1348,7 @@ struct redisServer {
int sentinel_mode; /* True if this instance is a Sentinel. */ int sentinel_mode; /* True if this instance is a Sentinel. */
size_t initial_memory_usage; /* Bytes used after initialization. */ size_t initial_memory_usage; /* Bytes used after initialization. */
int always_show_logo; /* Show logo even for non-stdout logging. */ int always_show_logo; /* Show logo even for non-stdout logging. */
int in_eval; /* Are we inside EVAL? */ int in_script; /* Are we inside EVAL? */
int in_exec; /* Are we inside EXEC? */ int in_exec; /* Are we inside EXEC? */
int propagate_in_transaction; /* Make sure we don't propagate nested MULTI/EXEC */ int propagate_in_transaction; /* Make sure we don't propagate nested MULTI/EXEC */
char *ignore_warnings; /* Config: warnings that should be ignored. */ char *ignore_warnings; /* Config: warnings that should be ignored. */
...@@ -1719,28 +1733,11 @@ struct redisServer { ...@@ -1719,28 +1733,11 @@ struct redisServer {
is down? */ is down? */
int cluster_config_file_lock_fd; /* cluster config fd, will be flock */ int cluster_config_file_lock_fd; /* cluster config fd, will be flock */
/* Scripting */ /* Scripting */
lua_State *lua; /* The Lua interpreter. We use just one for all clients */ client *script_caller; /* The client running script right now, or NULL */
client *lua_client; /* The "fake client" to query Redis from Lua */ mstime_t script_time_limit; /* Script timeout in milliseconds */
client *lua_caller; /* The client running EVAL right now, or NULL */
char* lua_cur_script; /* SHA1 of the script currently running, or NULL */
dict *lua_scripts; /* A dictionary of SHA1 -> Lua scripts */
unsigned long long lua_scripts_mem; /* Cached scripts' memory + oh */
mstime_t lua_time_limit; /* Script timeout in milliseconds */
monotime lua_time_start; /* monotonic timer to detect timed-out script */
mstime_t lua_time_snapshot; /* Snapshot of mstime when script is started */
int lua_write_dirty; /* True if a write command was called during the
execution of the current script. */
int lua_random_dirty; /* True if a random command was called during the
execution of the current script. */
int lua_replicate_commands; /* True if we are doing single commands repl. */
int lua_multi_emitted;/* True if we already propagated MULTI. */
int lua_repl; /* Script replication flags for redis.set_repl(). */
int lua_timedout; /* True if we reached the time limit for script
execution. */
int lua_kill; /* Kill the script if true. */
int lua_always_replicate_commands; /* Default replication type. */ int lua_always_replicate_commands; /* Default replication type. */
int lua_oom; /* OOM detected when script start? */ int script_oom; /* OOM detected when script start */
int lua_disable_deny_script; /* Allow running commands marked "no-script" inside a script. */ int script_disable_deny_script; /* Allow running commands marked "no-script" inside a script. */
/* Lazy free */ /* Lazy free */
int lazyfree_lazy_eviction; int lazyfree_lazy_eviction;
int lazyfree_lazy_expire; int lazyfree_lazy_expire;
...@@ -2687,6 +2684,7 @@ int sintercardGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysRes ...@@ -2687,6 +2684,7 @@ int sintercardGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysRes
int zunionInterDiffGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result); int zunionInterDiffGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result);
int zunionInterDiffStoreGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result); int zunionInterDiffStoreGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result);
int evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result); int evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
int functionGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
int sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result); int sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
int migrateGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result); int migrateGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
int georadiusGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result); int georadiusGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
...@@ -2722,8 +2720,17 @@ void scriptingInit(int setup); ...@@ -2722,8 +2720,17 @@ void scriptingInit(int setup);
int ldbRemoveChild(pid_t pid); int ldbRemoveChild(pid_t pid);
void ldbKillForkedSessions(void); void ldbKillForkedSessions(void);
int ldbPendingChildren(void); int ldbPendingChildren(void);
sds luaCreateFunction(client *c, lua_State *lua, robj *body); sds luaCreateFunction(client *c, robj *body);
void luaLdbLineHook(lua_State *lua, lua_Debug *ar);
void freeLuaScriptsAsync(dict *lua_scripts); void freeLuaScriptsAsync(dict *lua_scripts);
int ldbIsEnabled();
void ldbLog(sds entry);
void ldbLogRedisReply(char *reply);
void sha1hex(char *digest, char *script, size_t len);
unsigned long evalMemory();
dict* evalScriptsDict();
unsigned long evalScriptsMemory();
mstime_t evalTimeSnapshot();
/* Blocked clients */ /* Blocked clients */
void processUnblockedClients(void); void processUnblockedClients(void);
...@@ -2769,6 +2776,7 @@ uint64_t dictSdsCaseHash(const void *key); ...@@ -2769,6 +2776,7 @@ uint64_t dictSdsCaseHash(const void *key);
int dictSdsKeyCompare(dict *d, const void *key1, const void *key2); int dictSdsKeyCompare(dict *d, const void *key1, const void *key2);
int dictSdsKeyCaseCompare(dict *d, const void *key1, const void *key2); int dictSdsKeyCaseCompare(dict *d, const void *key1, const void *key2);
void dictSdsDestructor(dict *d, void *val); void dictSdsDestructor(dict *d, void *val);
void *dictSdsDup(dict *d, const void *key);
/* Git SHA1 */ /* Git SHA1 */
char *redisGitSHA1(void); char *redisGitSHA1(void);
......
...@@ -294,7 +294,7 @@ void sortCommandGeneric(client *c, int readonly) { ...@@ -294,7 +294,7 @@ void sortCommandGeneric(client *c, int readonly) {
* scripting and replication. */ * scripting and replication. */
if (dontsort && if (dontsort &&
sortval->type == OBJ_SET && sortval->type == OBJ_SET &&
(storekey || c->flags & CLIENT_LUA)) (storekey || c->flags & CLIENT_SCRIPT))
{ {
/* Force ALPHA sorting */ /* Force ALPHA sorting */
dontsort = 0; dontsort = 0;
......
...@@ -1998,7 +1998,7 @@ void xreadCommand(client *c) { ...@@ -1998,7 +1998,7 @@ void xreadCommand(client *c) {
int moreargs = c->argc-i-1; int moreargs = c->argc-i-1;
char *o = c->argv[i]->ptr; char *o = c->argv[i]->ptr;
if (!strcasecmp(o,"BLOCK") && moreargs) { if (!strcasecmp(o,"BLOCK") && moreargs) {
if (c->flags & CLIENT_LUA) { if (c->flags & CLIENT_SCRIPT) {
/* /*
* Although the CLIENT_DENY_BLOCKING flag should protect from blocking the client * Although the CLIENT_DENY_BLOCKING flag should protect from blocking the client
* on Lua/MULTI/RM_Call we want special treatment for Lua to keep backward compatibility. * on Lua/MULTI/RM_Call we want special treatment for Lua to keep backward compatibility.
......
...@@ -521,6 +521,12 @@ foreach testType {Successful Aborted} { ...@@ -521,6 +521,12 @@ foreach testType {Successful Aborted} {
# Set a key value on replica to check status during loading, on failure and after swapping db # Set a key value on replica to check status during loading, on failure and after swapping db
$replica set mykey myvalue $replica set mykey myvalue
# Set a function value on replica to check status during loading, on failure and after swapping db
$replica function create LUA test {return 'hello1'}
# Set a function value on master to check it reaches the replica when replication ends
$master function create LUA test {return 'hello2'}
# Force the replica to try another full sync (this time it will have matching master replid) # Force the replica to try another full sync (this time it will have matching master replid)
$master multi $master multi
$master client kill type replica $master client kill type replica
...@@ -552,6 +558,9 @@ foreach testType {Successful Aborted} { ...@@ -552,6 +558,9 @@ foreach testType {Successful Aborted} {
# Ensure we still see old values while async_loading is in progress and also not LOADING status # Ensure we still see old values while async_loading is in progress and also not LOADING status
assert_equal [$replica get mykey] "myvalue" assert_equal [$replica get mykey] "myvalue"
# Ensure we still can call old function while async_loading is in progress
assert_equal [$replica fcall test 0] "hello1"
# Make sure we're still async_loading to validate previous assertion # Make sure we're still async_loading to validate previous assertion
assert_equal [s -1 async_loading] 1 assert_equal [s -1 async_loading] 1
...@@ -576,6 +585,9 @@ foreach testType {Successful Aborted} { ...@@ -576,6 +585,9 @@ foreach testType {Successful Aborted} {
# Ensure we see old values from replica # Ensure we see old values from replica
assert_equal [$replica get mykey] "myvalue" assert_equal [$replica get mykey] "myvalue"
# Ensure we still can call old function
assert_equal [$replica fcall test 0] "hello1"
# Make sure amount of replica keys didn't change # Make sure amount of replica keys didn't change
assert_equal [$replica dbsize] 2001 assert_equal [$replica dbsize] 2001
} }
...@@ -595,6 +607,9 @@ foreach testType {Successful Aborted} { ...@@ -595,6 +607,9 @@ foreach testType {Successful Aborted} {
# Ensure we don't see anymore the key that was stored only to replica and also that we don't get LOADING status # Ensure we don't see anymore the key that was stored only to replica and also that we don't get LOADING status
assert_equal [$replica GET mykey] "" assert_equal [$replica GET mykey] ""
# Ensure we got the new function
assert_equal [$replica fcall test 0] "hello2"
# Make sure amount of keys matches master # Make sure amount of keys matches master
assert_equal [$replica dbsize] 1010 assert_equal [$replica dbsize] 1010
} }
...@@ -624,6 +639,10 @@ test {diskless loading short read} { ...@@ -624,6 +639,10 @@ test {diskless loading short read} {
$replica config set dynamic-hz no $replica config set dynamic-hz no
# Try to fill the master with all types of data types / encodings # Try to fill the master with all types of data types / encodings
set start [clock clicks -milliseconds] set start [clock clicks -milliseconds]
# Set a function value to check short read handling on functions
r function create LUA test {return 'hello1'}
for {set k 0} {$k < 3} {incr k} { for {set k 0} {$k < 3} {incr k} {
for {set i 0} {$i < 10} {incr i} { for {set i 0} {$i < 10} {incr i} {
r set "$k int_$i" [expr {int(rand()*10000)}] r set "$k int_$i" [expr {int(rand()*10000)}]
......
start_server {tags {"scripting"}} {
test {FUNCTION - Basic usage} {
r function create LUA test {return 'hello'}
r fcall test 0
} {hello}
test {FUNCTION - Create an already exiting function raise error} {
catch {
r function create LUA test {return 'hello1'}
} e
set _ $e
} {*Function already exists*}
test {FUNCTION - Create function with unexisting engine} {
catch {
r function create bad_engine test {return 'hello1'}
} e
set _ $e
} {*Engine not found*}
test {FUNCTION - Test uncompiled script} {
catch {
r function create LUA test1 {bad script}
} e
set _ $e
} {*Error compiling function*}
test {FUNCTION - test replace argument} {
r function create LUA test REPLACE {return 'hello1'}
r fcall test 0
} {hello1}
test {FUNCTION - test replace argument with function creation failure keeps old function} {
catch {r function create LUA test REPLACE {error}}
r fcall test 0
} {hello1}
test {FUNCTION - test function delete} {
r function delete test
catch {
r fcall test 0
} e
set _ $e
} {*Function not found*}
test {FUNCTION - test description argument} {
r function create LUA test DESCRIPTION {some description} {return 'hello'}
r function list
} {{name test engine LUA description {some description}}}
test {FUNCTION - test info specific function} {
r function info test WITHCODE
} {name test engine LUA description {some description} code {return 'hello'}}
test {FUNCTION - test info without code} {
r function info test
} {name test engine LUA description {some description}}
test {FUNCTION - test info on function that does not exists} {
catch {
r function info bad_function_name
} e
set _ $e
} {*Function does not exists*}
test {FUNCTION - test info with bad number of arguments} {
catch {
r function info test WITHCODE bad_arg
} e
set _ $e
} {*wrong number of arguments*}
test {FUNCTION - test fcall bad arguments} {
catch {
r fcall test bad_arg
} e
set _ $e
} {*Bad number of keys provided*}
test {FUNCTION - test fcall bad number of keys arguments} {
catch {
r fcall test 10 key1
} e
set _ $e
} {*Number of keys can't be greater than number of args*}
test {FUNCTION - test fcall negative number of keys} {
catch {
r fcall test -1 key1
} e
set _ $e
} {*Number of keys can't be negative*}
test {FUNCTION - test function delete on not exiting function} {
catch {
r function delete test1
} e
set _ $e
} {*Function not found*}
test {FUNCTION - test function kill when function is not running} {
catch {
r function kill
} e
set _ $e
} {*No scripts in execution*}
test {FUNCTION - test wrong subcommand} {
catch {
r function bad_subcommand
} e
set _ $e
} {*Unknown subcommand*}
test {FUNCTION - test loading from rdb} {
r debug reload
r fcall test 0
} {hello}
test {FUNCTION - test fcall_ro with write command} {
r function create lua test REPLACE {return redis.call('set', 'x', '1')}
catch { r fcall_ro test 0 } e
set _ $e
} {*Write commands are not allowed from read-only scripts*}
test {FUNCTION - test fcall_ro with read only commands} {
r function create lua test REPLACE {return redis.call('get', 'x')}
r set x 1
r fcall_ro test 0
} {1}
test {FUNCTION - test keys and argv} {
r function create lua test REPLACE {return redis.call('set', KEYS[1], ARGV[1])}
r fcall test 1 x foo
r get x
} {foo}
test {FUNCTION - test command get keys on fcall} {
r COMMAND GETKEYS fcall test 1 x foo
} {x}
test {FUNCTION - test command get keys on fcall_ro} {
r COMMAND GETKEYS fcall_ro test 1 x foo
} {x}
test {FUNCTION - test function kill} {
set rd [redis_deferring_client]
r config set script-time-limit 10
r function create lua test REPLACE {local a = 1 while true do a = a + 1 end}
$rd fcall test 0
after 200
catch {r ping} e
assert_match {BUSY*} $e
assert_match {running_script {name test command {fcall test 0} duration_ms *} engines LUA} [r FUNCTION STATS]
r function kill
after 200 ; # Give some time to Lua to call the hook again...
assert_equal [r ping] "PONG"
}
test {FUNCTION - test script kill not working on function} {
set rd [redis_deferring_client]
r config set script-time-limit 10
r function create lua test REPLACE {local a = 1 while true do a = a + 1 end}
$rd fcall test 0
after 200
catch {r ping} e
assert_match {BUSY*} $e
catch {r script kill} e
assert_match {BUSY*} $e
r function kill
after 200 ; # Give some time to Lua to call the hook again...
assert_equal [r ping] "PONG"
}
test {FUNCTION - test function kill not working on eval} {
set rd [redis_deferring_client]
r config set script-time-limit 10
$rd eval {local a = 1 while true do a = a + 1 end} 0
after 200
catch {r ping} e
assert_match {BUSY*} $e
catch {r function kill} e
assert_match {BUSY*} $e
r script kill
after 200 ; # Give some time to Lua to call the hook again...
assert_equal [r ping] "PONG"
}
}
start_server {tags {"scripting repl"}} {
start_server {} {
test "Connect a replica to the master instance" {
r -1 slaveof [srv 0 host] [srv 0 port]
wait_for_condition 50 100 {
[s -1 role] eq {slave} &&
[string match {*master_link_status:up*} [r -1 info replication]]
} else {
fail "Can't turn the instance into a replica"
}
}
test {FUNCTION - creation is replicated to replica} {
r function create LUA test DESCRIPTION {some description} {return 'hello'}
wait_for_condition 50 100 {
[r -1 function list] eq {{name test engine LUA description {some description}}}
} else {
fail "Failed waiting for function to replicate to replica"
}
}
test {FUNCTION - call on replica} {
r -1 fcall test 0
} {hello}
test {FUNCTION - delete is replicated to replica} {
r function delete test
wait_for_condition 50 100 {
[r -1 function list] eq {}
} else {
fail "Failed waiting for function to replicate to replica"
}
}
test "Disconnecting the replica from master instance" {
r -1 slaveof no one
# creating a function after disconnect to make sure function
# is replicated on rdb phase
r function create LUA test DESCRIPTION {some description} {return 'hello'}
# reconnect the replica
r -1 slaveof [srv 0 host] [srv 0 port]
wait_for_condition 50 100 {
[s -1 role] eq {slave} &&
[string match {*master_link_status:up*} [r -1 info replication]]
} else {
fail "Can't turn the instance into a replica"
}
}
test "FUNCTION - test replication to replica on rdb phase" {
r -1 fcall test 0
} {hello}
test "FUNCTION - test replication to replica on rdb phase info command" {
r -1 function info test WITHCODE
} {name test engine LUA description {some description} code {return 'hello'}}
test "FUNCTION - create on read only replica" {
catch {
r -1 function create LUA test DESCRIPTION {some description} {return 'hello'}
} e
set _ $e
} {*Can not create a function on a read only replica*}
test "FUNCTION - delete on read only replica" {
catch {
r -1 function delete test
} e
set _ $e
} {*Can not delete a function on a read only replica*}
test "FUNCTION - function effect is replicated to replica" {
r function create LUA test REPLACE {return redis.call('set', 'x', '1')}
r fcall test 0
assert {[r get x] eq {1}}
wait_for_condition 50 100 {
[r -1 get x] eq {1}
} else {
fail "Failed waiting function effect to be replicated to replica"
}
}
test "FUNCTION - modify key space of read only replica" {
catch {
r -1 fcall test 0
} e
set _ $e
} {*can't write against a read only replica*}
}
}
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment