config.c 81.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* Configuration file parsing and CONFIG GET/SET commands implementation.
 *
 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

31 32 33 34
#ifdef _WIN32
#include "win32_Interop/win32_types.h"
#endif

35
#include "redis.h"
H
Henry Rawas 已提交
36 37 38
#ifdef _WIN32
#include <direct.h>
#endif
39

40 41 42
#include <fcntl.h>
#include <sys/stat.h>

43
#ifndef _WIN32
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
static struct {
    const char     *name;
    const int       value;
} validSyslogFacilities[] = {
    {"user",    LOG_USER},
    {"local0",  LOG_LOCAL0},
    {"local1",  LOG_LOCAL1},
    {"local2",  LOG_LOCAL2},
    {"local3",  LOG_LOCAL3},
    {"local4",  LOG_LOCAL4},
    {"local5",  LOG_LOCAL5},
    {"local6",  LOG_LOCAL6},
    {"local7",  LOG_LOCAL7},
    {NULL, 0}
};
59
#endif
60

A
antirez 已提交
61
clientBufferLimitsConfig clientBufferLimitsDefaults[REDIS_CLIENT_TYPE_COUNT] = {
62 63 64 65 66
    {0, 0, 0}, /* normal */
    {1024*1024*256, 1024*1024*64, 60}, /* slave */
    {1024*1024*32, 1024*1024*8, 60}  /* pubsub */
};

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/*-----------------------------------------------------------------------------
 * Config file parsing
 *----------------------------------------------------------------------------*/

int yesnotoi(char *s) {
    if (!strcasecmp(s,"yes")) return 1;
    else if (!strcasecmp(s,"no")) return 0;
    else return -1;
}

void appendServerSaveParams(time_t seconds, int changes) {
    server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
    server.saveparams[server.saveparamslen].seconds = seconds;
    server.saveparams[server.saveparamslen].changes = changes;
    server.saveparamslen++;
}

84
void resetServerSaveParams(void) {
85 86 87 88 89
    zfree(server.saveparams);
    server.saveparams = NULL;
    server.saveparamslen = 0;
}

90 91 92 93
void loadServerConfigFromString(char *config) {
    char *err = NULL;
    int linenum = 0, totlines, i;
    sds *lines;
94

H
Henry Rawas 已提交
95
    lines = sdssplitlen(config,(int)strlen(config),"\n",1,&totlines);
96

97
    for (i = 0; i < totlines; i++) {
98
        sds *argv;
99
        int argc;
100

101 102
        linenum = i+1;
        lines[i] = sdstrim(lines[i]," \t\r\n");
103

104
        /* Skip comments and blank lines */
105
        if (lines[i][0] == '#' || lines[i][0] == '\0') continue;
106 107

        /* Split into arguments */
108
        argv = sdssplitargs(lines[i],&argc);
C
charsyam 已提交
109
        if (argv == NULL) {
110
            err = "Unbalanced quotes in configuration line";
C
charsyam 已提交
111 112
            goto loaderr;
        }
113 114 115 116

        /* Skip this line if the resulting command vector is empty. */
        if (argc == 0) {
            sdsfreesplitres(argv,argc);
117
            continue;
118
        }
119 120 121 122 123 124 125 126
        sdstolower(argv[0]);

        /* Execute config directives */
        if (!strcasecmp(argv[0],"timeout") && argc == 2) {
            server.maxidletime = atoi(argv[1]);
            if (server.maxidletime < 0) {
                err = "Invalid timeout value"; goto loaderr;
            }
127 128 129 130 131
        } else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) {
            server.tcpkeepalive = atoi(argv[1]);
            if (server.tcpkeepalive < 0) {
                err = "Invalid tcp-keepalive value"; goto loaderr;
            }
132 133
        } else if (!strcasecmp(argv[0],"port") && argc == 2) {
            server.port = atoi(argv[1]);
134
            if (server.port < 0 || server.port > 65535) {
135 136
                err = "Invalid port"; goto loaderr;
            }
137 138 139
        } else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) {
            server.tcp_backlog = atoi(argv[1]);
            if (server.tcp_backlog < 0) {
140 141
                err = "Invalid backlog value"; goto loaderr;
            }
A
antirez 已提交
142 143 144 145 146 147 148 149 150
        } else if (!strcasecmp(argv[0],"bind") && argc >= 2) {
            int j, addresses = argc-1;

            if (addresses > REDIS_BINDADDR_MAX) {
                err = "Too many bind addresses specified"; goto loaderr;
            }
            for (j = 0; j < addresses; j++)
                server.bindaddr[j] = zstrdup(argv[j+1]);
            server.bindaddr_count = addresses;
151 152
        } else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) {
            server.unixsocket = zstrdup(argv[1]);
153
        } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) {
154
            errno = 0;
155 156 157 158
            server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8);
            if (errno || server.unixsocketperm > 0777) {
                err = "Invalid socket file permissions"; goto loaderr;
            }
159 160 161 162 163 164 165 166 167 168
        } else if (!strcasecmp(argv[0],"save")) {
            if (argc == 3) {
                int seconds = atoi(argv[1]);
                int changes = atoi(argv[2]);
                if (seconds < 1 || changes < 0) {
                    err = "Invalid save parameters"; goto loaderr;
                }
                appendServerSaveParams(seconds,changes);
            } else if (argc == 2 && !strcasecmp(argv[1],"")) {
                resetServerSaveParams();
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
            }
        } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
            if (chdir(argv[1]) == -1) {
                redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
                    argv[1], strerror(errno));
                exit(1);
            }
        } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
            if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
            else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
            else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
            else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
            else {
                err = "Invalid log level. Must be one of debug, notice, warning";
                goto loaderr;
            }
185 186 187
#ifdef _WIN32
            setLogVerbosityLevel(server.verbosity);
#endif
188 189 190
        } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
            FILE *logfp;

191
            zfree(server.logfile);
192
#ifdef _WIN32
193 194 195
            int length = (int)sdslen(argv[1]);
            if ((argv[1][0] == '\''  &&  argv[1][length-1] == '\'')  ||
                (argv[1][0] == '\"'  &&  argv[1][length-1] == '\"')) {
196
                if (length == 2) {
197
                    server.logfile = zstrdup("\0");
198 199 200 201
                } else {
                    size_t l = length - 2 + 1;
                    char *p = zmalloc(l);
                    memcpy(p, argv[1]+1, l);
202
                    server.logfile = p;
203 204 205 206 207
                }
            } else {
                server.logfile = zstrdup(argv[1]);
            }
#else
208
            server.logfile = zstrdup(argv[1]);
209
#endif
210
            if (server.logfile[0] != '\0') {
211 212 213 214 215 216 217
                /* Test if we are able to open the file. The server will not
                 * be able to abort just for this problem later... */
                logfp = fopen(server.logfile,"a");
                if (logfp == NULL) {
                    err = sdscatprintf(sdsempty(),
                        "Can't open the log file: %s", strerror(errno));
                    goto loaderr;
218 219
                } else {
#ifdef _WIN32
220
                    setLogFile( server.logfile );
221
#endif
222
                }
223

224 225
                fclose(logfp);
            }
J
Jonah H. Harris 已提交
226 227 228 229
        } else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) {
            if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
230 231 232
#ifdef _WIN32
            setSyslogEnabled(server.syslog_enabled);
#endif
J
Jonah H. Harris 已提交
233 234 235
        } else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) {
            if (server.syslog_ident) zfree(server.syslog_ident);
            server.syslog_ident = zstrdup(argv[1]);
H
Henry Rawas 已提交
236
#ifdef _WIN32
237 238 239 240 241
            setSyslogIdent(server.syslog_ident);
#endif
        } else if (!strcasecmp(argv[0], "syslog-facility") && argc == 2) {
#ifdef _WIN32
            // Skip error - just ignore syslog-facility
H
Henry Rawas 已提交
242
#else
J
Jonah H. Harris 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255
            int i;

            for (i = 0; validSyslogFacilities[i].name; i++) {
                if (!strcasecmp(validSyslogFacilities[i].name, argv[1])) {
                    server.syslog_facility = validSyslogFacilities[i].value;
                    break;
                }
            }

            if (!validSyslogFacilities[i].name) {
                err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7";
                goto loaderr;
            }
H
Henry Rawas 已提交
256
#endif
257 258 259 260 261 262
        } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
            server.dbnum = atoi(argv[1]);
            if (server.dbnum < 1) {
                err = "Invalid number of databases"; goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"include") && argc == 2) {
263
            loadServerConfig(argv[1],NULL);
264 265
        } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
            server.maxclients = atoi(argv[1]);
266 267 268
            if (server.maxclients < 1) {
                err = "Invalid max clients limit"; goto loaderr;
            }
269 270
        } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
            server.maxmemory = memtoll(argv[1],NULL);
271 272 273 274 275 276 277 278 279 280 281
        } else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) {
            if (!strcasecmp(argv[1],"volatile-lru")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
            } else if (!strcasecmp(argv[1],"volatile-random")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM;
            } else if (!strcasecmp(argv[1],"volatile-ttl")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL;
            } else if (!strcasecmp(argv[1],"allkeys-lru")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU;
            } else if (!strcasecmp(argv[1],"allkeys-random")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM;
282 283
            } else if (!strcasecmp(argv[1],"noeviction")) {
                server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
284 285 286 287
            } else {
                err = "Invalid maxmemory policy";
                goto loaderr;
            }
288 289 290 291 292 293
        } else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) {
            server.maxmemory_samples = atoi(argv[1]);
            if (server.maxmemory_samples <= 0) {
                err = "maxmemory-samples must be 1 or greater";
                goto loaderr;
            }
294 295 296
        } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
            server.masterhost = sdsnew(argv[1]);
            server.masterport = atoi(argv[2]);
