]> git.saurik.com Git - redis.git/blob - src/scripting.c
0b6eb616c63829ef0a90cb8d7556024810e30e2e
[redis.git] / src / scripting.c
1 #include "redis.h"
2 #include "sha1.h"
3
4 #include <lua.h>
5 #include <lauxlib.h>
6 #include <lualib.h>
7 #include <ctype.h>
8
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);
14
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.
18 *
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.
24 *
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.
29 *
30 * Errors are returned as a table with a single 'err' field set to the
31 * error string.
32 */
33
34 char *redisProtocolToLuaType(lua_State *lua, char* reply) {
35 char *p = reply;
36
37 switch(*p) {
38 case ':':
39 p = redisProtocolToLuaType_Int(lua,reply);
40 break;
41 case '$':
42 p = redisProtocolToLuaType_Bulk(lua,reply);
43 break;
44 case '+':
45 p = redisProtocolToLuaType_Status(lua,reply);
46 break;
47 case '-':
48 p = redisProtocolToLuaType_Error(lua,reply);
49 break;
50 case '*':
51 p = redisProtocolToLuaType_MultiBulk(lua,reply);
52 break;
53 }
54 return p;
55 }
56
57 char *redisProtocolToLuaType_Int(lua_State *lua, char *reply) {
58 char *p = strchr(reply+1,'\r');
59 long long value;
60
61 string2ll(reply+1,p-reply-1,&value);
62 lua_pushnumber(lua,(lua_Number)value);
63 return p+2;
64 }
65
66 char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply) {
67 char *p = strchr(reply+1,'\r');
68 long long bulklen;
69
70 string2ll(reply+1,p-reply-1,&bulklen);
71 if (bulklen == -1) {
72 lua_pushboolean(lua,0);
73 return p+2;
74 } else {
75 lua_pushlstring(lua,p+2,bulklen);
76 return p+2+bulklen+2;
77 }
78 }
79
80 char *redisProtocolToLuaType_Status(lua_State *lua, char *reply) {
81 char *p = strchr(reply+1,'\r');
82
83 lua_newtable(lua);
84 lua_pushstring(lua,"ok");
85 lua_pushlstring(lua,reply+1,p-reply-1);
86 lua_settable(lua,-3);
87 return p+2;
88 }
89
90 char *redisProtocolToLuaType_Error(lua_State *lua, char *reply) {
91 char *p = strchr(reply+1,'\r');
92
93 lua_newtable(lua);
94 lua_pushstring(lua,"err");
95 lua_pushlstring(lua,reply+1,p-reply-1);
96 lua_settable(lua,-3);
97 return p+2;
98 }
99
100 char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply) {
101 char *p = strchr(reply+1,'\r');
102 long long mbulklen;
103 int j = 0;
104
105 string2ll(reply+1,p-reply-1,&mbulklen);
106 p += 2;
107 if (mbulklen == -1) {
108 lua_pushboolean(lua,0);
109 return p;
110 }
111 lua_newtable(lua);
112 for (j = 0; j < mbulklen; j++) {
113 lua_pushnumber(lua,j+1);
114 p = redisProtocolToLuaType(lua,p);
115 lua_settable(lua,-3);
116 }
117 return p;
118 }
119
120 void luaPushError(lua_State *lua, char *error) {
121 lua_newtable(lua);
122 lua_pushstring(lua,"err");
123 lua_pushstring(lua, error);
124 lua_settable(lua,-3);
125 }
126
127 int luaRedisCommand(lua_State *lua) {
128 int j, argc = lua_gettop(lua);
129 struct redisCommand *cmd;
130 robj **argv;
131 redisClient *c = server.lua_client;
132 sds reply;
133
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));
140 }
141
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). */
145 if (j != argc) {
146 j--;
147 while (j >= 0) {
148 decrRefCount(argv[j]);
149 j--;
150 }
151 zfree(argv);
152 luaPushError(lua,
153 "Lua redis() command arguments must be strings or integers");
154 return 1;
155 }
156
157 /* Command lookup */
158 cmd = lookupCommand(argv[0]->ptr);
159 if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||
160 (argc < -cmd->arity)))
161 {
162 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
163 zfree(argv);
164 if (cmd)
165 luaPushError(lua,
166 "Wrong number of args calling Redis command From Lua script");
167 else
168 luaPushError(lua,"Unknown Redis command called from Lua script");
169 return 1;
170 }
171
172 /* Run the command in the context of a fake client */
173 c->argv = argv;
174 c->argc = argc;
175 cmd->proc(c);
176
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
179 * output buffers. */
180 reply = sdsempty();
181 if (c->bufpos) {
182 reply = sdscatlen(reply,c->buf,c->bufpos);
183 c->bufpos = 0;
184 }
185 while(listLength(c->reply)) {
186 robj *o = listNodeValue(listFirst(c->reply));
187
188 reply = sdscatlen(reply,o->ptr,sdslen(o->ptr));
189 listDelNode(c->reply,listFirst(c->reply));
190 }
191 redisProtocolToLuaType(lua,reply);
192 sdsfree(reply);
193
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]);
198 zfree(c->argv);
199
200 return 1;
201 }
202
203 void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
204 long long elapsed;
205 REDIS_NOTUSED(ar);
206
207 elapsed = (ustime()/1000) - server.lua_time_start;
208 if (elapsed >= server.lua_time_limit) {
209 redisLog(REDIS_NOTICE,"Lua script aborted for max execution time after %lld milliseconds of running time.",elapsed);
210 lua_pushstring(lua,"Script aborted for max execution time.");
211 lua_error(lua);
212 }
213 }
214
215 void scriptingInit(void) {
216 lua_State *lua = lua_open();
217 luaL_openlibs(lua);
218
219 /* Register the 'r' command */
220 lua_pushcfunction(lua,luaRedisCommand);
221 lua_setglobal(lua,"redis");
222
223 /* Create the (non connected) client that we use to execute Redis commands
224 * inside the Lua interpreter */
225 server.lua_client = createClient(-1);
226 server.lua_client->flags |= REDIS_LUA_CLIENT;
227
228 server.lua = lua;
229 }
230
231 /* Hash the scripit into a SHA1 digest. We use this as Lua function name.
232 * Digest should point to a 41 bytes buffer: 40 for SHA1 converted into an
233 * hexadecimal number, plus 1 byte for null term. */
234 void hashScript(char *digest, char *script, size_t len) {
235 SHA1_CTX ctx;
236 unsigned char hash[20];
237 char *cset = "0123456789abcdef";
238 int j;
239
240 SHA1Init(&ctx);
241 SHA1Update(&ctx,(unsigned char*)script,len);
242 SHA1Final(hash,&ctx);
243
244 for (j = 0; j < 20; j++) {
245 digest[j*2] = cset[((hash[j]&0xF0)>>4)];
246 digest[j*2+1] = cset[(hash[j]&0xF)];
247 }
248 digest[40] = '\0';
249 }
250
251 void luaReplyToRedisReply(redisClient *c, lua_State *lua) {
252 int t = lua_type(lua,-1);
253
254 switch(t) {
255 case LUA_TSTRING:
256 addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1));
257 break;
258 case LUA_TBOOLEAN:
259 addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk);
260 break;
261 case LUA_TNUMBER:
262 addReplyLongLong(c,(long long)lua_tonumber(lua,-1));
263 break;
264 case LUA_TTABLE:
265 /* We need to check if it is an array, an error, or a status reply.
266 * Error are returned as a single element table with 'err' field.
267 * Status replies are returned as single elment table with 'ok' field */
268 lua_pushstring(lua,"err");
269 lua_gettable(lua,-2);
270 t = lua_type(lua,-1);
271 if (t == LUA_TSTRING) {
272 addReplySds(c,sdscatprintf(sdsempty(),
273 "-%s\r\n",(char*)lua_tostring(lua,-1)));
274 lua_pop(lua,2);
275 return;
276 }
277
278 lua_pop(lua,1);
279 lua_pushstring(lua,"ok");
280 lua_gettable(lua,-2);
281 t = lua_type(lua,-1);
282 if (t == LUA_TSTRING) {
283 addReplySds(c,sdscatprintf(sdsempty(),
284 "+%s\r\n",(char*)lua_tostring(lua,-1)));
285 lua_pop(lua,1);
286 } else {
287 void *replylen = addDeferredMultiBulkLength(c);
288 int j = 1, mbulklen = 0;
289
290 lua_pop(lua,1); /* Discard the 'ok' field value we popped */
291 while(1) {
292 lua_pushnumber(lua,j++);
293 lua_gettable(lua,-2);
294 t = lua_type(lua,-1);
295 if (t == LUA_TNIL) {
296 lua_pop(lua,1);
297 break;
298 }
299 luaReplyToRedisReply(c, lua);
300 mbulklen++;
301 }
302 setDeferredMultiBulkLength(c,replylen,mbulklen);
303 }
304 break;
305 default:
306 addReply(c,shared.nullbulk);
307 }
308 lua_pop(lua,1);
309 }
310
311 /* Set an array of Redis String Objects as a Lua array (table) stored into a
312 * global variable. */
313 void luaSetGlobalArray(lua_State *lua, char *var, robj **elev, int elec) {
314 int j;
315
316 lua_newtable(lua);
317 for (j = 0; j < elec; j++) {
318 lua_pushlstring(lua,(char*)elev[j]->ptr,sdslen(elev[j]->ptr));
319 lua_rawseti(lua,-2,j+1);
320 }
321 lua_setglobal(lua,var);
322 }
323
324 void evalGenericCommand(redisClient *c, int evalsha) {
325 lua_State *lua = server.lua;
326 char funcname[43];
327 long long numkeys;
328
329 /* Get the number of arguments that are keys */
330 if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != REDIS_OK)
331 return;
332 if (numkeys > (c->argc - 3)) {
333 addReplyError(c,"Number of keys can't be greater than number of args");
334 return;
335 }
336
337 /* We obtain the script SHA1, then check if this function is already
338 * defined into the Lua state */
339 funcname[0] = 'f';
340 funcname[1] = '_';
341 if (!evalsha) {
342 /* Hash the code if this is an EVAL call */
343 hashScript(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr));
344 } else {
345 /* We already have the SHA if it is a EVALSHA */
346 int j;
347 char *sha = c->argv[1]->ptr;
348
349 for (j = 0; j < 40; j++)
350 funcname[j+2] = tolower(sha[j]);
351 funcname[42] = '\0';
352 }
353
354 lua_getglobal(lua, funcname);
355 if (lua_isnil(lua,1)) {
356 sds funcdef;
357
358 /* Function not defined... let's define it if we have the
359 * body of the funciton. If this is an EVALSHA call we can just
360 * return an error. */
361 if (evalsha) {
362 addReply(c, shared.noscripterr);
363 lua_pop(lua,1); /* remove the nil from the stack */
364 return;
365 }
366 funcdef = sdsempty();
367
368 lua_pop(lua,1); /* remove the nil from the stack */
369 funcdef = sdscat(funcdef,"function ");
370 funcdef = sdscatlen(funcdef,funcname,42);
371 funcdef = sdscatlen(funcdef," ()\n",4);
372 funcdef = sdscatlen(funcdef,c->argv[1]->ptr,sdslen(c->argv[1]->ptr));
373 funcdef = sdscatlen(funcdef,"\nend\n",5);
374 /* printf("Defining:\n%s\n",funcdef); */
375
376 if (luaL_loadbuffer(lua,funcdef,sdslen(funcdef),"func definition")) {
377 addReplyErrorFormat(c,"Error compiling script (new function): %s\n",
378 lua_tostring(lua,-1));
379 lua_pop(lua,1);
380 sdsfree(funcdef);
381 return;
382 }
383 sdsfree(funcdef);
384 if (lua_pcall(lua,0,0,0)) {
385 addReplyErrorFormat(c,"Error running script (new function): %s\n",
386 lua_tostring(lua,-1));
387 lua_pop(lua,1);
388 return;
389 }
390 lua_getglobal(lua, funcname);
391 }
392
393 /* Populate the argv and keys table accordingly to the arguments that
394 * EVAL received. */
395 luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys);
396 luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);
397
398 /* Select the right DB in the context of the Lua client */
399 selectDb(server.lua_client,c->db->id);
400
401 /* Set an hook in order to be able to stop the script execution if it
402 * is running for too much time.
403 * We set the hook only if the time limit is enabled as the hook will
404 * make the Lua script execution slower. */
405 if (server.lua_time_limit > 0) {
406 lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000);
407 server.lua_time_start = ustime()/1000;
408 } else {
409 lua_sethook(lua,luaMaskCountHook,0,0);
410 }
411
412 /* At this point whatever this script was never seen before or if it was
413 * already defined, we can call it. We have zero arguments and expect
414 * a single return value. */
415 if (lua_pcall(lua,0,1,0)) {
416 selectDb(c,server.lua_client->db->id); /* set DB ID from Lua client */
417 addReplyErrorFormat(c,"Error running script (call to %s): %s\n",
418 funcname, lua_tostring(lua,-1));
419 lua_pop(lua,1);
420 lua_gc(lua,LUA_GCCOLLECT,0);
421 return;
422 }
423 selectDb(c,server.lua_client->db->id); /* set DB ID from Lua client */
424 luaReplyToRedisReply(c,lua);
425 lua_gc(lua,LUA_GCSTEP,1);
426 }
427
428 void evalCommand(redisClient *c) {
429 evalGenericCommand(c,0);
430 }
431
432 void evalShaCommand(redisClient *c) {
433 if (sdslen(c->argv[1]->ptr) != 40) {
434 /* We know that a match is not possible if the provided SHA is
435 * not the right length. So we return an error ASAP, this way
436 * evalGenericCommand() can be implemented without string length
437 * sanity check */
438 addReply(c, shared.noscripterr);
439 return;
440 }
441 evalGenericCommand(c,1);
442 }