]> git.saurik.com Git - redis.git/blob - redis-cli.c
An interesting refactoring + more expressive internal API
[redis.git] / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "fmacros.h"
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37
38 #include "anet.h"
39 #include "sds.h"
40 #include "adlist.h"
41 #include "zmalloc.h"
42
43 #define REDIS_CMD_INLINE 1
44 #define REDIS_CMD_BULK 2
45 #define REDIS_CMD_MULTIBULK 4
46
47 #define REDIS_NOTUSED(V) ((void) V)
48
49 static struct config {
50 char *hostip;
51 int hostport;
52 long repeat;
53 int dbnum;
54 int interactive;
55 } config;
56
57 struct redisCommand {
58 char *name;
59 int arity;
60 int flags;
61 };
62
63 static struct redisCommand cmdTable[] = {
64 {"get",2,REDIS_CMD_INLINE},
65 {"set",3,REDIS_CMD_BULK},
66 {"setnx",3,REDIS_CMD_BULK},
67 {"append",3,REDIS_CMD_BULK},
68 {"substr",4,REDIS_CMD_INLINE},
69 {"del",-2,REDIS_CMD_INLINE},
70 {"exists",2,REDIS_CMD_INLINE},
71 {"incr",2,REDIS_CMD_INLINE},
72 {"decr",2,REDIS_CMD_INLINE},
73 {"rpush",3,REDIS_CMD_BULK},
74 {"lpush",3,REDIS_CMD_BULK},
75 {"rpop",2,REDIS_CMD_INLINE},
76 {"lpop",2,REDIS_CMD_INLINE},
77 {"brpop",-3,REDIS_CMD_INLINE},
78 {"blpop",-3,REDIS_CMD_INLINE},
79 {"llen",2,REDIS_CMD_INLINE},
80 {"lindex",3,REDIS_CMD_INLINE},
81 {"lset",4,REDIS_CMD_BULK},
82 {"lrange",4,REDIS_CMD_INLINE},
83 {"ltrim",4,REDIS_CMD_INLINE},
84 {"lrem",4,REDIS_CMD_BULK},
85 {"rpoplpush",3,REDIS_CMD_BULK},
86 {"sadd",3,REDIS_CMD_BULK},
87 {"srem",3,REDIS_CMD_BULK},
88 {"smove",4,REDIS_CMD_BULK},
89 {"sismember",3,REDIS_CMD_BULK},
90 {"scard",2,REDIS_CMD_INLINE},
91 {"spop",2,REDIS_CMD_INLINE},
92 {"srandmember",2,REDIS_CMD_INLINE},
93 {"sinter",-2,REDIS_CMD_INLINE},
94 {"sinterstore",-3,REDIS_CMD_INLINE},
95 {"sunion",-2,REDIS_CMD_INLINE},
96 {"sunionstore",-3,REDIS_CMD_INLINE},
97 {"sdiff",-2,REDIS_CMD_INLINE},
98 {"sdiffstore",-3,REDIS_CMD_INLINE},
99 {"smembers",2,REDIS_CMD_INLINE},
100 {"zadd",4,REDIS_CMD_BULK},
101 {"zincrby",4,REDIS_CMD_BULK},
102 {"zrem",3,REDIS_CMD_BULK},
103 {"zremrangebyscore",4,REDIS_CMD_INLINE},
104 {"zmerge",-3,REDIS_CMD_INLINE},
105 {"zmergeweighed",-4,REDIS_CMD_INLINE},
106 {"zrange",-4,REDIS_CMD_INLINE},
107 {"zrank",3,REDIS_CMD_BULK},
108 {"zrangebyscore",-4,REDIS_CMD_INLINE},
109 {"zcount",4,REDIS_CMD_INLINE},
110 {"zrevrange",-4,REDIS_CMD_INLINE},
111 {"zcard",2,REDIS_CMD_INLINE},
112 {"zscore",3,REDIS_CMD_BULK},
113 {"incrby",3,REDIS_CMD_INLINE},
114 {"decrby",3,REDIS_CMD_INLINE},
115 {"getset",3,REDIS_CMD_BULK},
116 {"randomkey",1,REDIS_CMD_INLINE},
117 {"select",2,REDIS_CMD_INLINE},
118 {"move",3,REDIS_CMD_INLINE},
119 {"rename",3,REDIS_CMD_INLINE},
120 {"renamenx",3,REDIS_CMD_INLINE},
121 {"keys",2,REDIS_CMD_INLINE},
122 {"dbsize",1,REDIS_CMD_INLINE},
123 {"ping",1,REDIS_CMD_INLINE},
124 {"echo",2,REDIS_CMD_BULK},
125 {"save",1,REDIS_CMD_INLINE},
126 {"bgsave",1,REDIS_CMD_INLINE},
127 {"rewriteaof",1,REDIS_CMD_INLINE},
128 {"bgrewriteaof",1,REDIS_CMD_INLINE},
129 {"shutdown",1,REDIS_CMD_INLINE},
130 {"lastsave",1,REDIS_CMD_INLINE},
131 {"type",2,REDIS_CMD_INLINE},
132 {"flushdb",1,REDIS_CMD_INLINE},
133 {"flushall",1,REDIS_CMD_INLINE},
134 {"sort",-2,REDIS_CMD_INLINE},
135 {"info",1,REDIS_CMD_INLINE},
136 {"mget",-2,REDIS_CMD_INLINE},
137 {"expire",3,REDIS_CMD_INLINE},
138 {"expireat",3,REDIS_CMD_INLINE},
139 {"ttl",2,REDIS_CMD_INLINE},
140 {"slaveof",3,REDIS_CMD_INLINE},
141 {"debug",-2,REDIS_CMD_INLINE},
142 {"mset",-3,REDIS_CMD_MULTIBULK},
143 {"msetnx",-3,REDIS_CMD_MULTIBULK},
144 {"monitor",1,REDIS_CMD_INLINE},
145 {"multi",1,REDIS_CMD_INLINE},
146 {"exec",1,REDIS_CMD_INLINE},
147 {"discard",1,REDIS_CMD_INLINE},
148 {"hset",4,REDIS_CMD_MULTIBULK},
149 {"hget",3,REDIS_CMD_BULK},
150 {"hdel",3,REDIS_CMD_BULK},
151 {"hlen",2,REDIS_CMD_INLINE},
152 {NULL,0,0}
153 };
154
155 static int cliReadReply(int fd);
156 static void usage();
157
158 static struct redisCommand *lookupCommand(char *name) {
159 int j = 0;
160 while(cmdTable[j].name != NULL) {
161 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
162 j++;
163 }
164 return NULL;
165 }
166
167 static int cliConnect(void) {
168 char err[ANET_ERR_LEN];
169 static int fd = ANET_ERR;
170
171 if (fd == ANET_ERR) {
172 fd = anetTcpConnect(err,config.hostip,config.hostport);
173 if (fd == ANET_ERR) {
174 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
175 return -1;
176 }
177 anetTcpNoDelay(NULL,fd);
178 }
179 return fd;
180 }
181
182 static sds cliReadLine(int fd) {
183 sds line = sdsempty();
184
185 while(1) {
186 char c;
187 ssize_t ret;
188
189 ret = read(fd,&c,1);
190 if (ret == -1) {
191 sdsfree(line);
192 return NULL;
193 } else if ((ret == 0) || (c == '\n')) {
194 break;
195 } else {
196 line = sdscatlen(line,&c,1);
197 }
198 }
199 return sdstrim(line,"\r\n");
200 }
201
202 static int cliReadSingleLineReply(int fd, int quiet) {
203 sds reply = cliReadLine(fd);
204
205 if (reply == NULL) return 1;
206 if (!quiet)
207 printf("%s\n", reply);
208 sdsfree(reply);
209 return 0;
210 }
211
212 static int cliReadBulkReply(int fd) {
213 sds replylen = cliReadLine(fd);
214 char *reply, crlf[2];
215 int bulklen;
216
217 if (replylen == NULL) return 1;
218 bulklen = atoi(replylen);
219 if (bulklen == -1) {
220 sdsfree(replylen);
221 printf("(nil)\n");
222 return 0;
223 }
224 reply = zmalloc(bulklen);
225 anetRead(fd,reply,bulklen);
226 anetRead(fd,crlf,2);
227 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
228 zfree(reply);
229 return 1;
230 }
231 if (isatty(fileno(stdout)) && reply[bulklen-1] != '\n')
232 printf("\n");
233 zfree(reply);
234 return 0;
235 }
236
237 static int cliReadMultiBulkReply(int fd) {
238 sds replylen = cliReadLine(fd);
239 int elements, c = 1;
240
241 if (replylen == NULL) return 1;
242 elements = atoi(replylen);
243 if (elements == -1) {
244 sdsfree(replylen);
245 printf("(nil)\n");
246 return 0;
247 }
248 if (elements == 0) {
249 printf("(empty list or set)\n");
250 }
251 while(elements--) {
252 printf("%d. ", c);
253 if (cliReadReply(fd)) return 1;
254 c++;
255 }
256 return 0;
257 }
258
259 static int cliReadReply(int fd) {
260 char type;
261
262 if (anetRead(fd,&type,1) <= 0) exit(1);
263 switch(type) {
264 case '-':
265 printf("(error) ");
266 cliReadSingleLineReply(fd,0);
267 return 1;
268 case '+':
269 return cliReadSingleLineReply(fd,0);
270 case ':':
271 printf("(integer) ");
272 return cliReadSingleLineReply(fd,0);
273 case '$':
274 return cliReadBulkReply(fd);
275 case '*':
276 return cliReadMultiBulkReply(fd);
277 default:
278 printf("protocol error, got '%c' as reply type byte\n", type);
279 return 1;
280 }
281 }
282
283 static int selectDb(int fd) {
284 int retval;
285 sds cmd;
286 char type;
287
288 if (config.dbnum == 0)
289 return 0;
290
291 cmd = sdsempty();
292 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
293 anetWrite(fd,cmd,sdslen(cmd));
294 anetRead(fd,&type,1);
295 if (type <= 0 || type != '+') return 1;
296 retval = cliReadSingleLineReply(fd,1);
297 if (retval) {
298 return retval;
299 }
300 return 0;
301 }
302
303 static int cliSendCommand(int argc, char **argv) {
304 struct redisCommand *rc = lookupCommand(argv[0]);
305 int fd, j, retval = 0;
306 int read_forever = 0;
307 sds cmd;
308
309 if (!rc) {
310 fprintf(stderr,"Unknown command '%s'\n",argv[0]);
311 return 1;
312 }
313
314 if ((rc->arity > 0 && argc != rc->arity) ||
315 (rc->arity < 0 && argc < -rc->arity)) {
316 fprintf(stderr,"Wrong number of arguments for '%s'\n",rc->name);
317 return 1;
318 }
319 if (!strcasecmp(rc->name,"monitor")) read_forever = 1;
320 if ((fd = cliConnect()) == -1) return 1;
321
322 /* Select db number */
323 retval = selectDb(fd);
324 if (retval) {
325 fprintf(stderr,"Error setting DB num\n");
326 return 1;
327 }
328
329 while(config.repeat--) {
330 /* Build the command to send */
331 cmd = sdsempty();
332 if (rc->flags & REDIS_CMD_MULTIBULK) {
333 cmd = sdscatprintf(cmd,"*%d\r\n",argc);
334 for (j = 0; j < argc; j++) {
335 cmd = sdscatprintf(cmd,"$%lu\r\n",
336 (unsigned long)sdslen(argv[j]));
337 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
338 cmd = sdscatlen(cmd,"\r\n",2);
339 }
340 } else {
341 for (j = 0; j < argc; j++) {
342 if (j != 0) cmd = sdscat(cmd," ");
343 if (j == argc-1 && rc->flags & REDIS_CMD_BULK) {
344 cmd = sdscatprintf(cmd,"%lu",
345 (unsigned long)sdslen(argv[j]));
346 } else {
347 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
348 }
349 }
350 cmd = sdscat(cmd,"\r\n");
351 if (rc->flags & REDIS_CMD_BULK) {
352 cmd = sdscatlen(cmd,argv[argc-1],sdslen(argv[argc-1]));
353 cmd = sdscatlen(cmd,"\r\n",2);
354 }
355 }
356 anetWrite(fd,cmd,sdslen(cmd));
357 sdsfree(cmd);
358
359 while (read_forever) {
360 cliReadSingleLineReply(fd,0);
361 }
362
363 retval = cliReadReply(fd);
364 if (retval) {
365 return retval;
366 }
367 }
368 return 0;
369 }
370
371 static int parseOptions(int argc, char **argv) {
372 int i;
373
374 for (i = 1; i < argc; i++) {
375 int lastarg = i==argc-1;
376
377 if (!strcmp(argv[i],"-h") && !lastarg) {
378 char *ip = zmalloc(32);
379 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
380 printf("Can't resolve %s\n", argv[i]);
381 exit(1);
382 }
383 config.hostip = ip;
384 i++;
385 } else if (!strcmp(argv[i],"-h") && lastarg) {
386 usage();
387 } else if (!strcmp(argv[i],"-p") && !lastarg) {
388 config.hostport = atoi(argv[i+1]);
389 i++;
390 } else if (!strcmp(argv[i],"-r") && !lastarg) {
391 config.repeat = strtoll(argv[i+1],NULL,10);
392 i++;
393 } else if (!strcmp(argv[i],"-n") && !lastarg) {
394 config.dbnum = atoi(argv[i+1]);
395 i++;
396 } else if (!strcmp(argv[i],"-i")) {
397 config.interactive = 1;
398 } else {
399 break;
400 }
401 }
402 return i;
403 }
404
405 static sds readArgFromStdin(void) {
406 char buf[1024];
407 sds arg = sdsempty();
408
409 while(1) {
410 int nread = read(fileno(stdin),buf,1024);
411
412 if (nread == 0) break;
413 else if (nread == -1) {
414 perror("Reading from standard input");
415 exit(1);
416 }
417 arg = sdscatlen(arg,buf,nread);
418 }
419 return arg;
420 }
421
422 static void usage() {
423 fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
424 fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-p port] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
425 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
426 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
427 fprintf(stderr, "example: redis-cli get my_passwd\n");
428 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
429 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
430 exit(1);
431 }
432
433 /* Turn the plain C strings into Sds strings */
434 static char **convertToSds(int count, char** args) {
435 int j;
436 char **sds = zmalloc(sizeof(char*)*count+1);
437
438 for(j = 0; j < count; j++)
439 sds[j] = sdsnew(args[j]);
440
441 return sds;
442 }
443
444 static char *prompt(char *line, int size) {
445 char *retval;
446
447 do {
448 printf(">> ");
449 retval = fgets(line, size, stdin);
450 } while (retval && *line == '\n');
451 line[strlen(line) - 1] = '\0';
452
453 return retval;
454 }
455
456 static void repl() {
457 int size = 4096, max = size >> 1, argc;
458 char buffer[size];
459 char *line = buffer;
460 char **ap, *args[max];
461
462 while (prompt(line, size)) {
463 argc = 0;
464
465 for (ap = args; (*ap = strsep(&line, " \t")) != NULL;) {
466 if (**ap != '\0') {
467 if (argc >= max) break;
468 if (strcasecmp(*ap,"quit") == 0 || strcasecmp(*ap,"exit") == 0)
469 exit(0);
470 ap++;
471 argc++;
472 }
473 }
474
475 config.repeat = 1;
476 cliSendCommand(argc, convertToSds(argc, args));
477 line = buffer;
478 }
479
480 exit(0);
481 }
482
483 int main(int argc, char **argv) {
484 int firstarg;
485 char **argvcopy;
486 struct redisCommand *rc;
487
488 config.hostip = "127.0.0.1";
489 config.hostport = 6379;
490 config.repeat = 1;
491 config.dbnum = 0;
492 config.interactive = 0;
493
494 firstarg = parseOptions(argc,argv);
495 argc -= firstarg;
496 argv += firstarg;
497
498 if (argc == 0 || config.interactive == 1) repl();
499
500 argvcopy = convertToSds(argc, argv);
501
502 /* Read the last argument from stdandard input if needed */
503 if ((rc = lookupCommand(argv[0])) != NULL) {
504 if (rc->arity > 0 && argc == rc->arity-1) {
505 sds lastarg = readArgFromStdin();
506 argvcopy[argc] = lastarg;
507 argc++;
508 }
509 }
510
511 return cliSendCommand(argc, argvcopy);
512 }