A
antirez 已提交
297
            server.repl_state = REDIS_REPL_CONNECT;
A
7c6da73  
antirez 已提交
298 299 300 301 302 303 304 305 306 307 308 309
        } else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) {
            server.repl_ping_slave_period = atoi(argv[1]);
            if (server.repl_ping_slave_period <= 0) {
                err = "repl-ping-slave-period must be 1 or greater";
                goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) {
            server.repl_timeout = atoi(argv[1]);
            if (server.repl_timeout <= 0) {
                err = "repl-timeout must be 1 or greater";
                goto loaderr;
            }
310 311 312
        } else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) {
            if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
313
            }
314 315 316 317
        } else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) {
            if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
A
antirez 已提交
318 319 320 321 322 323
        } else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) {
            server.repl_diskless_sync_delay = atoi(argv[1]);
            if (server.repl_diskless_sync_delay < 0) {
                err = "repl-diskless-sync-delay can't be negative";
                goto loaderr;
            }
324
        } else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) {
325
            long long size = memtoll(argv[1],NULL);
326 327 328 329 330 331 332 333 334 335
            if (size <= 0) {
                err = "repl-backlog-size must be 1 or greater.";
                goto loaderr;
            }
            resizeReplicationBacklog(size);
        } else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) {
            server.repl_backlog_time_limit = atoi(argv[1]);
            if (server.repl_backlog_time_limit < 0) {
                err = "repl-backlog-ttl can't be negative ";
                goto loaderr;
336
            }
337
        } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
338
            server.masterauth = zstrdup(argv[1]);
339 340 341 342
        } else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) {
            if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
343 344 345 346
        } else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) {
            if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
347
        } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
A
antirez 已提交
348
            if ((server.rdb_compression = yesnotoi(argv[1])) == -1) {
349 350
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
351 352 353 354
        } else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) {
            if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
355 356 357 358 359 360 361 362
        } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
            if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
            if ((server.daemonize = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
363 364 365 366
        } else if (!strcasecmp(argv[0],"hz") && argc == 2) {
            server.hz = atoi(argv[1]);
            if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ;
            if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ;
367
        } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
368 369 370
            int yes;

            if ((yes = yesnotoi(argv[1])) == -1) {
371 372
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
373
            server.aof_state = yes ? REDIS_AOF_ON : REDIS_AOF_OFF;
374
        } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
375 376 377 378
            if (!pathIsBaseName(argv[1])) {
                err = "appendfilename can't be a path, just a filename";
                goto loaderr;
            }
379 380
            zfree(server.aof_filename);
            server.aof_filename = zstrdup(argv[1]);
381 382
        } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
                   && argc == 2) {
383
            if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) {
384 385 386 387
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
            if (!strcasecmp(argv[1],"no")) {
388
                server.aof_fsync = AOF_FSYNC_NO;
389
            } else if (!strcasecmp(argv[1],"always")) {
390
                server.aof_fsync = AOF_FSYNC_ALWAYS;
391
            } else if (!strcasecmp(argv[1],"everysec")) {
392
                server.aof_fsync = AOF_FSYNC_EVERYSEC;
393 394 395 396
            } else {
                err = "argument must be 'no', 'always' or 'everysec'";
                goto loaderr;
            }
397 398 399
        } else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") &&
                   argc == 2)
        {
400 401
            server.aof_rewrite_perc = atoi(argv[1]);
            if (server.aof_rewrite_perc < 0) {
402 403 404 405 406 407
                err = "Invalid negative percentage for AOF auto rewrite";
                goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") &&
                   argc == 2)
        {
408
            server.aof_rewrite_min_size = memtoll(argv[1],NULL);
409 410 411
        } else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") &&
                   argc == 2)
        {
412 413 414 415 416 417
            if ((server.aof_rewrite_incremental_fsync =
                 yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) {
            if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) {
418 419
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
420
        } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
421 422 423 424
            if (strlen(argv[1]) > REDIS_AUTHPASS_MAX_LEN) {
                err = "Password is longer than REDIS_AUTHPASS_MAX_LEN";
                goto loaderr;
            }
425 426 427 428 429
            server.requirepass = zstrdup(argv[1]);
        } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
            zfree(server.pidfile);
            server.pidfile = zstrdup(argv[1]);
        } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
430 431 432 433
            if (!pathIsBaseName(argv[1])) {
                err = "dbfilename can't be a path, just a filename";
                goto loaderr;
            }
A
antirez 已提交
434 435
            zfree(server.rdb_filename);
            server.rdb_filename = zstrdup(argv[1]);
436 437 438 439
        } else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) {
            server.hash_max_ziplist_entries = memtoll(argv[1], NULL);
        } else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) {
            server.hash_max_ziplist_value = memtoll(argv[1], NULL);
440 441
        } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
            server.list_max_ziplist_entries = memtoll(argv[1], NULL);
442
        } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) {
443
            server.list_max_ziplist_value = memtoll(argv[1], NULL);
444
        } else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) {
445
            server.set_max_intset_entries = memtoll(argv[1], NULL);
446 447 448 449
        } else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) {
            server.zset_max_ziplist_entries = memtoll(argv[1], NULL);
        } else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) {
            server.zset_max_ziplist_value = memtoll(argv[1], NULL);
450 451
        } else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) {
            server.hll_sparse_max_bytes = memtoll(argv[1], NULL);
452 453 454 455 456 457 458 459 460
        } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) {
            struct redisCommand *cmd = lookupCommand(argv[1]);
            int retval;

            if (!cmd) {
                err = "No such command in rename-command";
                goto loaderr;
            }

G
guiquanz 已提交
461
            /* If the target command name is the empty string we just
462 463 464 465 466 467 468 469 470 471 472 473 474 475
             * remove it from the command table. */
            retval = dictDelete(server.commands, argv[1]);
            redisAssert(retval == DICT_OK);

            /* Otherwise we re-add the command under a different name. */
            if (sdslen(argv[2]) != 0) {
                sds copy = sdsdup(argv[2]);

                retval = dictAdd(server.commands, copy, cmd);
                if (retval != DICT_OK) {
                    sdsfree(copy);
                    err = "Target command name already exists"; goto loaderr;
                }
            }
A
antirez 已提交
476 477
        } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) {
            server.lua_time_limit = strtoll(argv[1],NULL,10);
A
antirez 已提交
478 479 480 481
        } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") &&
                   argc == 2)
        {
            server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);
482 483 484 485 486 487 488 489
        } else if (!strcasecmp(argv[0],"latency-monitor-threshold") &&
                   argc == 2)
        {
            server.latency_monitor_threshold = strtoll(argv[1],NULL,10);
            if (server.latency_monitor_threshold < 0) {
                err = "The latency threshold can't be negative";
                goto loaderr;
            }
A
antirez 已提交
490
        } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) {
491
            server.slowlog_max_len = (unsigned long)(strtoll(argv[1],NULL,10));
492 493 494
        } else if (!strcasecmp(argv[0],"client-output-buffer-limit") &&
                   argc == 5)
        {
A
antirez 已提交
495
            int class = getClientTypeByName(argv[1]);
496 497 498 499 500 501 502 503 504 505 506
            unsigned long long hard, soft;
            int soft_seconds;

            if (class == -1) {
                err = "Unrecognized client limit class";
                goto loaderr;
            }
            hard = memtoll(argv[2],NULL);
            soft = memtoll(argv[3],NULL);
            soft_seconds = atoi(argv[4]);
            if (soft_seconds < 0) {
G
guiquanz 已提交
507
                err = "Negative number of seconds in soft limit is invalid";
508 509 510 511 512
                goto loaderr;
            }
            server.client_obuf_limits[class].hard_limit_bytes = hard;
            server.client_obuf_limits[class].soft_limit_bytes = soft;
            server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
513 514 515 516 517
        } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") &&
                   argc == 2) {
            if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
518 519
        } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) {
            server.slave_priority = atoi(argv[1]);
520 521 522 523 524 525 526 527 528 529
        } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) {
            server.repl_min_slaves_to_write = atoi(argv[1]);
            if (server.repl_min_slaves_to_write < 0) {
                err = "Invalid value for min-slaves-to-write."; goto loaderr;
            }
        } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) {
            server.repl_min_slaves_max_lag = atoi(argv[1]);
            if (server.repl_min_slaves_max_lag < 0) {
                err = "Invalid value for min-slaves-max-lag."; goto loaderr;
            }
A
antirez 已提交
530
        } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) {
531 532 533 534 535
            int flags = keyspaceEventsStringToFlags(argv[1]);

            if (flags == -1) {
                err = "Invalid event class character. Use 'g$lshzxeA'.";
                goto loaderr;
A
antirez 已提交
536
            }
537
            server.notify_keyspace_events = flags;
538 539 540 541 542 543 544 545 546 547 548
        } else if (!strcasecmp(argv[0],"sentinel")) {
            /* argc == 1 is handled by main() as we need to enter the sentinel
             * mode ASAP. */
            if (argc != 1) {
                if (!server.sentinel_mode) {
                    err = "sentinel directive while not in sentinel mode";
                    goto loaderr;
                }
                err = sentinelHandleConfiguration(argv+1,argc-1);
                if (err) goto loaderr;
            }
549
#ifdef _WIN32
550 551
		} else if (!strcasecmp(argv[0],"maxheap")) {
			// ignore. This is taken care of in the qfork code.
552 553 554
        } else if (!strcasecmp(argv[0], "heapdir")) {
            // ignore. This is taken care of in the qfork code.
        } else if (!strcasecmp(argv[0], "service-name")) {
555
			// ignore. This is taken care of in the win32_service code.
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        } else if (!strcasecmp(argv[0], "persistence-available")) {
            if (strcasecmp(argv[1], "no") == 0) {
                //remove BGSAVE and BGREWRITEAOF when persistence is disabled
                int retval;
                sds bgsave;
                sds bgrewriteaof;

                bgsave = sdsnew("bgsave");
                bgrewriteaof = sdsnew("bgrewriteaof");

                retval = dictDelete(server.commands, bgsave);
                redisAssert(retval == DICT_OK);
                retval = dictDelete(server.commands, bgrewriteaof);
                redisAssert(retval == DICT_OK);

                sdsfree(bgsave);
                sdsfree(bgrewriteaof);
            }
574 575
#endif
		} else {
576 577
            err = "Bad directive or wrong number of arguments"; goto loaderr;
        }
