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