]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Import linenoise as dependency for redis-cli
[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>
c0b3d423 39#include <errno.h>
b4b62c34 40#include <sys/stat.h>
3ce014c7 41#include <sys/time.h>
ed9b544e 42
7fc4ce13 43#include "hiredis.h"
ed9b544e 44#include "sds.h"
ed9b544e 45#include "zmalloc.h"
cf87ebf2 46#include "linenoise.h"
ed9b544e 47
ed9b544e 48#define REDIS_NOTUSED(V) ((void) V)
49
7fc4ce13 50static redisContext *context;
ed9b544e 51static struct config {
52 char *hostip;
53 int hostport;
7e91f971 54 char *hostsocket;
5762b7f0 55 long repeat;
62e920df 56 int dbnum;
5d15b520 57 int interactive;
36e5db6d 58 int shutdown;
249c3a7d 59 int monitor_mode;
60 int pubsub_mode;
f2dd4769 61 int raw_output; /* output mode per command */
123a10f7 62 int tty; /* flag for default output format */
bc63407b 63 int stdinarg; /* get last arg from stdin. (-x option) */
3a51bff0 64 char mb_sep;
288799e0 65 char *auth;
99628c1a 66 char *historyfile;
ed9b544e 67} config;
68
a9158272 69static void usage();
c937aa89 70
3ce014c7 71/*------------------------------------------------------------------------------
72 * Utility functions
73 *--------------------------------------------------------------------------- */
74
75static long long mstime(void) {
76 struct timeval tv;
77 long long mst;
78
79 gettimeofday(&tv, NULL);
80 mst = ((long)tv.tv_sec)*1000;
81 mst += tv.tv_usec/1000;
82 return mst;
83}
84
3ce014c7 85/*------------------------------------------------------------------------------
86 * Networking / parsing
87 *--------------------------------------------------------------------------- */
88
7fc4ce13
PN
89/* Send AUTH command to the server */
90static int cliAuth() {
91 redisReply *reply;
92 if (config.auth == NULL) return REDIS_OK;
93
94 reply = redisCommand(context,"AUTH %s",config.auth);
95 if (reply != NULL) {
96 freeReplyObject(reply);
97 return REDIS_OK;
98 }
99 return REDIS_ERR;
100}
101
102/* Send SELECT dbnum to the server */
103static int cliSelect() {
104 redisReply *reply;
105 char dbnum[16];
106 if (config.dbnum == 0) return REDIS_OK;
107
108 snprintf(dbnum,sizeof(dbnum),"%d",config.dbnum);
109 reply = redisCommand(context,"SELECT %s",dbnum);
110 if (reply != NULL) {
111 freeReplyObject(reply);
112 return REDIS_OK;
113 }
114 return REDIS_ERR;
115}
116
c0b3d423 117/* Connect to the client. If force is not zero the connection is performed
118 * even if there is already a connected socket. */
119static int cliConnect(int force) {
7fc4ce13
PN
120 if (context == NULL || force) {
121 if (context != NULL)
122 redisFree(context);
ed9b544e 123
7e91f971 124 if (config.hostsocket == NULL) {
7fc4ce13 125 context = redisConnect(config.hostip,config.hostport);
7e91f971 126 } else {
7fc4ce13 127 context = redisConnectUnix(config.hostsocket);
7e91f971 128 }
7fc4ce13
PN
129
130 if (context->err) {
7e91f971
PN
131 fprintf(stderr,"Could not connect to Redis at ");
132 if (config.hostsocket == NULL)
7fc4ce13 133 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
7e91f971 134 else
7fc4ce13
PN
135 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
136 redisFree(context);
137 context = NULL;
138 return REDIS_ERR;
6fa24622 139 }
ed9b544e 140
7fc4ce13
PN
141 /* Do AUTH and select the right DB. */
142 if (cliAuth() != REDIS_OK)
143 return REDIS_ERR;
144 if (cliSelect() != REDIS_OK)
145 return REDIS_ERR;
ed9b544e 146 }
7fc4ce13 147 return REDIS_OK;
ed9b544e 148}
149
7fc4ce13
PN
150static void cliPrintContextErrorAndExit() {
151 if (context == NULL) return;
152 fprintf(stderr,"Error: %s\n",context->errstr);
153 exit(1);
ed9b544e 154}
155
7fc4ce13
PN
156static sds cliFormatReply(redisReply *r, char *prefix) {
157 sds out = sdsempty();
158 switch (r->type) {
159 case REDIS_REPLY_ERROR:
7fc4ce13
PN
160 if (config.tty) out = sdscat(out,"(error) ");
161 out = sdscatprintf(out,"%s\n", r->str);
162 break;
163 case REDIS_REPLY_STATUS:
7fc4ce13
PN
164 out = sdscat(out,r->str);
165 out = sdscat(out,"\n");
166 break;
167 case REDIS_REPLY_INTEGER:
7fc4ce13
PN
168 if (config.tty) out = sdscat(out,"(integer) ");
169 out = sdscatprintf(out,"%lld\n",r->integer);
170 break;
171 case REDIS_REPLY_STRING:
7fc4ce13
PN
172 if (config.raw_output || !config.tty) {
173 out = sdscatlen(out,r->str,r->len);
174 } else {
175 /* If you are producing output for the standard output we want
176 * a more interesting output with quoted characters and so forth */
177 out = sdscatrepr(out,r->str,r->len);
178 out = sdscat(out,"\n");
21cdc9f0 179 }
7fc4ce13
PN
180 break;
181 case REDIS_REPLY_NIL:
7fc4ce13
PN
182 out = sdscat(out,"(nil)\n");
183 break;
184 case REDIS_REPLY_ARRAY:
185 if (r->elements == 0) {
7fc4ce13 186 out = sdscat(out,"(empty list or set)\n");
c0b3d423 187 } else {
cfcd5d6d
PN
188 unsigned int i, idxlen = 0;
189 char _prefixlen[16];
190 char _prefixfmt[16];
191 sds _prefix;
7fc4ce13
PN
192 sds tmp;
193
cfcd5d6d
PN
194 /* Calculate chars needed to represent the largest index */
195 i = r->elements;
196 do {
197 idxlen++;
198 i /= 10;
199 } while(i);
200
201 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
202 memset(_prefixlen,' ',idxlen+2);
203 _prefixlen[idxlen+2] = '\0';
204 _prefix = sdscat(sdsnew(prefix),_prefixlen);
205
206 /* Setup prefix format for every entry */
207 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
208
7fc4ce13 209 for (i = 0; i < r->elements; i++) {
cfcd5d6d
PN
210 /* Don't use the prefix for the first element, as the parent
211 * caller already prepended the index number. */
212 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
213
214 /* Format the multi bulk entry */
215 tmp = cliFormatReply(r->element[i],_prefix);
7fc4ce13
PN
216 out = sdscatlen(out,tmp,sdslen(tmp));
217 sdsfree(tmp);
218 }
cfcd5d6d 219 sdsfree(_prefix);
c0b3d423 220 }
7fc4ce13 221 break;
c937aa89 222 default:
7fc4ce13
PN
223 fprintf(stderr,"Unknown reply type: %d\n", r->type);
224 exit(1);
c937aa89 225 }
7fc4ce13 226 return out;
c937aa89 227}
228
7fc4ce13
PN
229static int cliReadReply() {
230 redisReply *reply;
231 sds out;
232
233 if (redisGetReply(context,(void**)&reply) != REDIS_OK) {
234 if (config.shutdown)
235 return REDIS_OK;
236 if (config.interactive) {
237 /* Filter cases where we should reconnect */
238 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
239 return REDIS_ERR;
240 if (context->err == REDIS_ERR_EOF)
241 return REDIS_ERR;
242 }
243 cliPrintContextErrorAndExit();
244 return REDIS_ERR; /* avoid compiler warning */
62e920df 245 }
7fc4ce13
PN
246
247 out = cliFormatReply(reply,"");
248 freeReplyObject(reply);
249 fwrite(out,sdslen(out),1,stdout);
250 sdsfree(out);
251 return REDIS_OK;
62e920df 252}
253
8079656a 254static void showInteractiveHelp(void) {
255 printf(
256 "\n"
257 "Welcome to redis-cli " REDIS_VERSION "!\n"
258 "Just type any valid Redis command to see a pretty printed output.\n"
259 "\n"
260 "It is possible to quote strings, like in:\n"
261 " set \"my key\" \"some string \\xff\\n\"\n"
262 "\n"
263 "You can find a list of valid Redis commands at\n"
264 " http://code.google.com/p/redis/wiki/CommandReference\n"
265 "\n"
266 "Note: redis-cli supports line editing, use up/down arrows for history."
267 "\n\n");
268}
269
aab055ae 270static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 271 char *command = argv[0];
7fc4ce13
PN
272 size_t *argvlen;
273 int j;
ed9b544e 274
37dc9e5a 275 config.raw_output = !strcasecmp(command,"info");
8079656a 276 if (!strcasecmp(command,"help")) {
277 showInteractiveHelp();
7fc4ce13 278 return REDIS_OK;
8079656a 279 }
37dc9e5a
PN
280 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
281 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
282 if (!strcasecmp(command,"subscribe") ||
283 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
ed9b544e 284
7fc4ce13
PN
285 /* Setup argument length */
286 argvlen = malloc(argc*sizeof(size_t));
287 for (j = 0; j < argc; j++)
288 argvlen[j] = sdslen(argv[j]);
a2f4f871 289
aab055ae 290 while(repeat--) {
7fc4ce13 291 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
249c3a7d 292 while (config.monitor_mode) {
7fc4ce13 293 if (cliReadReply() != REDIS_OK) exit(1);
621d5c19 294 }
295
249c3a7d 296 if (config.pubsub_mode) {
7fc4ce13 297 printf("Reading messages... (press Ctrl-C to quit)\n");
249c3a7d 298 while (1) {
7fc4ce13 299 if (cliReadReply() != REDIS_OK) exit(1);
249c3a7d 300 }
301 }
302
7fc4ce13
PN
303 if (cliReadReply() != REDIS_OK)
304 return REDIS_ERR;
ed9b544e 305 }
7fc4ce13 306 return REDIS_OK;
ed9b544e 307}
308
3ce014c7 309/*------------------------------------------------------------------------------
310 * User interface
311 *--------------------------------------------------------------------------- */
312
ed9b544e 313static int parseOptions(int argc, char **argv) {
314 int i;
315
316 for (i = 1; i < argc; i++) {
317 int lastarg = i==argc-1;
6cf5882c 318
ed9b544e 319 if (!strcmp(argv[i],"-h") && !lastarg) {
7fc4ce13 320 config.hostip = argv[i+1];
ed9b544e 321 i++;
a9158272 322 } else if (!strcmp(argv[i],"-h") && lastarg) {
323 usage();
bc63407b 324 } else if (!strcmp(argv[i],"-x")) {
325 config.stdinarg = 1;
ed9b544e 326 } else if (!strcmp(argv[i],"-p") && !lastarg) {
327 config.hostport = atoi(argv[i+1]);
328 i++;
7e91f971
PN
329 } else if (!strcmp(argv[i],"-s") && !lastarg) {
330 config.hostsocket = argv[i+1];
331 i++;
5762b7f0 332 } else if (!strcmp(argv[i],"-r") && !lastarg) {
333 config.repeat = strtoll(argv[i+1],NULL,10);
334 i++;
62e920df 335 } else if (!strcmp(argv[i],"-n") && !lastarg) {
336 config.dbnum = atoi(argv[i+1]);
337 i++;
fdfdae0f 338 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 339 config.auth = argv[i+1];
fdfdae0f 340 i++;
6cf5882c 341 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
342 fprintf(stderr,
343"Starting interactive mode using -i is deprecated. Interactive mode is started\n"
344"by default when redis-cli is executed without a command to execute.\n"
345 );
37dc9e5a 346 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
347 fprintf(stderr,
348"Reading last argument from standard input using -c is deprecated.\n"
349"When standard input is connected to a pipe or regular file, it is\n"
350"automatically used as last argument.\n"
351 );
185cabda 352 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 353 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 354 exit(0);
ed9b544e 355 } else {
356 break;
357 }
358 }
359 return i;
360}
361
362static sds readArgFromStdin(void) {
363 char buf[1024];
364 sds arg = sdsempty();
365
366 while(1) {
367 int nread = read(fileno(stdin),buf,1024);
368
369 if (nread == 0) break;
370 else if (nread == -1) {
371 perror("Reading from standard input");
372 exit(1);
373 }
374 arg = sdscatlen(arg,buf,nread);
375 }
376 return arg;
377}
378
a9158272 379static void usage() {
7e91f971 380 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-s /path/to/socket] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
bc63407b 381 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
382 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
a9158272 383 fprintf(stderr, "example: redis-cli get my_passwd\n");
384 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 385 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 386 exit(1);
387}
388
6cf5882c
MMDJ
389/* Turn the plain C strings into Sds strings */
390static char **convertToSds(int count, char** args) {
391 int j;
37dc9e5a 392 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
393
394 for(j = 0; j < count; j++)
395 sds[j] = sdsnew(args[j]);
396
397 return sds;
398}
399
a88a2af6 400#define LINE_BUFLEN 4096
6cf5882c 401static void repl() {
a88a2af6 402 int argc, j;
cbce5171 403 char *line;
404 sds *argv;
6cf5882c 405
5d15b520 406 config.interactive = 1;
bc86d88e 407 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 408 if (line[0] != '\0') {
cbce5171 409 argv = sdssplitargs(line,&argc);
a88a2af6 410 linenoiseHistoryAdd(line);
99628c1a 411 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
412 if (argv == NULL) {
413 printf("Invalid argument(s)\n");
414 continue;
415 } else if (argc > 0) {
a88a2af6 416 if (strcasecmp(argv[0],"quit") == 0 ||
417 strcasecmp(argv[0],"exit") == 0)
c0b3d423 418 {
419 exit(0);
420 } else {
3ce014c7 421 long long start_time = mstime(), elapsed;
c0b3d423 422
7fc4ce13
PN
423 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
424 printf("Reconnecting... ");
425 fflush(stdout);
426 if (cliConnect(1) != REDIS_OK) exit(1);
427 printf("OK\n");
428
429 /* If we still cannot send the command,
430 * print error and abort. */
431 if (cliSendCommand(argc,argv,1) != REDIS_OK)
432 cliPrintContextErrorAndExit();
c0b3d423 433 }
3ce014c7 434 elapsed = mstime()-start_time;
339b9dc2
PN
435 if (elapsed >= 500) {
436 printf("(%.2fs)\n",(double)elapsed/1000);
437 }
c0b3d423 438 }
a88a2af6 439 }
440 /* Free the argument vector */
441 for (j = 0; j < argc; j++)
442 sdsfree(argv[j]);
8ff6a48b 443 zfree(argv);
6cf5882c 444 }
a88a2af6 445 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 446 free(line);
6cf5882c 447 }
6cf5882c
MMDJ
448 exit(0);
449}
450
b4b62c34
PN
451static int noninteractive(int argc, char **argv) {
452 int retval = 0;
bc63407b 453 if (config.stdinarg) {
b4b62c34
PN
454 argv = zrealloc(argv, (argc+1)*sizeof(char*));
455 argv[argc] = readArgFromStdin();
456 retval = cliSendCommand(argc+1, argv, config.repeat);
457 } else {
458 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
459 retval = cliSendCommand(argc, argv, config.repeat);
460 }
461 return retval;
462}
463
ed9b544e 464int main(int argc, char **argv) {
6cf5882c 465 int firstarg;
ed9b544e 466
467 config.hostip = "127.0.0.1";
468 config.hostport = 6379;
7e91f971 469 config.hostsocket = NULL;
5762b7f0 470 config.repeat = 1;
62e920df 471 config.dbnum = 0;
5d15b520 472 config.interactive = 0;
36e5db6d 473 config.shutdown = 0;
249c3a7d 474 config.monitor_mode = 0;
475 config.pubsub_mode = 0;
f40b035d 476 config.raw_output = 0;
bc63407b 477 config.stdinarg = 0;
288799e0 478 config.auth = NULL;
99628c1a 479 config.historyfile = NULL;
cf0c6b78 480 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 481 config.mb_sep = '\n';
99628c1a 482
483 if (getenv("HOME") != NULL) {
484 config.historyfile = malloc(256);
485 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
486 linenoiseHistoryLoad(config.historyfile);
487 }
ed9b544e 488
489 firstarg = parseOptions(argc,argv);
490 argc -= firstarg;
491 argv += firstarg;
ed9b544e 492
7fc4ce13
PN
493 /* Try to connect */
494 if (cliConnect(0) != REDIS_OK) exit(1);
aab055ae 495
abb731e5
PN
496 /* Start interactive mode when no command is provided */
497 if (argc == 0) repl();
b4b62c34
PN
498 /* Otherwise, we have some arguments to execute */
499 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 500}