578
        sdsfreesplitres(argv,argc);
579
    }
580
    sdsfreesplitres(lines,totlines);
581 582 583
    return;

loaderr:
584 585 586 587 588 589
#ifdef _WIN32
    redisLog(REDIS_WARNING, "\n*** FATAL CONFIG FILE ERROR ***\n");
    redisLog(REDIS_WARNING, "Reading the configuration file, at line %d\n", linenum);
    redisLog(REDIS_WARNING, ">>> '%s'\n", lines[i]);
    redisLog(REDIS_WARNING, "%s\n", err);
#else
590 591
    fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
    fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
592
    fprintf(stderr, ">>> '%s'\n", lines[i]);
593
    fprintf(stderr, "%s\n", err);
594
#endif
595 596 597
    exit(1);
}

598 599 600 601 602
/* Load the server configuration from the specified filename.
 * The function appends the additional configuration directives stored
 * in the 'options' string to the config file before loading.
 *
 * Both filename and options can be NULL, in such a case are considered
G
guiquanz 已提交
603
 * empty. This way loadServerConfig can be used to just load a file or
604 605 606 607 608 609 610 611 612 613 614 615
 * just load a string. */
void loadServerConfig(char *filename, char *options) {
    sds config = sdsempty();
    char buf[REDIS_CONFIGLINE_MAX+1];

    /* Load the file content */
    if (filename) {
        FILE *fp;

        if (filename[0] == '-' && filename[1] == '\0') {
            fp = stdin;
        } else {
H
Henry Rawas 已提交
616 617 618
#ifdef _WIN32
            if ((fp = fopen(filename,"rb")) == NULL) {
#else
619
            if ((fp = fopen(filename,"r")) == NULL) {
H
Henry Rawas 已提交
620
#endif
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
                redisLog(REDIS_WARNING,
                    "Fatal error, can't open config file '%s'", filename);
                exit(1);
            }
        }
        while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL)
            config = sdscat(config,buf);
        if (fp != stdin) fclose(fp);
    }
    /* Append the additional options */
    if (options) {
        config = sdscat(config,"\n");
        config = sdscat(config,options);
    }
    loadServerConfigFromString(config);
    sdsfree(config);
}

639
/*-----------------------------------------------------------------------------
640
 * CONFIG SET implementation
641 642 643
 *----------------------------------------------------------------------------*/

void configSetCommand(redisClient *c) {
644
    robj *o;
645
    long long ll;
646 647
    redisAssertWithInfo(c,c->argv[2],c->argv[2]->encoding == REDIS_ENCODING_RAW);
    redisAssertWithInfo(c,c->argv[2],c->argv[3]->encoding == REDIS_ENCODING_RAW);
648
    o = c->argv[3];
649 650

    if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
651 652 653 654
        if (!pathIsBaseName(o->ptr)) {
            addReplyError(c, "dbfilename can't be a path, just a filename");
            return;
        }
A
antirez 已提交
655 656
        zfree(server.rdb_filename);
        server.rdb_filename = zstrdup(o->ptr);
657
    } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
658
        if (sdslen(o->ptr) > REDIS_AUTHPASS_MAX_LEN) goto badfmt;
659
        zfree(server.requirepass);
660
        server.requirepass = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
661 662
    } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
        zfree(server.masterauth);
663
        server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
664 665 666 667
    } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0) goto badfmt;
        server.maxmemory = ll;
668 669 670 671 672 673
        if (server.maxmemory) {
            if (server.maxmemory < zmalloc_used_memory()) {
                redisLog(REDIS_WARNING,"WARNING: the new maxmemory value set via CONFIG SET is smaller than the current memory usage. This will result in keys eviction and/or inability to accept new write commands depending on the maxmemory-policy.");
            }
            freeMemoryIfNeeded();
        }
A
antirez 已提交
674 675 676
    } else if (!strcasecmp(c->argv[2]->ptr,"maxclients")) {
        int orig_value = server.maxclients;

M
Matt Stancliff 已提交
677
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 1) goto badfmt;
A
antirez 已提交
678 679

        /* Try to check if the OS is capable of supporting so many FDs. */
680
        server.maxclients = (int)ll;
A
antirez 已提交
681 682 683 684 685 686 687
        if (ll > orig_value) {
            adjustOpenFilesLimit();
            if (server.maxclients != ll) {
                addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients);
                server.maxclients = orig_value;
                return;
            }
688
            if ((unsigned int) aeGetSetSize(server.el) <
A
antirez 已提交
689 690 691 692 693 694 695 696 697 698 699
                server.maxclients + REDIS_EVENTLOOP_FDSET_INCR)
            {
                if (aeResizeSetSize(server.el,
                    server.maxclients + REDIS_EVENTLOOP_FDSET_INCR) == AE_ERR)
                {
                    addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients");
                    server.maxclients = orig_value;
                    return;
                }
            }
        }
700
    } else if (!strcasecmp(c->argv[2]->ptr,"hz")) {
A
antirez 已提交
701
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
702
        server.hz = (int)ll;
703 704
        if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ;
        if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ;
705 706 707 708 709 710 711 712 713 714 715
    } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-policy")) {
        if (!strcasecmp(o->ptr,"volatile-lru")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
        } else if (!strcasecmp(o->ptr,"volatile-random")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM;
        } else if (!strcasecmp(o->ptr,"volatile-ttl")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL;
        } else if (!strcasecmp(o->ptr,"allkeys-lru")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU;
        } else if (!strcasecmp(o->ptr,"allkeys-random")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM;
716 717
        } else if (!strcasecmp(o->ptr,"noeviction")) {
            server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
718 719 720
        } else {
            goto badfmt;
        }
721 722 723
    } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-samples")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll <= 0) goto badfmt;
724
        server.maxmemory_samples = (int)ll;
725 726 727
    } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0 || ll > LONG_MAX) goto badfmt;
728
        server.maxidletime = (int)ll;
729 730 731
    } else if (!strcasecmp(c->argv[2]->ptr,"tcp-keepalive")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0 || ll > INT_MAX) goto badfmt;
732
        server.tcpkeepalive = (int)ll;
733 734
    } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
        if (!strcasecmp(o->ptr,"no")) {
735
            server.aof_fsync = AOF_FSYNC_NO;
736
        } else if (!strcasecmp(o->ptr,"everysec")) {
737
            server.aof_fsync = AOF_FSYNC_EVERYSEC;
738
        } else if (!strcasecmp(o->ptr,"always")) {
739
            server.aof_fsync = AOF_FSYNC_ALWAYS;
740 741 742 743 744 745 746
        } else {
            goto badfmt;
        }
    } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
747
        server.aof_no_fsync_on_rewrite = yn;
748
    } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
749 750 751 752 753 754 755 756 757 758
        int enable = yesnotoi(o->ptr);

        if (enable == -1) goto badfmt;
        if (enable == 0 && server.aof_state != REDIS_AOF_OFF) {
            stopAppendOnly();
        } else if (enable && server.aof_state == REDIS_AOF_OFF) {
            if (startAppendOnly() == REDIS_ERR) {
                addReplyError(c,
                    "Unable to turn on AOF. Check server logs.");
                return;
759 760
            }
        }
761 762
    } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-percentage")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
763
        server.aof_rewrite_perc = (int)ll;
764 765
    } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-min-size")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
766
        server.aof_rewrite_min_size = ll;
767 768 769 770 771
    } else if (!strcasecmp(c->argv[2]->ptr,"aof-rewrite-incremental-fsync")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.aof_rewrite_incremental_fsync = yn;
772 773 774 775 776
    } else if (!strcasecmp(c->argv[2]->ptr,"aof-load-truncated")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.aof_load_truncated = yn;
777 778
    } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
        int vlen, j;
H
Henry Rawas 已提交
779
        sds *v = sdssplitlen(o->ptr,(int)sdslen(o->ptr)," ",1,&vlen);
780 781 782 783 784 785 786 787 788 789 790 791

        /* Perform sanity check before setting the new config:
         * - Even number of args
         * - Seconds >= 1, changes >= 0 */
        if (vlen & 1) {
            sdsfreesplitres(v,vlen);
            goto badfmt;
        }
        for (j = 0; j < vlen; j++) {
            char *eptr;
            long val;

792
            val = (long)strtoll(v[j], &eptr, 10);
793 794 795 796 797 798 799 800 801 802 803 804 805 806
            if (eptr[0] != '\0' ||
                ((j & 1) == 0 && val < 1) ||
                ((j & 1) == 1 && val < 0)) {
                sdsfreesplitres(v,vlen);
                goto badfmt;
            }
        }
        /* Finally set the new config */
        resetServerSaveParams();
        for (j = 0; j < vlen; j += 2) {
            time_t seconds;
            int changes;

            seconds = strtoll(v[j],NULL,10);
807
            changes = (int)strtoll(v[j+1],NULL,10);
808 809 810
            appendServerSaveParams(seconds, changes);
        }
        sdsfreesplitres(v,vlen);
