]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
don't open/close log file if log level is not matched
[redis.git] / src / redis-cli.c
CommitLineData
ed9b544e 1/* Redis CLI (command line interface)
2 *
12d090d2 3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 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
23d4709d 31#include "fmacros.h"
185cabda 32#include "version.h"
23d4709d 33
ed9b544e 34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37#include <unistd.h>
a88a2af6 38#include <ctype.h>
ed9b544e 39
40#include "anet.h"
41#include "sds.h"
42#include "adlist.h"
43#include "zmalloc.h"
cf87ebf2 44#include "linenoise.h"
ed9b544e 45
46#define REDIS_CMD_INLINE 1
47#define REDIS_CMD_BULK 2
e17e0b05 48#define REDIS_CMD_MULTIBULK 4
ed9b544e 49
50#define REDIS_NOTUSED(V) ((void) V)
51
52static struct config {
53 char *hostip;
54 int hostport;
5762b7f0 55 long repeat;
62e920df 56 int dbnum;
37dc9e5a 57 int argn_from_stdin;
6cf5882c 58 int interactive;
36e5db6d 59 int shutdown;
249c3a7d 60 int monitor_mode;
61 int pubsub_mode;
f40b035d 62 int raw_output;
288799e0 63 char *auth;
99628c1a 64 char *historyfile;
ed9b544e 65} config;
66
c937aa89 67static int cliReadReply(int fd);
a9158272 68static void usage();
c937aa89 69
ed9b544e 70static int cliConnect(void) {
71 char err[ANET_ERR_LEN];
6fa24622 72 static int fd = ANET_ERR;
ed9b544e 73
ed9b544e 74 if (fd == ANET_ERR) {
6fa24622
DJMM
75 fd = anetTcpConnect(err,config.hostip,config.hostport);
76 if (fd == ANET_ERR) {
77 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
78 return -1;
79 }
80 anetTcpNoDelay(NULL,fd);
ed9b544e 81 }
ed9b544e 82 return fd;
83}
84
85static sds cliReadLine(int fd) {
86 sds line = sdsempty();
87
88 while(1) {
89 char c;
b91f03a4 90 ssize_t ret;
ed9b544e 91
b91f03a4
LH
92 ret = read(fd,&c,1);
93 if (ret == -1) {
ed9b544e 94 sdsfree(line);
95 return NULL;
b91f03a4 96 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 97 break;
98 } else {
99 line = sdscatlen(line,&c,1);
100 }
101 }
102 return sdstrim(line,"\r\n");
103}
104
62e920df 105static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 106 sds reply = cliReadLine(fd);
107
108 if (reply == NULL) return 1;
62e920df 109 if (!quiet)
110 printf("%s\n", reply);
621d5c19 111 sdsfree(reply);
ed9b544e 112 return 0;
113}
114
21cdc9f0 115static void printStringRepr(char *s, int len) {
116 printf("\"");
117 while(len--) {
118 switch(*s) {
119 case '\\':
120 case '"':
121 printf("\\%c",*s);
122 break;
123 case '\n': printf("\\n"); break;
124 case '\r': printf("\\r"); break;
125 case '\t': printf("\\t"); break;
126 case '\a': printf("\\a"); break;
127 case '\b': printf("\\b"); break;
128 default:
129 if (isprint(*s))
130 printf("%c",*s);
131 else
132 printf("\\x%02x",(unsigned char)*s);
133 break;
134 }
135 s++;
136 }
137 printf("\"\n");
138}
139
c937aa89 140static int cliReadBulkReply(int fd) {
ed9b544e 141 sds replylen = cliReadLine(fd);
142 char *reply, crlf[2];
c937aa89 143 int bulklen;
ed9b544e 144
145 if (replylen == NULL) return 1;
ed9b544e 146 bulklen = atoi(replylen);
c937aa89 147 if (bulklen == -1) {
ed9b544e 148 sdsfree(replylen);
060f6be6 149 printf("(nil)\n");
ed9b544e 150 return 0;
151 }
ed9b544e 152 reply = zmalloc(bulklen);
153 anetRead(fd,reply,bulklen);
154 anetRead(fd,crlf,2);
f40b035d 155 if (config.raw_output || !isatty(fileno(stdout))) {
21cdc9f0 156 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
157 zfree(reply);
158 return 1;
159 }
21cdc9f0 160 } else {
161 /* If you are producing output for the standard output we want
162 * a more interesting output with quoted characters and so forth */
163 printStringRepr(reply,bulklen);
ed9b544e 164 }
ed9b544e 165 zfree(reply);
c937aa89 166 return 0;
ed9b544e 167}
168
169static int cliReadMultiBulkReply(int fd) {
170 sds replylen = cliReadLine(fd);
171 int elements, c = 1;
172
173 if (replylen == NULL) return 1;
c937aa89 174 elements = atoi(replylen);
175 if (elements == -1) {
ed9b544e 176 sdsfree(replylen);
177 printf("(nil)\n");
178 return 0;
179 }
c937aa89 180 if (elements == 0) {
181 printf("(empty list or set)\n");
182 }
ed9b544e 183 while(elements--) {
184 printf("%d. ", c);
c937aa89 185 if (cliReadReply(fd)) return 1;
ed9b544e 186 c++;
187 }
188 return 0;
189}
190
c937aa89 191static int cliReadReply(int fd) {
192 char type;
193
36e5db6d
BD
194 if (anetRead(fd,&type,1) <= 0) {
195 if (config.shutdown) return 0;
196 exit(1);
197 }
c937aa89 198 switch(type) {
199 case '-':
200 printf("(error) ");
62e920df 201 cliReadSingleLineReply(fd,0);
c937aa89 202 return 1;
203 case '+':
62e920df 204 return cliReadSingleLineReply(fd,0);
c937aa89 205 case ':':
443c6409 206 printf("(integer) ");
62e920df 207 return cliReadSingleLineReply(fd,0);
c937aa89 208 case '$':
209 return cliReadBulkReply(fd);
210 case '*':
211 return cliReadMultiBulkReply(fd);
212 default:
213 printf("protocol error, got '%c' as reply type byte\n", type);
214 return 1;
215 }
216}
217
6cf5882c 218static int selectDb(int fd) {
62e920df 219 int retval;
220 sds cmd;
221 char type;
222
223 if (config.dbnum == 0)
224 return 0;
225
226 cmd = sdsempty();
227 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
228 anetWrite(fd,cmd,sdslen(cmd));
229 anetRead(fd,&type,1);
230 if (type <= 0 || type != '+') return 1;
231 retval = cliReadSingleLineReply(fd,1);
232 if (retval) {
6cf5882c 233 return retval;
62e920df 234 }
235 return 0;
236}
237
aab055ae 238static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 239 char *command = argv[0];
ed9b544e 240 int fd, j, retval = 0;
5762b7f0 241 sds cmd;
ed9b544e 242
37dc9e5a
PN
243 config.raw_output = !strcasecmp(command,"info");
244 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
245 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
246 if (!strcasecmp(command,"subscribe") ||
247 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
ed9b544e 248 if ((fd = cliConnect()) == -1) return 1;
249
62e920df 250 /* Select db number */
251 retval = selectDb(fd);
252 if (retval) {
253 fprintf(stderr,"Error setting DB num\n");
254 return 1;
255 }
6cf5882c 256
a2f4f871
PN
257 /* Build the command to send */
258 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
259 for (j = 0; j < argc; j++) {
260 cmd = sdscatprintf(cmd,"$%lu\r\n",
261 (unsigned long)sdslen(argv[j]));
262 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
263 cmd = sdscatlen(cmd,"\r\n",2);
264 }
265
aab055ae 266 while(repeat--) {
5762b7f0 267 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 268 while (config.monitor_mode) {
621d5c19 269 cliReadSingleLineReply(fd,0);
270 }
271
249c3a7d 272 if (config.pubsub_mode) {
273 printf("Reading messages... (press Ctrl-c to quit)\n");
274 while (1) {
275 cliReadReply(fd);
276 printf("\n");
277 }
278 }
279
5762b7f0 280 retval = cliReadReply(fd);
281 if (retval) {
36e5db6d 282 return retval;
8165a5f2 283 }
ed9b544e 284 }
ed9b544e 285 return 0;
286}
287
288static int parseOptions(int argc, char **argv) {
289 int i;
290
291 for (i = 1; i < argc; i++) {
292 int lastarg = i==argc-1;
6cf5882c 293
ed9b544e 294 if (!strcmp(argv[i],"-h") && !lastarg) {
295 char *ip = zmalloc(32);
296 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
297 printf("Can't resolve %s\n", argv[i]);
298 exit(1);
299 }
300 config.hostip = ip;
301 i++;
a9158272 302 } else if (!strcmp(argv[i],"-h") && lastarg) {
303 usage();
ed9b544e 304 } else if (!strcmp(argv[i],"-p") && !lastarg) {
305 config.hostport = atoi(argv[i+1]);
306 i++;
5762b7f0 307 } else if (!strcmp(argv[i],"-r") && !lastarg) {
308 config.repeat = strtoll(argv[i+1],NULL,10);
309 i++;
62e920df 310 } else if (!strcmp(argv[i],"-n") && !lastarg) {
311 config.dbnum = atoi(argv[i+1]);
312 i++;
fdfdae0f 313 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 314 config.auth = argv[i+1];
fdfdae0f 315 i++;
6cf5882c
MMDJ
316 } else if (!strcmp(argv[i],"-i")) {
317 config.interactive = 1;
37dc9e5a
PN
318 } else if (!strcmp(argv[i],"-c")) {
319 config.argn_from_stdin = 1;
185cabda 320 } else if (!strcmp(argv[i],"-v")) {
321 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION);
322 exit(0);
ed9b544e 323 } else {
324 break;
325 }
326 }
327 return i;
328}
329
330static sds readArgFromStdin(void) {
331 char buf[1024];
332 sds arg = sdsempty();
333
334 while(1) {
335 int nread = read(fileno(stdin),buf,1024);
336
337 if (nread == 0) break;
338 else if (nread == -1) {
339 perror("Reading from standard input");
340 exit(1);
341 }
342 arg = sdscatlen(arg,buf,nread);
343 }
344 return arg;
345}
346
a9158272 347static void usage() {
185cabda 348 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
37dc9e5a 349 fprintf(stderr, "usage: echo \"argN\" | redis-cli -c [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
a9158272 350 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
351 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
352 fprintf(stderr, "example: redis-cli get my_passwd\n");
353 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 354 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 355 exit(1);
356}
357
6cf5882c
MMDJ
358/* Turn the plain C strings into Sds strings */
359static char **convertToSds(int count, char** args) {
360 int j;
37dc9e5a 361 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
362
363 for(j = 0; j < count; j++)
364 sds[j] = sdsnew(args[j]);
365
366 return sds;
367}
368
a88a2af6 369static char **splitArguments(char *line, int *argc) {
370 char *p = line;
371 char *current = NULL;
372 char **vector = NULL;
373
374 *argc = 0;
375 while(1) {
376 /* skip blanks */
377 while(*p && isspace(*p)) p++;
378 if (*p) {
379 /* get a token */
380 int inq=0; /* set to 1 if we are in "quotes" */
381 int done = 0;
382
383 if (current == NULL) current = sdsempty();
384 while(!done) {
385 if (inq) {
386 if (*p == '\\' && *(p+1)) {
387 char c;
388
389 p++;
390 switch(*p) {
391 case 'n': c = '\n'; break;
392 case 'r': c = '\r'; break;
393 case 't': c = '\t'; break;
394 case 'b': c = '\b'; break;
395 case 'a': c = '\a'; break;
396 default: c = *p; break;
397 }
398 current = sdscatlen(current,&c,1);
399 } else if (*p == '"') {
400 done = 1;
401 } else {
402 current = sdscatlen(current,p,1);
403 }
404 } else {
405 switch(*p) {
406 case ' ':
407 case '\n':
408 case '\r':
409 case '\t':
410 case '\0':
411 done=1;
412 break;
413 case '"':
414 inq=1;
415 break;
416 default:
417 current = sdscatlen(current,p,1);
418 break;
419 }
420 }
421 if (*p) p++;
422 }
423 /* add the token to the vector */
424 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
425 vector[*argc] = current;
426 (*argc)++;
427 current = NULL;
428 } else {
429 return vector;
430 }
431 }
432}
433
434#define LINE_BUFLEN 4096
6cf5882c 435static void repl() {
a88a2af6 436 int argc, j;
437 char *line, **argv;
6cf5882c 438
bc86d88e 439 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 440 if (line[0] != '\0') {
a88a2af6 441 argv = splitArguments(line,&argc);
442 linenoiseHistoryAdd(line);
99628c1a 443 if (config.historyfile) linenoiseHistorySave(config.historyfile);
a88a2af6 444 if (argc > 0) {
445 if (strcasecmp(argv[0],"quit") == 0 ||
446 strcasecmp(argv[0],"exit") == 0)
447 exit(0);
448 else
449 cliSendCommand(argc, argv, 1);
450 }
451 /* Free the argument vector */
452 for (j = 0; j < argc; j++)
453 sdsfree(argv[j]);
8ff6a48b 454 zfree(argv);
6cf5882c 455 }
a88a2af6 456 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 457 free(line);
6cf5882c 458 }
6cf5882c
MMDJ
459 exit(0);
460}
461
ed9b544e 462int main(int argc, char **argv) {
6cf5882c 463 int firstarg;
ed9b544e 464 char **argvcopy;
465
466 config.hostip = "127.0.0.1";
467 config.hostport = 6379;
5762b7f0 468 config.repeat = 1;
62e920df 469 config.dbnum = 0;
37dc9e5a 470 config.argn_from_stdin = 0;
36e5db6d 471 config.shutdown = 0;
6cf5882c 472 config.interactive = 0;
249c3a7d 473 config.monitor_mode = 0;
474 config.pubsub_mode = 0;
f40b035d 475 config.raw_output = 0;
288799e0 476 config.auth = NULL;
99628c1a 477 config.historyfile = NULL;
478
479 if (getenv("HOME") != NULL) {
480 config.historyfile = malloc(256);
481 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
482 linenoiseHistoryLoad(config.historyfile);
483 }
ed9b544e 484
485 firstarg = parseOptions(argc,argv);
486 argc -= firstarg;
487 argv += firstarg;
ed9b544e 488
aab055ae
MMDJ
489 if (config.auth != NULL) {
490 char *authargv[2];
491
492 authargv[0] = "AUTH";
493 authargv[1] = config.auth;
494 cliSendCommand(2, convertToSds(2, authargv), 1);
495 }
496
d239ec59 497 if (argc == 0 || config.interactive == 1) repl();
ed9b544e 498
37dc9e5a
PN
499 argvcopy = convertToSds(argc+1, argv);
500 if (config.argn_from_stdin) {
6cf5882c
MMDJ
501 sds lastarg = readArgFromStdin();
502 argvcopy[argc] = lastarg;
503 argc++;
2073a849 504 }
aab055ae 505 return cliSendCommand(argc, argvcopy, config.repeat);
ed9b544e 506}