]>
git.saurik.com Git - redis.git/blob - src/scripting.c
9 char *redisProtocolToLuaType_Int(lua_State
*lua
, char *reply
);
10 char *redisProtocolToLuaType_Bulk(lua_State
*lua
, char *reply
);
11 char *redisProtocolToLuaType_Status(lua_State
*lua
, char *reply
);
12 char *redisProtocolToLuaType_Error(lua_State
*lua
, char *reply
);
13 char *redisProtocolToLuaType_MultiBulk(lua_State
*lua
, char *reply
);
15 /* Take a Redis reply in the Redis protocol format and convert it into a
16 * Lua type. Thanks to this function, and the introduction of not connected
17 * clients, it is trvial to implement the redis() lua function.
19 * Basically we take the arguments, execute the Redis command in the context
20 * of a non connected client, then take the generated reply and convert it
21 * into a suitable Lua type. With this trick the scripting feature does not
22 * need the introduction of a full Redis internals API. Basically the script
23 * is like a normal client that bypasses all the slow I/O paths.
25 * Note: in this function we do not do any sanity check as the reply is
26 * generated by Redis directly. This allows use to go faster.
27 * The reply string can be altered during the parsing as it is discared
28 * after the conversion is completed.
30 * Errors are returned as a table with a single 'err' field set to the
34 char *redisProtocolToLuaType(lua_State
*lua
, char* reply
) {
39 p
= redisProtocolToLuaType_Int(lua
,reply
);
42 p
= redisProtocolToLuaType_Bulk(lua
,reply
);
45 p
= redisProtocolToLuaType_Status(lua
,reply
);
48 p
= redisProtocolToLuaType_Error(lua
,reply
);
51 p
= redisProtocolToLuaType_MultiBulk(lua
,reply
);
57 char *redisProtocolToLuaType_Int(lua_State
*lua
, char *reply
) {
58 char *p
= strchr(reply
+1,'\r');
61 string2ll(reply
+1,p
-reply
-1,&value
);
62 lua_pushnumber(lua
,(lua_Number
)value
);
66 char *redisProtocolToLuaType_Bulk(lua_State
*lua
, char *reply
) {
67 char *p
= strchr(reply
+1,'\r');
70 string2ll(reply
+1,p
-reply
-1,&bulklen
);
72 lua_pushboolean(lua
,0);
75 lua_pushlstring(lua
,p
+2,bulklen
);
80 char *redisProtocolToLuaType_Status(lua_State
*lua
, char *reply
) {
81 char *p
= strchr(reply
+1,'\r');
84 lua_pushstring(lua
,"ok");
85 lua_pushlstring(lua
,reply
+1,p
-reply
-1);
90 char *redisProtocolToLuaType_Error(lua_State
*lua
, char *reply
) {
91 char *p
= strchr(reply
+1,'\r');
94 lua_pushstring(lua
,"err");
95 lua_pushlstring(lua
,reply
+1,p
-reply
-1);
100 char *redisProtocolToLuaType_MultiBulk(lua_State
*lua
, char *reply
) {
101 char *p
= strchr(reply
+1,'\r');
105 string2ll(reply
+1,p
-reply
-1,&mbulklen
);
107 if (mbulklen
== -1) {
108 lua_pushboolean(lua
,0);
112 for (j
= 0; j
< mbulklen
; j
++) {
113 lua_pushnumber(lua
,j
+1);
114 p
= redisProtocolToLuaType(lua
,p
);
115 lua_settable(lua
,-3);
120 void luaPushError(lua_State
*lua
, char *error
) {
122 lua_pushstring(lua
,"err");
123 lua_pushstring(lua
, error
);
124 lua_settable(lua
,-3);
127 int luaRedisCommand(lua_State
*lua
) {
128 int j
, argc
= lua_gettop(lua
);
129 struct redisCommand
*cmd
;
131 redisClient
*c
= server
.lua_client
;
134 /* Build the arguments vector */
135 argv
= zmalloc(sizeof(robj
*)*argc
);
136 for (j
= 0; j
< argc
; j
++) {
137 if (!lua_isstring(lua
,j
+1)) break;
138 argv
[j
] = createStringObject((char*)lua_tostring(lua
,j
+1),
139 lua_strlen(lua
,j
+1));
142 /* Check if one of the arguments passed by the Lua script
143 * is not a string or an integer (lua_isstring() return true for
144 * integers as well). */
148 decrRefCount(argv
[j
]);
153 "Lua redis() command arguments must be strings or integers");
158 cmd
= lookupCommand(argv
[0]->ptr
);
159 if (!cmd
|| ((cmd
->arity
> 0 && cmd
->arity
!= argc
) ||
160 (argc
< -cmd
->arity
)))
162 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
166 "Wrong number of args calling Redis command From Lua script");
168 luaPushError(lua
,"Unknown Redis command called from Lua script");
172 /* Run the command in the context of a fake client */
177 /* Convert the result of the Redis command into a suitable Lua type.
178 * The first thing we need is to create a single string from the client
182 reply
= sdscatlen(reply
,c
->buf
,c
->bufpos
);
185 while(listLength(c
->reply
)) {
186 robj
*o
= listNodeValue(listFirst(c
->reply
));
188 reply
= sdscatlen(reply
,o
->ptr
,sdslen(o
->ptr
));
189 listDelNode(c
->reply
,listFirst(c
->reply
));
191 redisProtocolToLuaType(lua
,reply
);
194 /* Clean up. Command code may have changed argv/argc so we use the
195 * argv/argc of the client instead of the local variables. */
196 for (j
= 0; j
< c
->argc
; j
++)
197 decrRefCount(c
->argv
[j
]);
203 int luaLogCommand(lua_State
*lua
) {
204 int j
, argc
= lua_gettop(lua
);
209 luaPushError(lua
, "redis.log() requires two arguments or more.");
211 } else if (!lua_isnumber(lua
,-argc
)) {
212 luaPushError(lua
, "First argument must be a number (log level).");
215 level
= lua_tonumber(lua
,-argc
);
216 if (level
< REDIS_DEBUG
|| level
> REDIS_WARNING
) {
217 luaPushError(lua
, "Invalid debug level.");
221 /* Glue together all the arguments */
223 for (j
= 1; j
< argc
; j
++) {
227 s
= (char*)lua_tolstring(lua
,(-argc
)+j
,&len
);
229 if (j
!= 1) log
= sdscatlen(log
," ",1);
230 log
= sdscatlen(log
,s
,len
);
233 redisLogRaw(level
,log
);
238 void luaMaskCountHook(lua_State
*lua
, lua_Debug
*ar
) {
242 elapsed
= (ustime()/1000) - server
.lua_time_start
;
243 if (elapsed
>= server
.lua_time_limit
) {
244 redisLog(REDIS_NOTICE
,"Lua script aborted for max execution time after %lld milliseconds of running time.",elapsed
);
245 lua_pushstring(lua
,"Script aborted for max execution time.");
250 void scriptingInit(void) {
251 lua_State
*lua
= lua_open();
254 /* Register the redis commands table and fields */
258 lua_pushstring(lua
,"call");
259 lua_pushcfunction(lua
,luaRedisCommand
);
260 lua_settable(lua
,-3);
262 /* redis.log and log levels. */
263 lua_pushstring(lua
,"log");
264 lua_pushcfunction(lua
,luaLogCommand
);
265 lua_settable(lua
,-3);
267 lua_pushstring(lua
,"LOG_DEBUG");
268 lua_pushnumber(lua
,REDIS_DEBUG
);
269 lua_settable(lua
,-3);
271 lua_pushstring(lua
,"LOG_VERBOSE");
272 lua_pushnumber(lua
,REDIS_VERBOSE
);
273 lua_settable(lua
,-3);
275 lua_pushstring(lua
,"LOG_NOTICE");
276 lua_pushnumber(lua
,REDIS_NOTICE
);
277 lua_settable(lua
,-3);
279 lua_pushstring(lua
,"LOG_WARNING");
280 lua_pushnumber(lua
,REDIS_WARNING
);
281 lua_settable(lua
,-3);
283 /* Finally set the table as 'redis' global var. */
284 lua_setglobal(lua
,"redis");
286 /* Create the (non connected) client that we use to execute Redis commands
287 * inside the Lua interpreter */
288 server
.lua_client
= createClient(-1);
289 server
.lua_client
->flags
|= REDIS_LUA_CLIENT
;
294 /* Hash the scripit into a SHA1 digest. We use this as Lua function name.
295 * Digest should point to a 41 bytes buffer: 40 for SHA1 converted into an
296 * hexadecimal number, plus 1 byte for null term. */
297 void hashScript(char *digest
, char *script
, size_t len
) {
299 unsigned char hash
[20];
300 char *cset
= "0123456789abcdef";
304 SHA1Update(&ctx
,(unsigned char*)script
,len
);
305 SHA1Final(hash
,&ctx
);
307 for (j
= 0; j
< 20; j
++) {
308 digest
[j
*2] = cset
[((hash
[j
]&0xF0)>>4)];
309 digest
[j
*2+1] = cset
[(hash
[j
]&0xF)];
314 void luaReplyToRedisReply(redisClient
*c
, lua_State
*lua
) {
315 int t
= lua_type(lua
,-1);
319 addReplyBulkCBuffer(c
,(char*)lua_tostring(lua
,-1),lua_strlen(lua
,-1));
322 addReply(c
,lua_toboolean(lua
,-1) ? shared
.cone
: shared
.nullbulk
);
325 addReplyLongLong(c
,(long long)lua_tonumber(lua
,-1));
328 /* We need to check if it is an array, an error, or a status reply.
329 * Error are returned as a single element table with 'err' field.
330 * Status replies are returned as single elment table with 'ok' field */
331 lua_pushstring(lua
,"err");
332 lua_gettable(lua
,-2);
333 t
= lua_type(lua
,-1);
334 if (t
== LUA_TSTRING
) {
335 sds err
= sdsnew(lua_tostring(lua
,-1));
336 sdsmapchars(err
,"\r\n"," ",2);
337 addReplySds(c
,sdscatprintf(sdsempty(),"-%s\r\n",err
));
344 lua_pushstring(lua
,"ok");
345 lua_gettable(lua
,-2);
346 t
= lua_type(lua
,-1);
347 if (t
== LUA_TSTRING
) {
348 sds ok
= sdsnew(lua_tostring(lua
,-1));
349 sdsmapchars(ok
,"\r\n"," ",2);
350 addReplySds(c
,sdscatprintf(sdsempty(),"+%s\r\n",ok
));
354 void *replylen
= addDeferredMultiBulkLength(c
);
355 int j
= 1, mbulklen
= 0;
357 lua_pop(lua
,1); /* Discard the 'ok' field value we popped */
359 lua_pushnumber(lua
,j
++);
360 lua_gettable(lua
,-2);
361 t
= lua_type(lua
,-1);
366 luaReplyToRedisReply(c
, lua
);
369 setDeferredMultiBulkLength(c
,replylen
,mbulklen
);
373 addReply(c
,shared
.nullbulk
);
378 /* Set an array of Redis String Objects as a Lua array (table) stored into a
379 * global variable. */
380 void luaSetGlobalArray(lua_State
*lua
, char *var
, robj
**elev
, int elec
) {
384 for (j
= 0; j
< elec
; j
++) {
385 lua_pushlstring(lua
,(char*)elev
[j
]->ptr
,sdslen(elev
[j
]->ptr
));
386 lua_rawseti(lua
,-2,j
+1);
388 lua_setglobal(lua
,var
);
391 void evalGenericCommand(redisClient
*c
, int evalsha
) {
392 lua_State
*lua
= server
.lua
;
396 /* Get the number of arguments that are keys */
397 if (getLongLongFromObjectOrReply(c
,c
->argv
[2],&numkeys
,NULL
) != REDIS_OK
)
399 if (numkeys
> (c
->argc
- 3)) {
400 addReplyError(c
,"Number of keys can't be greater than number of args");
404 /* We obtain the script SHA1, then check if this function is already
405 * defined into the Lua state */
409 /* Hash the code if this is an EVAL call */
410 hashScript(funcname
+2,c
->argv
[1]->ptr
,sdslen(c
->argv
[1]->ptr
));
412 /* We already have the SHA if it is a EVALSHA */
414 char *sha
= c
->argv
[1]->ptr
;
416 for (j
= 0; j
< 40; j
++)
417 funcname
[j
+2] = tolower(sha
[j
]);
421 lua_getglobal(lua
, funcname
);
422 if (lua_isnil(lua
,1)) {
425 /* Function not defined... let's define it if we have the
426 * body of the funciton. If this is an EVALSHA call we can just
427 * return an error. */
429 addReply(c
, shared
.noscripterr
);
430 lua_pop(lua
,1); /* remove the nil from the stack */
433 funcdef
= sdsempty();
435 lua_pop(lua
,1); /* remove the nil from the stack */
436 funcdef
= sdscat(funcdef
,"function ");
437 funcdef
= sdscatlen(funcdef
,funcname
,42);
438 funcdef
= sdscatlen(funcdef
," ()\n",4);
439 funcdef
= sdscatlen(funcdef
,c
->argv
[1]->ptr
,sdslen(c
->argv
[1]->ptr
));
440 funcdef
= sdscatlen(funcdef
,"\nend\n",5);
441 /* printf("Defining:\n%s\n",funcdef); */
443 if (luaL_loadbuffer(lua
,funcdef
,sdslen(funcdef
),"func definition")) {
444 addReplyErrorFormat(c
,"Error compiling script (new function): %s\n",
445 lua_tostring(lua
,-1));
451 if (lua_pcall(lua
,0,0,0)) {
452 addReplyErrorFormat(c
,"Error running script (new function): %s\n",
453 lua_tostring(lua
,-1));
457 lua_getglobal(lua
, funcname
);
460 /* Populate the argv and keys table accordingly to the arguments that
462 luaSetGlobalArray(lua
,"KEYS",c
->argv
+3,numkeys
);
463 luaSetGlobalArray(lua
,"ARGV",c
->argv
+3+numkeys
,c
->argc
-3-numkeys
);
465 /* Select the right DB in the context of the Lua client */
466 selectDb(server
.lua_client
,c
->db
->id
);
468 /* Set an hook in order to be able to stop the script execution if it
469 * is running for too much time.
470 * We set the hook only if the time limit is enabled as the hook will
471 * make the Lua script execution slower. */
472 if (server
.lua_time_limit
> 0) {
473 lua_sethook(lua
,luaMaskCountHook
,LUA_MASKCOUNT
,100000);
474 server
.lua_time_start
= ustime()/1000;
476 lua_sethook(lua
,luaMaskCountHook
,0,0);
479 /* At this point whatever this script was never seen before or if it was
480 * already defined, we can call it. We have zero arguments and expect
481 * a single return value. */
482 if (lua_pcall(lua
,0,1,0)) {
483 selectDb(c
,server
.lua_client
->db
->id
); /* set DB ID from Lua client */
484 addReplyErrorFormat(c
,"Error running script (call to %s): %s\n",
485 funcname
, lua_tostring(lua
,-1));
487 lua_gc(lua
,LUA_GCCOLLECT
,0);
490 selectDb(c
,server
.lua_client
->db
->id
); /* set DB ID from Lua client */
491 luaReplyToRedisReply(c
,lua
);
492 lua_gc(lua
,LUA_GCSTEP
,1);
495 void evalCommand(redisClient
*c
) {
496 evalGenericCommand(c
,0);
499 void evalShaCommand(redisClient
*c
) {
500 if (sdslen(c
->argv
[1]->ptr
) != 40) {
501 /* We know that a match is not possible if the provided SHA is
502 * not the right length. So we return an error ASAP, this way
503 * evalGenericCommand() can be implemented without string length
505 addReply(c
, shared
.noscripterr
);
508 evalGenericCommand(c
,1);