811 812 813 814 815
    } else if (!strcasecmp(c->argv[2]->ptr,"slave-serve-stale-data")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.repl_serve_stale_data = yn;
816 817 818 819 820
    } else if (!strcasecmp(c->argv[2]->ptr,"slave-read-only")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.repl_slave_ro = yn;
A
antirez 已提交
821 822 823 824 825
    } else if (!strcasecmp(c->argv[2]->ptr,"dir")) {
        if (chdir((char*)o->ptr) == -1) {
            addReplyErrorFormat(c,"Changing directory: %s", strerror(errno));
            return;
        }
826
    } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-entries")) {
827
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
828 829
        server.hash_max_ziplist_entries = ll;
    } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-value")) {
830
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
831
        server.hash_max_ziplist_value = ll;
832 833 834 835 836 837 838 839 840
    } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-entries")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.list_max_ziplist_entries = ll;
    } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-value")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.list_max_ziplist_value = ll;
    } else if (!strcasecmp(c->argv[2]->ptr,"set-max-intset-entries")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.set_max_intset_entries = ll;
841 842 843 844 845 846
    } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-entries")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.zset_max_ziplist_entries = ll;
    } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-value")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.zset_max_ziplist_value = ll;
847 848 849
    } else if (!strcasecmp(c->argv[2]->ptr,"hll-sparse-max-bytes")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.hll_sparse_max_bytes = ll;
A
antirez 已提交
850 851 852
    } else if (!strcasecmp(c->argv[2]->ptr,"lua-time-limit")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.lua_time_limit = ll;
A
antirez 已提交
853 854 855 856 857 858
    } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-log-slower-than")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR) goto badfmt;
        server.slowlog_log_slower_than = ll;
    } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-max-len")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.slowlog_max_len = (unsigned)ll;
859 860 861
    } else if (!strcasecmp(c->argv[2]->ptr,"latency-monitor-threshold")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.latency_monitor_threshold = ll;
A
antirez 已提交
862 863 864 865 866 867 868 869 870 871 872 873
    } else if (!strcasecmp(c->argv[2]->ptr,"loglevel")) {
        if (!strcasecmp(o->ptr,"warning")) {
            server.verbosity = REDIS_WARNING;
        } else if (!strcasecmp(o->ptr,"notice")) {
            server.verbosity = REDIS_NOTICE;
        } else if (!strcasecmp(o->ptr,"verbose")) {
            server.verbosity = REDIS_VERBOSE;
        } else if (!strcasecmp(o->ptr,"debug")) {
            server.verbosity = REDIS_DEBUG;
        } else {
            goto badfmt;
        }
874
#ifdef _WIN32
875
        setLogVerbosityLevel(server.verbosity);
876
#endif
877 878
    } else if (!strcasecmp(c->argv[2]->ptr,"client-output-buffer-limit")) {
        int vlen, j;
H
Henry Rawas 已提交
879
        sds *v = sdssplitlen(o->ptr,(int)sdslen(o->ptr)," ",1,&vlen);
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

        /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */
        if (vlen % 4) {
            sdsfreesplitres(v,vlen);
            goto badfmt;
        }

        /* Sanity check of single arguments, so that we either refuse the
         * whole configuration string or accept it all, even if a single
         * error in a single client class is present. */
        for (j = 0; j < vlen; j++) {
            char *eptr;
            long val;

            if ((j % 4) == 0) {
A
antirez 已提交
895
                if (getClientTypeByName(v[j]) == -1) {
896 897 898 899
                    sdsfreesplitres(v,vlen);
                    goto badfmt;
                }
            } else {
900
                val = (long)strtoll(v[j], &eptr, 10);
901 902 903 904 905 906 907 908 909 910 911 912
                if (eptr[0] != '\0' || val < 0) {
                    sdsfreesplitres(v,vlen);
                    goto badfmt;
                }
            }
        }
        /* Finally set the new config */
        for (j = 0; j < vlen; j += 4) {
            int class;
            unsigned long long hard, soft;
            int soft_seconds;

A
antirez 已提交
913
            class = getClientTypeByName(v[j]);
914 915
            hard = strtoll(v[j+1],NULL,10);
            soft = strtoll(v[j+2],NULL,10);
916
            soft_seconds = (int)strtoll(v[j+3],NULL,10);
917 918 919 920 921 922

            server.client_obuf_limits[class].hard_limit_bytes = hard;
            server.client_obuf_limits[class].soft_limit_bytes = soft;
            server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
        }
        sdsfreesplitres(v,vlen);
923 924
    } else if (!strcasecmp(c->argv[2]->ptr,"stop-writes-on-bgsave-error")) {
        int yn = yesnotoi(o->ptr);
925

926 927
        if (yn == -1) goto badfmt;
        server.stop_writes_on_bgsave_err = yn;
928 929
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-ping-slave-period")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
930
        server.repl_ping_slave_period = (int)ll;
931 932
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-timeout")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
933
        server.repl_timeout = (int)ll;
934 935 936 937 938 939
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-size")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
        resizeReplicationBacklog(ll);
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-ttl")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        server.repl_backlog_time_limit = ll;
A
antirez 已提交
940 941 942
    } else if (!strcasecmp(c->argv[2]->ptr,"watchdog-period")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
        if (ll)
H
Henry Rawas 已提交
943
            enableWatchdog((int)ll);
A
antirez 已提交
944 945
        else
            disableWatchdog();
946 947 948 949 950
    } else if (!strcasecmp(c->argv[2]->ptr,"rdbcompression")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.rdb_compression = yn;
A
antirez 已提交
951
    } else if (!strcasecmp(c->argv[2]->ptr,"notify-keyspace-events")) {
952
        int flags = keyspaceEventsStringToFlags(o->ptr);
953

954 955
        if (flags == -1) goto badfmt;
        server.notify_keyspace_events = flags;
956 957
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-disable-tcp-nodelay")) {
        int yn = yesnotoi(o->ptr);
958

959 960
        if (yn == -1) goto badfmt;
        server.repl_disable_tcp_nodelay = yn;
961 962 963 964 965
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-diskless-sync")) {
        int yn = yesnotoi(o->ptr);

        if (yn == -1) goto badfmt;
        server.repl_diskless_sync = yn;
A
antirez 已提交
966 967 968 969
    } else if (!strcasecmp(c->argv[2]->ptr,"repl-diskless-sync-delay")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0) goto badfmt;
        server.repl_diskless_sync_delay = ll;
970 971
    } else if (!strcasecmp(c->argv[2]->ptr,"slave-priority")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
972
            ll < 0) goto badfmt;
973
        server.slave_priority = (int)ll;
974 975 976
    } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-to-write")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0) goto badfmt;
977
        server.repl_min_slaves_to_write = (int)ll;
978
        refreshGoodSlavesCount();
979 980 981
    } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-max-lag")) {
        if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
            ll < 0) goto badfmt;
982
        server.repl_min_slaves_max_lag = (int)ll;
983
        refreshGoodSlavesCount();
984
    } else {
985 986
        addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s",
            (char*)c->argv[2]->ptr);
987 988 989 990 991 992
        return;
    }
    addReply(c,shared.ok);
    return;

badfmt: /* Bad format errors */
993
    addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'",
994
            (char*)o->ptr,
995
            (char*)c->argv[2]->ptr);
996 997
}

998 999 1000 1001
/*-----------------------------------------------------------------------------
 * CONFIG GET implementation
 *----------------------------------------------------------------------------*/

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
#define config_get_string_field(_name,_var) do { \
    if (stringmatch(pattern,_name,0)) { \
        addReplyBulkCString(c,_name); \
        addReplyBulkCString(c,_var ? _var : ""); \
        matches++; \
    } \
} while(0);

#define config_get_bool_field(_name,_var) do { \
    if (stringmatch(pattern,_name,0)) { \
        addReplyBulkCString(c,_name); \
        addReplyBulkCString(c,_var ? "yes" : "no"); \
        matches++; \
    } \
} while(0);

#define config_get_numerical_field(_name,_var) do { \
    if (stringmatch(pattern,_name,0)) { \
        ll2string(buf,sizeof(buf),_var); \
        addReplyBulkCString(c,_name); \
        addReplyBulkCString(c,buf); \
        matches++; \
    } \
} while(0);

1027
void configGetCommand(redisClient *c) {
1028
    robj *o = c->argv[2];
1029
    void *replylen = addDeferredMultiBulkLength(c);
1030
    char *pattern = o->ptr;
1031
    char buf[128];
1032
    int matches = 0;
1033
    redisAssertWithInfo(c,o,o->encoding == REDIS_ENCODING_RAW);
1034

1035 1036 1037
    /* String values */
    config_get_string_field("dbfilename",server.rdb_filename);
    config_get_string_field("requirepass",server.requirepass);
一个手艺人's avatar
一个手艺人 已提交
1038
    config_get_string_field("masterauth",server.masterauth);
1039 1040 1041 1042 1043 1044 1045 1046
    config_get_string_field("unixsocket",server.unixsocket);
    config_get_string_field("logfile",server.logfile);
    config_get_string_field("pidfile",server.pidfile);

    /* Numerical values */
    config_get_numerical_field("maxmemory",server.maxmemory);
    config_get_numerical_field("maxmemory-samples",server.maxmemory_samples);
    config_get_numerical_field("timeout",server.maxidletime);
1047
    config_get_numerical_field("tcp-keepalive",server.tcpkeepalive);
1048 1049 1050 1051
    config_get_numerical_field("auto-aof-rewrite-percentage",
            server.aof_rewrite_perc);
    config_get_numerical_field("auto-aof-rewrite-min-size",
            server.aof_rewrite_min_size);
A
antirez 已提交
1052 1053 1054 1055
    config_get_numerical_field("hash-max-ziplist-entries",
            server.hash_max_ziplist_entries);
    config_get_numerical_field("hash-max-ziplist-value",
            server.hash_max_ziplist_value);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    config_get_numerical_field("list-max-ziplist-entries",
            server.list_max_ziplist_entries);
    config_get_numerical_field("list-max-ziplist-value",
            server.list_max_ziplist_value);
    config_get_numerical_field("set-max-intset-entries",
            server.set_max_intset_entries);
    config_get_numerical_field("zset-max-ziplist-entries",
            server.zset_max_ziplist_entries);
    config_get_numerical_field("zset-max-ziplist-value",
            server.zset_max_ziplist_value);
1066 1067
    config_get_numerical_field("hll-sparse-max-bytes",
            server.hll_sparse_max_bytes);
1068 1069 1070
    config_get_numerical_field("lua-time-limit",server.lua_time_limit);
    config_get_numerical_field("slowlog-log-slower-than",
            server.slowlog_log_slower_than);
1071 1072
    config_get_numerical_field("latency-monitor-threshold",
            server.latency_monitor_threshold);
1073 1074 1075
    config_get_numerical_field("slowlog-max-len",
            server.slowlog_max_len);
    config_get_numerical_field("port",server.port);
1076
    config_get_numerical_field("tcp-backlog",server.tcp_backlog);
1077 1078 1079
    config_get_numerical_field("databases",server.dbnum);
    config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period);
    config_get_numerical_field("repl-timeout",server.repl_timeout);
