intluaRedisGenericCommand(lua_State *lua, int raise_error){ ...... /* If we are using single commands replication, we need to wrap what * we propagate into a MULTI/EXEC block, so that it will be atomic like * a Lua script in the context of AOF and slaves. */ if (server.lua_replicate_commands && !server.lua_multi_emitted && server.lua_write_dirty && server.lua_repl != PROPAGATE_NONE) { execCommandPropagateMulti(server.lua_caller); server.lua_multi_emitted = 1; }
/* Run the command */ int call_flags = CMD_CALL_SLOWLOG | CMD_CALL_STATS; if (server.lua_replicate_commands) { /* Set flags according to redis.set_repl() settings. */ if (server.lua_repl & PROPAGATE_AOF) call_flags |= CMD_CALL_PROPAGATE_AOF; if (server.lua_repl & PROPAGATE_REPL) call_flags |= CMD_CALL_PROPAGATE_REPL; } call(c, call_flags); ...... }
voidevalGenericCommand(client *c, int evalsha){ ...... /* If we are using single commands replication, emit EXEC if there * was at least a write. */ if (server.lua_replicate_commands) { preventCommandPropagation(c); if (server.lua_multi_emitted) { robj *propargv[1]; propargv[0] = createStringObject("EXEC",4); alsoPropagate(server.execCommand,c->db->id,propargv,1, PROPAGATE_AOF|PROPAGATE_REPL); decrRefCount(propargv[0]); } } ...... }
/* Initialize a dictionary we use to map SHAs to scripts. * This is useful for replication, as we need to replicate EVALSHA * as EVAL, so we need to remember the associated script. */ server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL);
/* Register the redis commands table and fields */ lua_newtable(lua);
voidevalGenericCommand(client *c, int evalsha){ lua_State *lua = server.lua; char funcname[43]; longlong numkeys; int delhook = 0, err;
/* When we replicate whole scripts, we want the same PRNG sequence at * every call so that our PRNG is not affected by external state. */ redisSrand48(0);
/* We set this flag to zero to remember that so far no random command * was called. This way we can allow the user to call commands like * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command * is called (otherwise the replication and AOF would end with non * deterministic sequences). * * Thanks to this flag we'll raise an error every time a write command * is called after a random command was used. */ server.lua_random_dirty = 0; server.lua_write_dirty = 0; server.lua_replicate_commands = server.lua_always_replicate_commands; server.lua_multi_emitted = 0; server.lua_repl = PROPAGATE_AOF|PROPAGATE_REPL;
/* Get the number of arguments that are keys */ if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != C_OK) return; if (numkeys > (c->argc - 3)) { addReplyError(c,"Number of keys can't be greater than number of args"); return; } elseif (numkeys < 0) { addReplyError(c,"Number of keys can't be negative"); return; }
/* We obtain the script SHA1, then check if this function is already * defined into the Lua state */ funcname[0] = 'f'; funcname[1] = '_'; if (!evalsha) { /* Hash the code if this is an EVAL call */ sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr)); } else { /* We already have the SHA if it is a EVALSHA */ int j; char *sha = c->argv[1]->ptr;
/* Convert to lowercase. We don't use tolower since the function * managed to always show up in the profiler output consuming * a non trivial amount of time. */ for (j = 0; j < 40; j++) funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ? sha[j]+('a'-'A') : sha[j]; funcname[42] = '\0'; }
/* Push the pcall error handler function on the stack. */ lua_getglobal(lua, "__redis__err__handler");
/* Try to lookup the Lua function */ lua_getglobal(lua, funcname); if (lua_isnil(lua,-1)) { lua_pop(lua,1); /* remove the nil from the stack */ /* Function not defined... let's define it if we have the * body of the function. If this is an EVALSHA call we can just * return an error. */ if (evalsha) { lua_pop(lua,1); /* remove the error handler from the stack. */ addReply(c, shared.noscripterr); return; } if (luaCreateFunction(c,lua,funcname,c->argv[1]) == C_ERR) { lua_pop(lua,1); /* remove the error handler from the stack. */ /* The error is sent to the client by luaCreateFunction() * itself when it returns C_ERR. */ return; } /* Now the following is guaranteed to return non nil */ lua_getglobal(lua, funcname); serverAssert(!lua_isnil(lua,-1)); }
/* Populate the argv and keys table accordingly to the arguments that * EVAL received. */ luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys); luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);
/* Select the right DB in the context of the Lua client */ selectDb(server.lua_client,c->db->id);
/* Set a hook in order to be able to stop the script execution if it * is running for too much time. * We set the hook only if the time limit is enabled as the hook will * make the Lua script execution slower. * * If we are debugging, we set instead a "line" hook so that the * debugger is call-back at every line executed by the script. */ server.lua_caller = c; server.lua_time_start = mstime(); server.lua_kill = 0; if (server.lua_time_limit > 0 && server.masterhost == NULL && ldb.active == 0) { lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000); delhook = 1; } elseif (ldb.active) { lua_sethook(server.lua,luaLdbLineHook,LUA_MASKLINE|LUA_MASKCOUNT,100000); delhook = 1; }
/* At this point whether this script was never seen before or if it was * already defined, we can call it. We have zero arguments and expect * a single return value. */ err = lua_pcall(lua,0,1,-2);
/* Perform some cleanup that we need to do both on error and success. */ if (delhook) lua_sethook(lua,NULL,0,0); /* Disable hook */ if (server.lua_timedout) { server.lua_timedout = 0; /* Restore the readable handler that was unregistered when the * script timeout was detected. */ aeCreateFileEvent(server.el,c->fd,AE_READABLE, readQueryFromClient,c); } server.lua_caller = NULL;
if (err) { addReplyErrorFormat(c,"Error running script (call to %s): %s\n", funcname, lua_tostring(lua,-1)); lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */ } else { /* On success convert the Lua return value into Redis protocol, and * send it to * the client. */ luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */ lua_pop(lua,1); /* Remove the error handler. */ }
/* If we are using single commands replication, emit EXEC if there * was at least a write. */ if (server.lua_replicate_commands) { preventCommandPropagation(c); if (server.lua_multi_emitted) { robj *propargv[1]; propargv[0] = createStringObject("EXEC",4); alsoPropagate(server.execCommand,c->db->id,propargv,1, PROPAGATE_AOF|PROPAGATE_REPL); decrRefCount(propargv[0]); } }
...... if (evalsha && !server.lua_replicate_commands) { if (!replicationScriptCacheExists(c->argv[1]->ptr)) { /* This script is not in our script cache, replicate it as * EVAL, then add it into the script cache, as from now on * slaves and AOF know about it. */ robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr);
/* By using Lua debug hooks it is possible to trigger a recursive call * to luaRedisGenericCommand(), which normally should never happen. * To make this function reentrant is futile and makes it slower, but * we should at least detect such a misuse, and abort. */ if (inuse) { char *recursion_warning = "luaRedisGenericCommand() recursive call detected. " "Are you doing funny stuff with Lua debug hooks?"; serverLog(LL_WARNING,"%s",recursion_warning); luaPushError(lua,recursion_warning); return1; } inuse++;
/* Require at least one argument */ if (argc == 0) { luaPushError(lua, "Please specify at least one argument for redis.call()"); inuse--; return raise_error ? luaRaiseError(lua) : 1; }
/* Build the arguments vector */ if (argv_size < argc) { argv = zrealloc(argv,sizeof(robj*)*argc); argv_size = argc; }
if (lua_type(lua,j+1) == LUA_TNUMBER) { /* We can't use lua_tolstring() for number -> string conversion * since Lua uses a format specifier that loses precision. */ lua_Number num = lua_tonumber(lua,j+1);
obj_len = snprintf(dbuf,sizeof(dbuf),"%.17g",(double)num); obj_s = dbuf; } else { obj_s = (char*)lua_tolstring(lua,j+1,&obj_len); if (obj_s == NULL) break; /* Not a string. */ }
/* Try to use a cached object. */ if (j < LUA_CMD_OBJCACHE_SIZE && cached_objects[j] && cached_objects_len[j] >= obj_len) { sds s = cached_objects[j]->ptr; argv[j] = cached_objects[j]; cached_objects[j] = NULL; memcpy(s,obj_s,obj_len+1); sdssetlen(s, obj_len); } else { argv[j] = createStringObject(obj_s, obj_len); } }
/* Check if one of the arguments passed by the Lua script * is not a string or an integer (lua_isstring() return true for * integers as well). */ if (j != argc) { j--; while (j >= 0) { decrRefCount(argv[j]); j--; } luaPushError(lua, "Lua redis() command arguments must be strings or integers"); inuse--; return raise_error ? luaRaiseError(lua) : 1; }
/* Command lookup */ cmd = lookupCommand(argv[0]->ptr); if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) || (argc < -cmd->arity))) { if (cmd) luaPushError(lua, "Wrong number of args calling Redis command From Lua script"); else luaPushError(lua,"Unknown Redis command called from Lua script"); goto cleanup; } c->cmd = c->lastcmd = cmd;
lookupCommand 查表,找到要执行的 redis 命令
1 2 3 4 5
/* There are commands that are not allowed inside scripts. */ if (cmd->flags & CMD_NOSCRIPT) { luaPushError(lua, "This Redis command is not allowed from scripts"); goto cleanup; }
/* Write commands are forbidden against read-only slaves, or if a * command marked as non-deterministic was already called in the context * of this script. */ if (cmd->flags & CMD_WRITE) { if (server.lua_random_dirty && !server.lua_replicate_commands) { luaPushError(lua, "Write commands not allowed after non deterministic commands. Call redis.replicate_commands() at the start of your script in order to switch to single commands replication mode."); goto cleanup; } elseif (server.masterhost && server.repl_slave_ro && !server.loading && !(server.lua_caller->flags & CLIENT_MASTER)) { luaPushError(lua, shared.roslaveerr->ptr); goto cleanup; } elseif (server.stop_writes_on_bgsave_err && server.saveparamslen > 0 && server.lastbgsave_status == C_ERR) { luaPushError(lua, shared.bgsaveerr->ptr); goto cleanup; } }
/* If we reached the memory limit configured via maxmemory, commands that * could enlarge the memory usage are not allowed, but only if this is the * first write in the context of this script, otherwise we can't stop * in the middle. */ if (server.maxmemory && server.lua_write_dirty == 0 && (cmd->flags & CMD_DENYOOM)) { if (freeMemoryIfNeeded() == C_ERR) { luaPushError(lua, shared.oomerr->ptr); goto cleanup; } }
if (cmd->flags & CMD_RANDOM) server.lua_random_dirty = 1; if (cmd->flags & CMD_WRITE) server.lua_write_dirty = 1;
设置 cmd->flags
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* If this is a Redis Cluster node, we need to make sure Lua is not * trying to access non-local keys, with the exception of commands * received from our master or when loading the AOF back in memory. */ if (server.cluster_enabled && !server.loading && !(server.lua_caller->flags & CLIENT_MASTER)) { /* Duplicate relevant flags in the lua client. */ c->flags &= ~(CLIENT_READONLY|CLIENT_ASKING); c->flags |= server.lua_caller->flags & (CLIENT_READONLY|CLIENT_ASKING); if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) != server.cluster->myself) { luaPushError(lua, "Lua script attempted to access a non local key in a " "cluster node"); goto cleanup; } }
/* If we are using single commands replication, we need to wrap what * we propagate into a MULTI/EXEC block, so that it will be atomic like * a Lua script in the context of AOF and slaves. */ if (server.lua_replicate_commands && !server.lua_multi_emitted && server.lua_write_dirty && server.lua_repl != PROPAGATE_NONE) { execCommandPropagateMulti(server.lua_caller); server.lua_multi_emitted = 1; }
如果是 effect replication 模式,生成 multi 事务命令用于复制
1 2 3 4 5 6 7 8 9 10
/* Run the command */ int call_flags = CMD_CALL_SLOWLOG | CMD_CALL_STATS; if (server.lua_replicate_commands) { /* Set flags according to redis.set_repl() settings. */ if (server.lua_repl & PROPAGATE_AOF) call_flags |= CMD_CALL_PROPAGATE_AOF; if (server.lua_repl & PROPAGATE_REPL) call_flags |= CMD_CALL_PROPAGATE_REPL; } call(c,call_flags);
/* Convert the result of the Redis command into a suitable Lua type. * The first thing we need is to create a single string from the client * output buffers. */ if (listLength(c->reply) == 0 && c->bufpos < PROTO_REPLY_CHUNK_BYTES) { /* This is a fast path for the common case of a reply inside the * client static buffer. Don't create an SDS string but just use * the client buffer directly. */ c->buf[c->bufpos] = '\0'; reply = c->buf; c->bufpos = 0; } else { reply = sdsnewlen(c->buf,c->bufpos); c->bufpos = 0; while(listLength(c->reply)) { robj *o = listNodeValue(listFirst(c->reply));