1080 1081
    config_get_numerical_field("repl-backlog-size",server.repl_backlog_size);
    config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit);
1082
    config_get_numerical_field("maxclients",server.maxclients);
A
antirez 已提交
1083
    config_get_numerical_field("watchdog-period",server.watchdog_period);
1084
    config_get_numerical_field("slave-priority",server.slave_priority);
1085 1086
    config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write);
    config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag);
1087
    config_get_numerical_field("hz",server.hz);
A
antirez 已提交
1088
    config_get_numerical_field("repl-diskless-sync-delay",server.repl_diskless_sync_delay);
1089 1090 1091 1092 1093 1094

    /* Bool (yes/no) values */
    config_get_bool_field("no-appendfsync-on-rewrite",
            server.aof_no_fsync_on_rewrite);
    config_get_bool_field("slave-serve-stale-data",
            server.repl_serve_stale_data);
1095 1096
    config_get_bool_field("slave-read-only",
            server.repl_slave_ro);
1097 1098 1099 1100
    config_get_bool_field("stop-writes-on-bgsave-error",
            server.stop_writes_on_bgsave_err);
    config_get_bool_field("daemonize", server.daemonize);
    config_get_bool_field("rdbcompression", server.rdb_compression);
1101
    config_get_bool_field("rdbchecksum", server.rdb_checksum);
1102
    config_get_bool_field("activerehashing", server.activerehashing);
1103 1104
    config_get_bool_field("repl-disable-tcp-nodelay",
            server.repl_disable_tcp_nodelay);
1105 1106
    config_get_bool_field("repl-diskless-sync",
            server.repl_diskless_sync);
1107 1108
    config_get_bool_field("aof-rewrite-incremental-fsync",
            server.aof_rewrite_incremental_fsync);
1109 1110
    config_get_bool_field("aof-load-truncated",
            server.aof_load_truncated);
1111 1112 1113 1114 1115 1116 1117 1118

    /* Everything we can't handle with macros follows. */

    if (stringmatch(pattern,"appendonly",0)) {
        addReplyBulkCString(c,"appendonly");
        addReplyBulkCString(c,server.aof_state == REDIS_AOF_OFF ? "no" : "yes");
        matches++;
    }
A
antirez 已提交
1119 1120 1121
    if (stringmatch(pattern,"dir",0)) {
        char buf[1024];

1122
        if (getcwd(buf,sizeof(buf)) == NULL)
A
antirez 已提交
1123
            buf[0] = '\0';
1124 1125 1126

        addReplyBulkCString(c,"dir");
        addReplyBulkCString(c,buf);
A
antirez 已提交
1127 1128
        matches++;
    }
1129 1130 1131 1132 1133 1134 1135 1136 1137
    if (stringmatch(pattern,"maxmemory-policy",0)) {
        char *s;

        switch(server.maxmemory_policy) {
        case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break;
        case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break;
        case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break;
        case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break;
        case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break;
1138
        case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break;
1139 1140 1141 1142 1143 1144
        default: s = "unknown"; break; /* too harmless to panic */
        }
        addReplyBulkCString(c,"maxmemory-policy");
        addReplyBulkCString(c,s);
        matches++;
    }
1145 1146 1147
    if (stringmatch(pattern,"appendfsync",0)) {
        char *policy;

1148 1149 1150 1151
        switch(server.aof_fsync) {
        case AOF_FSYNC_NO: policy = "no"; break;
        case AOF_FSYNC_EVERYSEC: policy = "everysec"; break;
        case AOF_FSYNC_ALWAYS: policy = "always"; break;
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
        default: policy = "unknown"; break; /* too harmless to panic */
        }
        addReplyBulkCString(c,"appendfsync");
        addReplyBulkCString(c,policy);
        matches++;
    }
    if (stringmatch(pattern,"save",0)) {
        sds buf = sdsempty();
        int j;

        for (j = 0; j < server.saveparamslen; j++) {
Y
YAMAMOTO Takashi 已提交
1163 1164
            buf = sdscatprintf(buf,"%jd %d",
                    (intmax_t)server.saveparams[j].seconds,
1165 1166 1167 1168 1169 1170 1171 1172 1173
                    server.saveparams[j].changes);
            if (j != server.saveparamslen-1)
                buf = sdscatlen(buf," ",1);
        }
        addReplyBulkCString(c,"save");
        addReplyBulkCString(c,buf);
        sdsfree(buf);
        matches++;
    }
A
antirez 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    if (stringmatch(pattern,"loglevel",0)) {
        char *s;

        switch(server.verbosity) {
        case REDIS_WARNING: s = "warning"; break;
        case REDIS_VERBOSE: s = "verbose"; break;
        case REDIS_NOTICE: s = "notice"; break;
        case REDIS_DEBUG: s = "debug"; break;
        default: s = "unknown"; break; /* too harmless to panic */
        }
        addReplyBulkCString(c,"loglevel");
        addReplyBulkCString(c,s);
        matches++;
    }
1188 1189 1190 1191
    if (stringmatch(pattern,"client-output-buffer-limit",0)) {
        sds buf = sdsempty();
        int j;

A
antirez 已提交
1192
        for (j = 0; j < REDIS_CLIENT_TYPE_COUNT; j++) {
1193
            buf = sdscatprintf(buf,"%s %llu %llu %ld",
A
antirez 已提交
1194
                    getClientTypeName(j),
1195 1196 1197
                    server.client_obuf_limits[j].hard_limit_bytes,
                    server.client_obuf_limits[j].soft_limit_bytes,
                    (long) server.client_obuf_limits[j].soft_limit_seconds);
A
antirez 已提交
1198
            if (j != REDIS_CLIENT_TYPE_COUNT-1)
1199 1200 1201 1202 1203 1204 1205
                buf = sdscatlen(buf," ",1);
        }
        addReplyBulkCString(c,"client-output-buffer-limit");
        addReplyBulkCString(c,buf);
        sdsfree(buf);
        matches++;
    }
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    if (stringmatch(pattern,"unixsocketperm",0)) {
        char buf[32];
        snprintf(buf,sizeof(buf),"%o",server.unixsocketperm);
        addReplyBulkCString(c,"unixsocketperm");
        addReplyBulkCString(c,buf);
        matches++;
    }
    if (stringmatch(pattern,"slaveof",0)) {
        char buf[256];

        addReplyBulkCString(c,"slaveof");
        if (server.masterhost)
            snprintf(buf,sizeof(buf),"%s %d",
                server.masterhost, server.masterport);
        else
            buf[0] = '\0';
        addReplyBulkCString(c,buf);
1223 1224
        matches++;
    }
1225 1226 1227 1228 1229 1230 1231 1232 1233
    if (stringmatch(pattern,"notify-keyspace-events",0)) {
        robj *flagsobj = createObject(REDIS_STRING,
            keyspaceEventsFlagsToString(server.notify_keyspace_events));

        addReplyBulkCString(c,"notify-keyspace-events");
        addReplyBulk(c,flagsobj);
        decrRefCount(flagsobj);
        matches++;
    }
A
antirez 已提交
1234 1235 1236 1237 1238 1239 1240 1241
    if (stringmatch(pattern,"bind",0)) {
        sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," ");

        addReplyBulkCString(c,"bind");
        addReplyBulkCString(c,aux);
        sdsfree(aux);
        matches++;
    }
1242
    setDeferredMultiBulkLength(c,replylen,matches*2);
1243 1244
}

1245 1246 1247 1248
/*-----------------------------------------------------------------------------
 * CONFIG REWRITE implementation
 *----------------------------------------------------------------------------*/

1249 1250
#define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE"

1251 1252 1253
/* We use the following dictionary type to store where a configuration
 * option is mentioned in the old configuration file, so it's
 * like "maxmemory" -> list of line numbers (first line is zero). */
1254 1255
unsigned int dictSdsCaseHash(const void *key);
int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2);
1256 1257 1258
void dictSdsDestructor(void *privdata, void *val);
void dictListDestructor(void *privdata, void *val);

1259 1260 1261 1262
/* Sentinel config rewriting is implemented inside sentinel.c by
 * rewriteConfigSentinelOption(). */
void rewriteConfigSentinelOption(struct rewriteConfigState *state);

1263
dictType optionToLineDictType = {
1264
    dictSdsCaseHash,            /* hash function */
1265 1266
    NULL,                       /* key dup */
    NULL,                       /* val dup */
1267
    dictSdsKeyCaseCompare,      /* key compare */
1268 1269 1270 1271
    dictSdsDestructor,          /* key destructor */
    dictListDestructor          /* val destructor */
};

1272 1273 1274 1275 1276 1277 1278 1279 1280
dictType optionSetDictType = {
    dictSdsCaseHash,            /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictSdsKeyCaseCompare,      /* key compare */
    dictSdsDestructor,          /* key destructor */
    NULL                        /* val destructor */
};

1281 1282 1283
/* The config rewrite state. */
struct rewriteConfigState {
    dict *option_to_line; /* Option -> list of config file lines map */
1284
    dict *rewritten;      /* Dictionary of already processed options */
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    int numlines;         /* Number of lines in current config */
    sds *lines;           /* Current lines as an array of sds strings */
    int has_tail;         /* True if we already added directives that were
                             not present in the original config file. */
};

/* Append the new line to the current configuration state. */
void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) {
    state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1));
    state->lines[state->numlines++] = line;
}

/* Populate the option -> list of line numbers map. */
void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) {
    list *l = dictFetchValue(state->option_to_line,option);

    if (l == NULL) {
        l = listCreate();
        dictAdd(state->option_to_line,sdsdup(option),l);
    }
    listAddNodeTail(l,(void*)(long)linenum);
}

1308 1309 1310 1311 1312 1313 1314
/* Add the specified option to the set of processed options.
 * This is useful as only unused lines of processed options will be blanked
 * in the config file, while options the rewrite process does not understand
 * remain untouched. */
void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, char *option) {
    sds opt = sdsnew(option);

1315
    if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt);
1316 1317
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
/* Read the old file, split it into lines to populate a newly created
 * config rewrite state, and return it to the caller.
 *
 * If it is impossible to read the old file, NULL is returned.
 * If the old file does not exist at all, an empty state is returned. */
struct rewriteConfigState *rewriteConfigReadOldFile(char *path) {
    FILE *fp = fopen(path,"r");
    struct rewriteConfigState *state = zmalloc(sizeof(*state));
    char buf[REDIS_CONFIGLINE_MAX+1];
    int linenum = -1;

    if (fp == NULL && errno != ENOENT) return NULL;

    state->option_to_line = dictCreate(&optionToLineDictType,NULL);
1332
    state->rewritten = dictCreate(&optionSetDictType,NULL);
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
    state->numlines = 0;
    state->lines = NULL;
    state->has_tail = 0;
    if (fp == NULL) return state;

    /* Read the old file line by line, populate the state. */
    while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
        int argc;
        sds *argv;
        sds line = sdstrim(sdsnew(buf),"\r\n\t ");

        linenum++; /* Zero based, so we init at -1 */

        /* Handle comments and empty lines. */
        if (line[0] == '#' || line[0] == '\0') {
1348 1349
            if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE))
                state->has_tail = 1;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
            rewriteConfigAppendLine(state,line);
            continue;
        }

        /* Not a comment, split into arguments. */
        argv = sdssplitargs(line,&argc);
        if (argv == NULL) {
            /* Apparently the line is unparsable for some reason, for
             * instance it may have unbalanced quotes. Load it as a
             * comment. */
            sds aux = sdsnew("# ??? ");
            aux = sdscatsds(aux,line);
            sdsfree(line);
            rewriteConfigAppendLine(state,aux);
            continue;
        }

        sdstolower(argv[0]); /* We only want lowercase config directives. */

        /* Now we populate the state according to the content of this line.
         * Append the line and populate the option -> line numbers map. */
        rewriteConfigAppendLine(state,line);
        rewriteConfigAddLineNumberToOption(state,argv[0],linenum);

        sdsfreesplitres(argv,argc);
    }
    fclose(fp);
    return state;
}

/* Rewrite the specified configuration option with the new "line".
 * It progressively uses lines of the file that were already used for the same
1382
 * configuration option in the old version of the file, removing that line from
1383 1384 1385 1386 1387 1388
 * the map of options -> line numbers.
 *
 * If there are lines associated with a given configuration option and
 * "force" is non-zero, the line is appended to the configuration file.
 * Usually "force" is true when an option has not its default value, so it
 * must be rewritten even if not present previously.
1389
 *
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
 * The first time a line is appended into a configuration file, a comment
 * is added to show that starting from that point the config file was generated
 * by CONFIG REWRITE.
 *
 * "line" is either used, or freed, so the caller does not need to free it
 * in any way. */
void rewriteConfigRewriteLine(struct rewriteConfigState *state, char *option, sds line, int force) {
    sds o = sdsnew(option);
    list *l = dictFetchValue(state->option_to_line,o);

1400 1401
    rewriteConfigMarkAsProcessed(state,option);

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    if (!l && !force) {
        /* Option not used previously, and we are not forced to use it. */
        sdsfree(line);
        sdsfree(o);
        return;
    }

    if (l) {
        listNode *ln = listFirst(l);
        int linenum = (long) ln->value;

        /* There are still lines in the old configuration file we can reuse
         * for this option. Replace the line with the new one. */
        listDelNode(l,ln);
        if (listLength(l) == 0) dictDelete(state->option_to_line,o);
        sdsfree(state->lines[linenum]);
        state->lines[linenum] = line;
    } else {
        /* Append a new line. */
        if (!state->has_tail) {
            rewriteConfigAppendLine(state,
1423
                sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE));
1424 1425 1426 1427 1428 1429 1430
            state->has_tail = 1;
        }
        rewriteConfigAppendLine(state,line);
    }
    sdsfree(o);
}

1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
/* Write the long long 'bytes' value as a string in a way that is parsable
 * inside redis.conf. If possible uses the GB, MB, KB notation. */
int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) {
    int gb = 1024*1024*1024;
    int mb = 1024*1024;
    int kb = 1024;

    if (bytes && (bytes % gb) == 0) {
        return snprintf(buf,len,"%lldgb",bytes/gb);
    } else if (bytes && (bytes % mb) == 0) {
        return snprintf(buf,len,"%lldmb",bytes/mb);
    } else if (bytes && (bytes % kb) == 0) {
        return snprintf(buf,len,"%lldkb",bytes/kb);
    } else {
        return snprintf(buf,len,"%lld",bytes);
    }
}

1449 1450
/* Rewrite a simple "option-name <bytes>" configuration option. */
void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
1451
    char buf[64];
1452
    int force = value != defvalue;
1453
    sds line;
1454

1455 1456
    rewriteConfigFormatMemory(buf,sizeof(buf),value);
    line = sdscatprintf(sdsempty(),"%s %s",option,buf);
1457 1458 1459
    rewriteConfigRewriteLine(state,option,line,force);
}

A
antirez 已提交
1460
/* Rewrite a yes/no option. */
1461 1462 1463 1464 1465 1466 1467 1468
void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
    int force = value != defvalue;
    sds line = sdscatprintf(sdsempty(),"%s %s",option,
        value ? "yes" : "no");

    rewriteConfigRewriteLine(state,option,line,force);
}

A
antirez 已提交
1469
/* Rewrite a string option. */
1470 1471 1472 1473 1474 1475
void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) {
    int force = 1;
    sds line;

    /* String options set to NULL need to be not present at all in the
     * configuration file to be set to NULL again at the next reboot. */
1476 1477 1478 1479
    if (value == NULL) {
        rewriteConfigMarkAsProcessed(state,option);
        return;
    }
1480

1481
    /* Set force to zero if the value is set to its default. */
1482 1483 1484 1485 1486 1487 1488 1489 1490
    if (defvalue && strcmp(value,defvalue) == 0) force = 0;

    line = sdsnew(option);
    line = sdscatlen(line, " ", 1);
    line = sdscatrepr(line, value, strlen(value));

    rewriteConfigRewriteLine(state,option,line,force);
}

A
antirez 已提交
1491
/* Rewrite a numerical (long long range) option. */
1492 1493 1494 1495 1496 1497 1498
void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
    int force = value != defvalue;
    sds line = sdscatprintf(sdsempty(),"%s %lld",option,value);

    rewriteConfigRewriteLine(state,option,line,force);
}

A
antirez 已提交
1499
/* Rewrite a octal option. */
1500 1501 1502 1503 1504 1505 1506
void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
    int force = value != defvalue;
    sds line = sdscatprintf(sdsempty(),"%s %o",option,value);

    rewriteConfigRewriteLine(state,option,line,force);
}

A
antirez 已提交
1507 1508 1509
/* Rewrite an enumeration option, after the "value" every enum/value pair
 * is specified, terminated by NULL. After NULL the default value is
 * specified. See how the function is used for more information. */
1510 1511
void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, ...) {
    va_list ap;
1512
    char *enum_name, *matching_name = NULL;
1513 1514
    int enum_val, def_val, force;
    sds line;
1515

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    va_start(ap, value);
    while(1) {
        enum_name = va_arg(ap,char*);
        enum_val = va_arg(ap,int);
        if (enum_name == NULL) {
            def_val = enum_val;
            break;
        }
        if (value == enum_val) matching_name = enum_name;
    }
    va_end(ap);
1527

1528 1529 1530 1531 1532
    force = value != def_val;
    line = sdscatprintf(sdsempty(),"%s %s",option,matching_name);
    rewriteConfigRewriteLine(state,option,line,force);
}

1533
#ifndef _WIN32
E
Ezequiel Lovelle 已提交
1534
/* Rewrite the syslog-facility option. */
1535
void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) {
1536 1537
    int value = server.syslog_facility, j;
    int force = value != LOG_LOCAL0;
1538
    char *name = NULL, *option = "syslog-facility";
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    sds line;

    for (j = 0; validSyslogFacilities[j].name; j++) {
        if (validSyslogFacilities[j].value == value) {
            name = (char*) validSyslogFacilities[j].name;
            break;
        }
    }
    line = sdscatprintf(sdsempty(),"%s %s",option,name);
    rewriteConfigRewriteLine(state,option,line,force);
1549
}
1550
#endif
1551

A
antirez 已提交
1552
/* Rewrite the save option. */
1553
void rewriteConfigSaveOption(struct rewriteConfigState *state) {
1554 1555 1556 1557 1558 1559 1560 1561
    int j;
    sds line;

    /* Note that if there are no save parameters at all, all the current
     * config line with "save" will be detected as orphaned and deleted,
     * resulting into no RDB persistence as expected. */
    for (j = 0; j < server.saveparamslen; j++) {
        line = sdscatprintf(sdsempty(),"save %ld %d",
1562
            (long) server.saveparams[j].seconds, server.saveparams[j].changes);
1563 1564
        rewriteConfigRewriteLine(state,"save",line,1);
    }
1565 1566
    /* Mark "save" as processed in case server.saveparamslen is zero. */
    rewriteConfigMarkAsProcessed(state,"save");
1567 1568
}

A
antirez 已提交
1569
/* Rewrite the dir option, always using absolute paths.*/
1570
void rewriteConfigDirOption(struct rewriteConfigState *state) {
1571 1572
    char cwd[1024];

1573 1574 1575 1576
    if (getcwd(cwd,sizeof(cwd)) == NULL) {
        rewriteConfigMarkAsProcessed(state,"dir");
        return; /* no rewrite on error. */
    }
1577
    rewriteConfigStringOption(state,"dir",cwd,NULL);
1578 1579
}

A
antirez 已提交
1580
/* Rewrite the slaveof option. */
1581
void rewriteConfigSlaveofOption(struct rewriteConfigState *state) {
1582
    char *option = "slaveof";
1583 1584 1585 1586
    sds line;

    /* If this is a master, we want all the slaveof config options
     * in the file to be removed. */
1587 1588 1589 1590
    if (server.masterhost == NULL) {
        rewriteConfigMarkAsProcessed(state,"slaveof");
        return;
    }
1591
    line = sdscatprintf(sdsempty(),"%s %s %d", option,
1592
        server.masterhost, server.masterport);
1593
    rewriteConfigRewriteLine(state,option,line,1);
1594 1595
}

A
antirez 已提交
1596
/* Rewrite the notify-keyspace-events option. */
1597
void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) {
1598 1599 1600 1601 1602
    int force = server.notify_keyspace_events != 0;
    char *option = "notify-keyspace-events";
    sds line, flags;

    flags = keyspaceEventsFlagsToString(server.notify_keyspace_events);
1603 1604 1605
    line = sdsnew(option);
    line = sdscatlen(line, " ", 1);
    line = sdscatrepr(line, flags, sdslen(flags));
1606 1607
    sdsfree(flags);
    rewriteConfigRewriteLine(state,option,line,force);
1608 1609
}

A
antirez 已提交
1610
/* Rewrite the client-output-buffer-limit option. */
1611
void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) {
1612 1613 1614
    int j;
    char *option = "client-output-buffer-limit";

A
antirez 已提交
1615
    for (j = 0; j < REDIS_CLIENT_TYPE_COUNT; j++) {
1616 1617 1618 1619 1620 1621 1622
        int force = (server.client_obuf_limits[j].hard_limit_bytes !=
                    clientBufferLimitsDefaults[j].hard_limit_bytes) ||
                    (server.client_obuf_limits[j].soft_limit_bytes !=
                    clientBufferLimitsDefaults[j].soft_limit_bytes) ||
                    (server.client_obuf_limits[j].soft_limit_seconds !=
                    clientBufferLimitsDefaults[j].soft_limit_seconds);
        sds line;
1623 1624 1625 1626 1627 1628
        char hard[64], soft[64];

        rewriteConfigFormatMemory(hard,sizeof(hard),
                server.client_obuf_limits[j].hard_limit_bytes);
        rewriteConfigFormatMemory(soft,sizeof(soft),
                server.client_obuf_limits[j].soft_limit_bytes);
1629

1630
        line = sdscatprintf(sdsempty(),"%s %s %s %s %ld",
A
antirez 已提交
1631
                option, getClientTypeName(j), hard, soft,
1632 1633 1634
                (long) server.client_obuf_limits[j].soft_limit_seconds);
        rewriteConfigRewriteLine(state,option,line,force);
    }
1635 1636
}

A
antirez 已提交
1637 1638 1639 1640 1641 1642 1643
/* Rewrite the bind option. */
void rewriteConfigBindOption(struct rewriteConfigState *state) {
    int force = 1;
    sds line, addresses;
    char *option = "bind";

    /* Nothing to rewrite if we don't have bind addresses. */
1644 1645 1646 1647
    if (server.bindaddr_count == 0) {
        rewriteConfigMarkAsProcessed(state,option);
        return;
    }
A
antirez 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

    /* Rewrite as bind <addr1> <addr2> ... <addrN> */
    addresses = sdsjoin(server.bindaddr,server.bindaddr_count," ");
    line = sdsnew(option);
    line = sdscatlen(line, " ", 1);
    line = sdscatsds(line, addresses);
    sdsfree(addresses);

    rewriteConfigRewriteLine(state,option,line,force);
}

1659 1660
/* Glue together the configuration lines in the current configuration
 * rewrite state into a single string, stripping multiple empty lines. */
1661 1662
sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) {
    sds content = sdsempty();
1663
    int j, was_empty = 0;
1664 1665

    for (j = 0; j < state->numlines; j++) {
1666 1667 1668 1669 1670 1671 1672
        /* Every cluster of empty lines is turned into a single empty line. */
        if (sdslen(state->lines[j]) == 0) {
            if (was_empty) continue;
            was_empty = 1;
        } else {
            was_empty = 0;
        }
1673 1674 1675 1676 1677 1678
        content = sdscatsds(content,state->lines[j]);
        content = sdscatlen(content,"\n",1);
    }
    return content;
}

A
antirez 已提交
1679
/* Free the configuration rewrite state. */
1680 1681 1682
void rewriteConfigReleaseState(struct rewriteConfigState *state) {
    sdsfreesplitres(state->lines,state->numlines);
    dictRelease(state->option_to_line);
1683
    dictRelease(state->rewritten);
1684 1685 1686
    zfree(state);
}

A
antirez 已提交
1687 1688 1689 1690 1691 1692 1693
/* At the end of the rewrite process the state contains the remaining
 * map between "option name" => "lines in the original config file".
 * Lines used by the rewrite process were removed by the function
 * rewriteConfigRewriteLine(), all the other lines are "orphaned" and
 * should be replaced by empty lines.
 *
 * This function does just this, iterating all the option names and
1694
 * blanking all the lines still associated. */
A
antirez 已提交
1695 1696 1697 1698 1699 1700
void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) {
    dictIterator *di = dictGetIterator(state->option_to_line);
    dictEntry *de;

    while((de = dictNext(di)) != NULL) {
        list *l = dictGetVal(de);
1701 1702 1703 1704
        sds option = dictGetKey(de);

        /* Don't blank lines about options the rewrite process
         * don't understand. */
1705
        if (dictFind(state->rewritten,option) == NULL) {
1706 1707 1708
            redisLog(REDIS_DEBUG,"Not rewritten option: %s", option);
            continue;
        }
A
antirez 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

        while(listLength(l)) {
            listNode *ln = listFirst(l);
            int linenum = (long) ln->value;

            sdsfree(state->lines[linenum]);
            state->lines[linenum] = sdsempty();
            listDelNode(l,ln);
        }
    }
    dictReleaseIterator(di);
}

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
/* This function overwrites the old configuration file with the new content.
 *
 * 1) The old file length is obtained.
 * 2) If the new content is smaller, padding is added.
 * 3) A single write(2) call is used to replace the content of the file.
 * 4) Later the file is truncated to the length of the new content.
 *
 * This way we are sure the file is left in a consistent state even if the
 * process is stopped between any of the four operations.
 *
 * The function returns 0 on success, otherwise -1 is returned and errno
 * set accordingly. */
int rewriteConfigOverwriteFile(char *configfile, sds content) {
    int retval = 0;
1736
    int fd = open(configfile,O_RDWR|O_CREAT,0644);
1737
    int content_size = (int)sdslen(content), padding = 0;
1738 1739 1740 1741 1742
#ifdef _WIN32
	struct _stat64 sb;
#else
	struct stat sb;
#endif
1743 1744 1745 1746 1747
    sds content_padded;

    /* 1) Open the old file (or create a new one if it does not
     *    exist), get the size. */
    if (fd == -1) return -1; /* errno set by open(). */
1748
	if (fstat(fd,&sb) == -1) {
1749 1750 1751 1752 1753 1754 1755 1756 1757
        close(fd);
        return -1; /* errno set by fstat(). */
    }

    /* 2) Pad the content at least match the old file size. */
    content_padded = sdsdup(content);
    if (content_size < sb.st_size) {
        /* If the old file was bigger, pad the content with
         * a newline plus as many "#" chars as required. */
1758
        padding = (int)(sb.st_size - content_size);
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
        content_padded = sdsgrowzero(content_padded,sb.st_size);
        content_padded[content_size] = '\n';
        memset(content_padded+content_size+1,'#',padding-1);
    }

    /* 3) Write the new content using a single write(2). */
    if (write(fd,content_padded,strlen(content_padded)) == -1) {
        retval = -1;
        goto cleanup;
    }

    /* 4) Truncate the file to the right length if we used padding. */
    if (padding) {
        if (ftruncate(fd,content_size) == -1) {
            /* Non critical error... */
        }
    }

cleanup:
    sdsfree(content_padded);
    close(fd);
    return retval;
}

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
/* Rewrite the configuration file at "path".
 * If the configuration file already exists, we try at best to retain comments
 * and overall structure.
 *
 * Configuration parameters that are at their default value, unless already
 * explicitly included in the old configuration file, are not rewritten.
 *
 * On error -1 is returned and errno is set accordingly, otherwise 0. */
int rewriteConfig(char *path) {
    struct rewriteConfigState *state;
    sds newcontent;
1794
    int retval;
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

    /* Step 1: read the old config into our rewrite state. */
    if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1;

    /* Step 2: rewrite every single option, replacing or appending it inside
     * the rewrite state. */

    rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0);
    rewriteConfigStringOption(state,"pidfile",server.pidfile,REDIS_DEFAULT_PID_FILE);
    rewriteConfigNumericalOption(state,"port",server.port,REDIS_SERVERPORT);
1805
    rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,REDIS_TCP_BACKLOG);
A
antirez 已提交
1806
    rewriteConfigBindOption(state);
1807
    rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL);
1808 1809 1810
    rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,REDIS_DEFAULT_UNIX_SOCKET_PERM);
    rewriteConfigNumericalOption(state,"timeout",server.maxidletime,REDIS_MAXIDLETIME);
    rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,REDIS_DEFAULT_TCP_KEEPALIVE);
1811 1812 1813 1814 1815
    rewriteConfigEnumOption(state,"loglevel",server.verbosity,
        "debug", REDIS_DEBUG,
        "verbose", REDIS_VERBOSE,
        "notice", REDIS_NOTICE,
        "warning", REDIS_WARNING,
1816 1817 1818
        NULL, REDIS_DEFAULT_VERBOSITY);
    rewriteConfigStringOption(state,"logfile",server.logfile,REDIS_DEFAULT_LOGFILE);
    rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,REDIS_DEFAULT_SYSLOG_ENABLED);
1819
    rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,REDIS_DEFAULT_SYSLOG_IDENT);
1820
#ifndef _WIN32
1821
    rewriteConfigSyslogfacilityOption(state);
1822
#endif
1823 1824
    rewriteConfigSaveOption(state);
    rewriteConfigNumericalOption(state,"databases",server.dbnum,REDIS_DEFAULT_DBNUM);
1825 1826 1827 1828
    rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,REDIS_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR);
    rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,REDIS_DEFAULT_RDB_COMPRESSION);
    rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,REDIS_DEFAULT_RDB_CHECKSUM);
    rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,REDIS_DEFAULT_RDB_FILENAME);
1829 1830 1831
    rewriteConfigDirOption(state);
    rewriteConfigSlaveofOption(state);
    rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL);
1832 1833
    rewriteConfigYesNoOption(state,"slave-serve-stale-data",server.repl_serve_stale_data,REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA);
    rewriteConfigYesNoOption(state,"slave-read-only",server.repl_slave_ro,REDIS_DEFAULT_SLAVE_READ_ONLY);
1834 1835
    rewriteConfigNumericalOption(state,"repl-ping-slave-period",server.repl_ping_slave_period,REDIS_REPL_PING_SLAVE_PERIOD);
    rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,REDIS_REPL_TIMEOUT);
1836
    rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,REDIS_DEFAULT_REPL_BACKLOG_SIZE);
1837
    rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT);
1838
    rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY);
1839
    rewriteConfigYesNoOption(state,"repl-diskless-sync",server.repl_diskless_sync,REDIS_DEFAULT_REPL_DISKLESS_SYNC);
A
antirez 已提交
1840
    rewriteConfigNumericalOption(state,"repl-diskless-sync-delay",server.repl_diskless_sync_delay,REDIS_DEFAULT_REPL_DISKLESS_SYNC_DELAY);
1841
    rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,REDIS_DEFAULT_SLAVE_PRIORITY);
1842 1843
    rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,REDIS_DEFAULT_MIN_SLAVES_TO_WRITE);
    rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,REDIS_DEFAULT_MIN_SLAVES_MAX_LAG);
1844 1845
    rewriteConfigStringOption(state,"requirepass",server.requirepass,NULL);
    rewriteConfigNumericalOption(state,"maxclients",server.maxclients,REDIS_MAX_CLIENTS);
1846
    rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,REDIS_DEFAULT_MAXMEMORY);
1847 1848 1849 1850 1851 1852 1853
    rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy,
        "volatile-lru", REDIS_MAXMEMORY_VOLATILE_LRU,
        "allkeys-lru", REDIS_MAXMEMORY_ALLKEYS_LRU,
        "volatile-random", REDIS_MAXMEMORY_VOLATILE_RANDOM,
        "allkeys-random", REDIS_MAXMEMORY_ALLKEYS_RANDOM,
        "volatile-ttl", REDIS_MAXMEMORY_VOLATILE_TTL,
        "noeviction", REDIS_MAXMEMORY_NO_EVICTION,
1854 1855
        NULL, REDIS_DEFAULT_MAXMEMORY_POLICY);
    rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,REDIS_DEFAULT_MAXMEMORY_SAMPLES);
1856 1857
    rewriteConfigYesNoOption(state,"appendonly",server.aof_state != REDIS_AOF_OFF,0);
    rewriteConfigStringOption(state,"appendfilename",server.aof_filename,REDIS_DEFAULT_AOF_FILENAME);
1858
    rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync,
1859
        "everysec", AOF_FSYNC_EVERYSEC,
1860 1861
        "always", AOF_FSYNC_ALWAYS,
        "no", AOF_FSYNC_NO,
1862 1863
        NULL, REDIS_DEFAULT_AOF_FSYNC);
    rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE);
1864 1865 1866 1867
    rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,REDIS_AOF_REWRITE_PERC);
    rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,REDIS_AOF_REWRITE_MIN_SIZE);
    rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,REDIS_LUA_TIME_LIMIT);
    rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,REDIS_SLOWLOG_LOG_SLOWER_THAN);
1868
    rewriteConfigNumericalOption(state,"latency-monitor-threshold",server.latency_monitor_threshold,REDIS_DEFAULT_LATENCY_MONITOR_THRESHOLD);
1869 1870 1871 1872 1873 1874 1875 1876 1877
    rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,REDIS_SLOWLOG_MAX_LEN);
    rewriteConfigNotifykeyspaceeventsOption(state);
    rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,REDIS_HASH_MAX_ZIPLIST_ENTRIES);
    rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,REDIS_HASH_MAX_ZIPLIST_VALUE);
    rewriteConfigNumericalOption(state,"list-max-ziplist-entries",server.list_max_ziplist_entries,REDIS_LIST_MAX_ZIPLIST_ENTRIES);
    rewriteConfigNumericalOption(state,"list-max-ziplist-value",server.list_max_ziplist_value,REDIS_LIST_MAX_ZIPLIST_VALUE);
    rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,REDIS_SET_MAX_INTSET_ENTRIES);
    rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,REDIS_ZSET_MAX_ZIPLIST_ENTRIES);
    rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,REDIS_ZSET_MAX_ZIPLIST_VALUE);
1878
    rewriteConfigNumericalOption(state,"hll-sparse-max-bytes",server.hll_sparse_max_bytes,REDIS_DEFAULT_HLL_SPARSE_MAX_BYTES);
1879
    rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,REDIS_DEFAULT_ACTIVE_REHASHING);
1880 1881
    rewriteConfigClientoutputbufferlimitOption(state);
    rewriteConfigNumericalOption(state,"hz",server.hz,REDIS_DEFAULT_HZ);
1882
    rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC);
1883
    rewriteConfigYesNoOption(state,"aof-load-truncated",server.aof_load_truncated,REDIS_DEFAULT_AOF_LOAD_TRUNCATED);
1884
    if (server.sentinel_mode) rewriteConfigSentinelOption(state);
1885 1886 1887 1888

    /* Step 3: remove all the orphaned lines in the old file, that is, lines
     * that were used by a config option and are no longer used, like in case
     * of multiple "save" options or duplicated options. */
A
antirez 已提交
1889
    rewriteConfigRemoveOrphaned(state);
1890 1891 1892 1893

    /* Step 4: generate a new configuration file from the modified state
     * and write it into the original file. */
    newcontent = rewriteConfigGetContentFromState(state);
1894
    retval = rewriteConfigOverwriteFile(server.configfile,newcontent);
1895 1896 1897

    sdsfree(newcontent);
    rewriteConfigReleaseState(state);
1898
    return retval;
1899 1900 1901 1902 1903 1904
}

/*-----------------------------------------------------------------------------
 * CONFIG command entry point
 *----------------------------------------------------------------------------*/

1905 1906 1907 1908 1909 1910 1911 1912 1913
void configCommand(redisClient *c) {
    if (!strcasecmp(c->argv[1]->ptr,"set")) {
        if (c->argc != 4) goto badarity;
        configSetCommand(c);
    } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
        if (c->argc != 3) goto badarity;
        configGetCommand(c);
    } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
        if (c->argc != 2) goto badarity;
1914
        resetServerStats();
1915
        resetCommandTableStats();
1916
        addReply(c,shared.ok);
1917 1918 1919 1920 1921 1922 1923
    } else if (!strcasecmp(c->argv[1]->ptr,"rewrite")) {
        if (c->argc != 2) goto badarity;
        if (server.configfile == NULL) {
            addReplyError(c,"The server is running without a config file");
            return;
        }
        if (rewriteConfig(server.configfile) == -1) {
A
antirez 已提交
1924
            redisLog(REDIS_WARNING,"CONFIG REWRITE failed: %s", strerror(errno));
1925 1926
            addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno));
        } else {
1927
            redisLog(REDIS_WARNING,"CONFIG REWRITE executed with success.");
1928 1929
            addReply(c,shared.ok);
        }
1930
    } else {
1931
        addReplyError(c,
1932
            "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE");
1933 1934 1935 1936
    }
    return;

badarity:
1937 1938
    addReplyErrorFormat(c,"Wrong number of arguments for CONFIG %s",
        (char*) c->argv[1]->ptr);
1939
}