1 /* Configuration file parsing and CONFIG GET/SET commands implementation. 2 * 3 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions are met: 8 * 9 * * Redistributions of source code must retain the above copyright notice, 10 * this list of conditions and the following disclaimer. 11 * * Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * * Neither the name of Redis nor the names of its contributors may be used 15 * to endorse or promote products derived from this software without 16 * specific prior written permission. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 * POSSIBILITY OF SUCH DAMAGE. 29 */ 30 31 #include "redis.h" 32 #include "cluster.h" 33 34 #include <fcntl.h> 35 #include <sys/stat.h> 36 37 static struct { 38 const char *name; 39 const int value; 40 } validSyslogFacilities[] = { 41 {"user", LOG_USER}, 42 {"local0", LOG_LOCAL0}, 43 {"local1", LOG_LOCAL1}, 44 {"local2", LOG_LOCAL2}, 45 {"local3", LOG_LOCAL3}, 46 {"local4", LOG_LOCAL4}, 47 {"local5", LOG_LOCAL5}, 48 {"local6", LOG_LOCAL6}, 49 {"local7", LOG_LOCAL7}, 50 {NULL, 0} 51 }; 52 53 clientBufferLimitsConfig clientBufferLimitsDefaults[REDIS_CLIENT_LIMIT_NUM_CLASSES] = { 54 {0, 0, 0}, /* normal */ 55 {1024*1024*256, 1024*1024*64, 60}, /* slave */ 56 {1024*1024*32, 1024*1024*8, 60} /* pubsub */ 57 }; 58 59 /*----------------------------------------------------------------------------- 60 * Config file parsing 61 *----------------------------------------------------------------------------*/ 62 63 int yesnotoi(char *s) { 64 if (!strcasecmp(s,"yes")) return 1; 65 else if (!strcasecmp(s,"no")) return 0; 66 else return -1; 67 } 68 69 void appendServerSaveParams(time_t seconds, int changes) { 70 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1)); 71 server.saveparams[server.saveparamslen].seconds = seconds; 72 server.saveparams[server.saveparamslen].changes = changes; 73 server.saveparamslen++; 74 } 75 76 void resetServerSaveParams() { 77 zfree(server.saveparams); 78 server.saveparams = NULL; 79 server.saveparamslen = 0; 80 } 81 82 void loadServerConfigFromString(char *config) { 83 char *err = NULL; 84 int linenum = 0, totlines, i; 85 int slaveof_linenum = 0; 86 sds *lines; 87 88 lines = sdssplitlen(config,strlen(config),"\n",1,&totlines); 89 90 for (i = 0; i < totlines; i++) { 91 sds *argv; 92 int argc; 93 94 linenum = i+1; 95 lines[i] = sdstrim(lines[i]," \t\r\n"); 96 97 /* Skip comments and blank lines */ 98 if (lines[i][0] == '#' || lines[i][0] == '\0') continue; 99 100 /* Split into arguments */ 101 argv = sdssplitargs(lines[i],&argc); 102 if (argv == NULL) { 103 err = "Unbalanced quotes in configuration line"; 104 goto loaderr; 105 } 106 107 /* Skip this line if the resulting command vector is empty. */ 108 if (argc == 0) { 109 sdsfreesplitres(argv,argc); 110 continue; 111 } 112 sdstolower(argv[0]); 113 114 /* Execute config directives */ 115 if (!strcasecmp(argv[0],"timeout") && argc == 2) { 116 server.maxidletime = atoi(argv[1]); 117 if (server.maxidletime < 0) { 118 err = "Invalid timeout value"; goto loaderr; 119 } 120 } else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) { 121 server.tcpkeepalive = atoi(argv[1]); 122 if (server.tcpkeepalive < 0) { 123 err = "Invalid tcp-keepalive value"; goto loaderr; 124 } 125 } else if (!strcasecmp(argv[0],"port") && argc == 2) { 126 server.port = atoi(argv[1]); 127 if (server.port < 0 || server.port > 65535) { 128 err = "Invalid port"; goto loaderr; 129 } 130 } else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) { 131 server.tcp_backlog = atoi(argv[1]); 132 if (server.tcp_backlog < 0) { 133 err = "Invalid backlog value"; goto loaderr; 134 } 135 } else if (!strcasecmp(argv[0],"bind") && argc >= 2) { 136 int j, addresses = argc-1; 137 138 if (addresses > REDIS_BINDADDR_MAX) { 139 err = "Too many bind addresses specified"; goto loaderr; 140 } 141 for (j = 0; j < addresses; j++) 142 server.bindaddr[j] = zstrdup(argv[j+1]); 143 server.bindaddr_count = addresses; 144 } else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) { 145 server.unixsocket = zstrdup(argv[1]); 146 } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) { 147 errno = 0; 148 server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8); 149 if (errno || server.unixsocketperm > 0777) { 150 err = "Invalid socket file permissions"; goto loaderr; 151 } 152 } else if (!strcasecmp(argv[0],"save")) { 153 if (argc == 3) { 154 int seconds = atoi(argv[1]); 155 int changes = atoi(argv[2]); 156 if (seconds < 1 || changes < 0) { 157 err = "Invalid save parameters"; goto loaderr; 158 } 159 appendServerSaveParams(seconds,changes); 160 } else if (argc == 2 && !strcasecmp(argv[1],"")) { 161 resetServerSaveParams(); 162 } 163 } else if (!strcasecmp(argv[0],"dir") && argc == 2) { 164 if (chdir(argv[1]) == -1) { 165 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s", 166 argv[1], strerror(errno)); 167 exit(1); 168 } 169 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) { 170 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG; 171 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE; 172 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE; 173 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING; 174 else { 175 err = "Invalid log level. Must be one of debug, notice, warning"; 176 goto loaderr; 177 } 178 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) { 179 FILE *logfp; 180 181 zfree(server.logfile); 182 server.logfile = zstrdup(argv[1]); 183 if (server.logfile[0] != '\0') { 184 /* Test if we are able to open the file. The server will not 185 * be able to abort just for this problem later... */ 186 logfp = fopen(server.logfile,"a"); 187 if (logfp == NULL) { 188 err = sdscatprintf(sdsempty(), 189 "Can't open the log file: %s", strerror(errno)); 190 goto loaderr; 191 } 192 fclose(logfp); 193 } 194 } else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) { 195 if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) { 196 err = "argument must be 'yes' or 'no'"; goto loaderr; 197 } 198 } else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) { 199 if (server.syslog_ident) zfree(server.syslog_ident); 200 server.syslog_ident = zstrdup(argv[1]); 201 } else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) { 202 int i; 203 204 for (i = 0; validSyslogFacilities[i].name; i++) { 205 if (!strcasecmp(validSyslogFacilities[i].name, argv[1])) { 206 server.syslog_facility = validSyslogFacilities[i].value; 207 break; 208 } 209 } 210 211 if (!validSyslogFacilities[i].name) { 212 err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7"; 213 goto loaderr; 214 } 215 } else if (!strcasecmp(argv[0],"databases") && argc == 2) { 216 server.dbnum = atoi(argv[1]); 217 if (server.dbnum < 1) { 218 err = "Invalid number of databases"; goto loaderr; 219 } 220 } else if (!strcasecmp(argv[0],"include") && argc == 2) { 221 loadServerConfig(argv[1],NULL); 222 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) { 223 server.maxclients = atoi(argv[1]); 224 if (server.maxclients < 1) { 225 err = "Invalid max clients limit"; goto loaderr; 226 } 227 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) { 228 server.maxmemory = memtoll(argv[1],NULL); 229 } else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) { 230 if (!strcasecmp(argv[1],"volatile-lru")) { 231 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; 232 } else if (!strcasecmp(argv[1],"volatile-random")) { 233 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM; 234 } else if (!strcasecmp(argv[1],"volatile-ttl")) { 235 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL; 236 } else if (!strcasecmp(argv[1],"allkeys-lru")) { 237 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU; 238 } else if (!strcasecmp(argv[1],"allkeys-random")) { 239 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM; 240 } else if (!strcasecmp(argv[1],"noeviction")) { 241 server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION; 242 } else { 243 err = "Invalid maxmemory policy"; 244 goto loaderr; 245 } 246 } else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) { 247 server.maxmemory_samples = atoi(argv[1]); 248 if (server.maxmemory_samples <= 0) { 249 err = "maxmemory-samples must be 1 or greater"; 250 goto loaderr; 251 } 252 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) { 253 slaveof_linenum = linenum; 254 server.masterhost = sdsnew(argv[1]); 255 server.masterport = atoi(argv[2]); 256 server.repl_state = REDIS_REPL_CONNECT; 257 } else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) { 258 server.repl_ping_slave_period = atoi(argv[1]); 259 if (server.repl_ping_slave_period <= 0) { 260 err = "repl-ping-slave-period must be 1 or greater"; 261 goto loaderr; 262 } 263 } else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) { 264 server.repl_timeout = atoi(argv[1]); 265 if (server.repl_timeout <= 0) { 266 err = "repl-timeout must be 1 or greater"; 267 goto loaderr; 268 } 269 } else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) { 270 if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) { 271 err = "argument must be 'yes' or 'no'"; goto loaderr; 272 } 273 } else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) { 274 long long size = memtoll(argv[1],NULL); 275 if (size <= 0) { 276 err = "repl-backlog-size must be 1 or greater."; 277 goto loaderr; 278 } 279 resizeReplicationBacklog(size); 280 } else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) { 281 server.repl_backlog_time_limit = atoi(argv[1]); 282 if (server.repl_backlog_time_limit < 0) { 283 err = "repl-backlog-ttl can't be negative "; 284 goto loaderr; 285 } 286 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) { 287 server.masterauth = zstrdup(argv[1]); 288 } else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) { 289 if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) { 290 err = "argument must be 'yes' or 'no'"; goto loaderr; 291 } 292 } else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) { 293 if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) { 294 err = "argument must be 'yes' or 'no'"; goto loaderr; 295 } 296 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) { 297 if ((server.rdb_compression = yesnotoi(argv[1])) == -1) { 298 err = "argument must be 'yes' or 'no'"; goto loaderr; 299 } 300 } else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) { 301 if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) { 302 err = "argument must be 'yes' or 'no'"; goto loaderr; 303 } 304 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) { 305 if ((server.activerehashing = yesnotoi(argv[1])) == -1) { 306 err = "argument must be 'yes' or 'no'"; goto loaderr; 307 } 308 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) { 309 if ((server.daemonize = yesnotoi(argv[1])) == -1) { 310 err = "argument must be 'yes' or 'no'"; goto loaderr; 311 } 312 } else if (!strcasecmp(argv[0],"hz") && argc == 2) { 313 server.hz = atoi(argv[1]); 314 if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ; 315 if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ; 316 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) { 317 int yes; 318 319 if ((yes = yesnotoi(argv[1])) == -1) { 320 err = "argument must be 'yes' or 'no'"; goto loaderr; 321 } 322 server.aof_state = yes ? REDIS_AOF_ON : REDIS_AOF_OFF; 323 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) { 324 if (!pathIsBaseName(argv[1])) { 325 err = "appendfilename can't be a path, just a filename"; 326 goto loaderr; 327 } 328 zfree(server.aof_filename); 329 server.aof_filename = zstrdup(argv[1]); 330 } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite") 331 && argc == 2) { 332 if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) { 333 err = "argument must be 'yes' or 'no'"; goto loaderr; 334 } 335 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) { 336 if (!strcasecmp(argv[1],"no")) { 337 server.aof_fsync = AOF_FSYNC_NO; 338 } else if (!strcasecmp(argv[1],"always")) { 339 server.aof_fsync = AOF_FSYNC_ALWAYS; 340 } else if (!strcasecmp(argv[1],"everysec")) { 341 server.aof_fsync = AOF_FSYNC_EVERYSEC; 342 } else { 343 err = "argument must be 'no', 'always' or 'everysec'"; 344 goto loaderr; 345 } 346 } else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") && 347 argc == 2) 348 { 349 server.aof_rewrite_perc = atoi(argv[1]); 350 if (server.aof_rewrite_perc < 0) { 351 err = "Invalid negative percentage for AOF auto rewrite"; 352 goto loaderr; 353 } 354 } else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") && 355 argc == 2) 356 { 357 server.aof_rewrite_min_size = memtoll(argv[1],NULL); 358 } else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") && 359 argc == 2) 360 { 361 if ((server.aof_rewrite_incremental_fsync = yesnotoi(argv[1])) == -1) { 362 err = "argument must be 'yes' or 'no'"; goto loaderr; 363 } 364 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) { 365 if (strlen(argv[1]) > REDIS_AUTHPASS_MAX_LEN) { 366 err = "Password is longer than REDIS_AUTHPASS_MAX_LEN"; 367 goto loaderr; 368 } 369 server.requirepass = zstrdup(argv[1]); 370 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) { 371 zfree(server.pidfile); 372 server.pidfile = zstrdup(argv[1]); 373 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) { 374 if (!pathIsBaseName(argv[1])) { 375 err = "dbfilename can't be a path, just a filename"; 376 goto loaderr; 377 } 378 zfree(server.rdb_filename); 379 server.rdb_filename = zstrdup(argv[1]); 380 } else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) { 381 server.hash_max_ziplist_entries = memtoll(argv[1], NULL); 382 } else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) { 383 server.hash_max_ziplist_value = memtoll(argv[1], NULL); 384 } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){ 385 server.list_max_ziplist_entries = memtoll(argv[1], NULL); 386 } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) { 387 server.list_max_ziplist_value = memtoll(argv[1], NULL); 388 } else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) { 389 server.set_max_intset_entries = memtoll(argv[1], NULL); 390 } else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) { 391 server.zset_max_ziplist_entries = memtoll(argv[1], NULL); 392 } else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) { 393 server.zset_max_ziplist_value = memtoll(argv[1], NULL); 394 } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) { 395 struct redisCommand *cmd = lookupCommand(argv[1]); 396 int retval; 397 398 if (!cmd) { 399 err = "No such command in rename-command"; 400 goto loaderr; 401 } 402 403 /* If the target command name is the empty string we just 404 * remove it from the command table. */ 405 retval = dictDelete(server.commands, argv[1]); 406 redisAssert(retval == DICT_OK); 407 408 /* Otherwise we re-add the command under a different name. */ 409 if (sdslen(argv[2]) != 0) { 410 sds copy = sdsdup(argv[2]); 411 412 retval = dictAdd(server.commands, copy, cmd); 413 if (retval != DICT_OK) { 414 sdsfree(copy); 415 err = "Target command name already exists"; goto loaderr; 416 } 417 } 418 } else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) { 419 if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) { 420 err = "argument must be 'yes' or 'no'"; goto loaderr; 421 } 422 } else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) { 423 zfree(server.cluster_configfile); 424 server.cluster_configfile = zstrdup(argv[1]); 425 } else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) { 426 server.cluster_node_timeout = strtoll(argv[1],NULL,10); 427 if (server.cluster_node_timeout <= 0) { 428 err = "cluster node timeout must be 1 or greater"; goto loaderr; 429 } 430 } else if (!strcasecmp(argv[0],"cluster-migration-barrier") 431 && argc == 2) 432 { 433 server.cluster_migration_barrier = atoi(argv[1]); 434 if (server.cluster_migration_barrier < 0) { 435 err = "cluster migration barrier must be positive"; 436 goto loaderr; 437 } 438 } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) { 439 server.lua_time_limit = strtoll(argv[1],NULL,10); 440 } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") && 441 argc == 2) 442 { 443 server.slowlog_log_slower_than = strtoll(argv[1],NULL,10); 444 } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) { 445 server.slowlog_max_len = strtoll(argv[1],NULL,10); 446 } else if (!strcasecmp(argv[0],"client-output-buffer-limit") && 447 argc == 5) 448 { 449 int class = getClientLimitClassByName(argv[1]); 450 unsigned long long hard, soft; 451 int soft_seconds; 452 453 if (class == -1) { 454 err = "Unrecognized client limit class"; 455 goto loaderr; 456 } 457 hard = memtoll(argv[2],NULL); 458 soft = memtoll(argv[3],NULL); 459 soft_seconds = atoi(argv[4]); 460 if (soft_seconds < 0) { 461 err = "Negative number of seconds in soft limit is invalid"; 462 goto loaderr; 463 } 464 server.client_obuf_limits[class].hard_limit_bytes = hard; 465 server.client_obuf_limits[class].soft_limit_bytes = soft; 466 server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; 467 } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") && 468 argc == 2) { 469 if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) { 470 err = "argument must be 'yes' or 'no'"; goto loaderr; 471 } 472 } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) { 473 server.slave_priority = atoi(argv[1]); 474 } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) { 475 server.repl_min_slaves_to_write = atoi(argv[1]); 476 if (server.repl_min_slaves_to_write < 0) { 477 err = "Invalid value for min-slaves-to-write."; goto loaderr; 478 } 479 } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) { 480 server.repl_min_slaves_max_lag = atoi(argv[1]); 481 if (server.repl_min_slaves_max_lag < 0) { 482 err = "Invalid value for min-slaves-max-lag."; goto loaderr; 483 } 484 } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) { 485 int flags = keyspaceEventsStringToFlags(argv[1]); 486 487 if (flags == -1) { 488 err = "Invalid event class character. Use 'g$lshzxeA'."; 489 goto loaderr; 490 } 491 server.notify_keyspace_events = flags; 492 } else if (!strcasecmp(argv[0],"sentinel")) { 493 /* argc == 1 is handled by main() as we need to enter the sentinel 494 * mode ASAP. */ 495 if (argc != 1) { 496 if (!server.sentinel_mode) { 497 err = "sentinel directive while not in sentinel mode"; 498 goto loaderr; 499 } 500 err = sentinelHandleConfiguration(argv+1,argc-1); 501 if (err) goto loaderr; 502 } 503 } else { 504 err = "Bad directive or wrong number of arguments"; goto loaderr; 505 } 506 sdsfreesplitres(argv,argc); 507 } 508 509 /* Sanity checks. */ 510 if (server.cluster_enabled && server.masterhost) { 511 linenum = slaveof_linenum; 512 i = linenum-1; 513 err = "slaveof directive not allowed in cluster mode"; 514 goto loaderr; 515 } 516 517 sdsfreesplitres(lines,totlines); 518 return; 519 520 loaderr: 521 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n"); 522 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum); 523 fprintf(stderr, ">>> '%s'\n", lines[i]); 524 fprintf(stderr, "%s\n", err); 525 exit(1); 526 } 527 528 /* Load the server configuration from the specified filename. 529 * The function appends the additional configuration directives stored 530 * in the 'options' string to the config file before loading. 531 * 532 * Both filename and options can be NULL, in such a case are considered 533 * empty. This way loadServerConfig can be used to just load a file or 534 * just load a string. */ 535 void loadServerConfig(char *filename, char *options) { 536 sds config = sdsempty(); 537 char buf[REDIS_CONFIGLINE_MAX+1]; 538 539 /* Load the file content */ 540 if (filename) { 541 FILE *fp; 542 543 if (filename[0] == '-' && filename[1] == '\0') { 544 fp = stdin; 545 } else { 546 if ((fp = fopen(filename,"r")) == NULL) { 547 redisLog(REDIS_WARNING, 548 "Fatal error, can't open config file '%s'", filename); 549 exit(1); 550 } 551 } 552 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) 553 config = sdscat(config,buf); 554 if (fp != stdin) fclose(fp); 555 } 556 /* Append the additional options */ 557 if (options) { 558 config = sdscat(config,"\n"); 559 config = sdscat(config,options); 560 } 561 loadServerConfigFromString(config); 562 sdsfree(config); 563 } 564 565 /*----------------------------------------------------------------------------- 566 * CONFIG SET implementation 567 *----------------------------------------------------------------------------*/ 568 569 void configSetCommand(redisClient *c) { 570 robj *o; 571 long long ll; 572 redisAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2])); 573 redisAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3])); 574 o = c->argv[3]; 575 576 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) { 577 if (!pathIsBaseName(o->ptr)) { 578 addReplyError(c, "dbfilename can't be a path, just a filename"); 579 return; 580 } 581 zfree(server.rdb_filename); 582 server.rdb_filename = zstrdup(o->ptr); 583 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) { 584 if (sdslen(o->ptr) > REDIS_AUTHPASS_MAX_LEN) goto badfmt; 585 zfree(server.requirepass); 586 server.requirepass = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; 587 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) { 588 zfree(server.masterauth); 589 server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; 590 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) { 591 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 592 ll < 0) goto badfmt; 593 server.maxmemory = ll; 594 if (server.maxmemory) { 595 if (server.maxmemory < zmalloc_used_memory()) { 596 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."); 597 } 598 freeMemoryIfNeeded(); 599 } 600 } else if (!strcasecmp(c->argv[2]->ptr,"maxclients")) { 601 int orig_value = server.maxclients; 602 603 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 604 605 /* Try to check if the OS is capable of supporting so many FDs. */ 606 server.maxclients = ll; 607 if (ll > orig_value) { 608 adjustOpenFilesLimit(); 609 if (server.maxclients != ll) { 610 addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients); 611 server.maxclients = orig_value; 612 return; 613 } 614 if (aeGetSetSize(server.el) < 615 server.maxclients + REDIS_EVENTLOOP_FDSET_INCR) 616 { 617 if (aeResizeSetSize(server.el, 618 server.maxclients + REDIS_EVENTLOOP_FDSET_INCR) == AE_ERR) 619 { 620 addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients"); 621 server.maxclients = orig_value; 622 return; 623 } 624 } 625 } 626 } else if (!strcasecmp(c->argv[2]->ptr,"hz")) { 627 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 628 server.hz = ll; 629 if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ; 630 if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ; 631 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-policy")) { 632 if (!strcasecmp(o->ptr,"volatile-lru")) { 633 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; 634 } else if (!strcasecmp(o->ptr,"volatile-random")) { 635 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM; 636 } else if (!strcasecmp(o->ptr,"volatile-ttl")) { 637 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL; 638 } else if (!strcasecmp(o->ptr,"allkeys-lru")) { 639 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU; 640 } else if (!strcasecmp(o->ptr,"allkeys-random")) { 641 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM; 642 } else if (!strcasecmp(o->ptr,"noeviction")) { 643 server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION; 644 } else { 645 goto badfmt; 646 } 647 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-samples")) { 648 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 649 ll <= 0) goto badfmt; 650 server.maxmemory_samples = ll; 651 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) { 652 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 653 ll < 0 || ll > LONG_MAX) goto badfmt; 654 server.maxidletime = ll; 655 } else if (!strcasecmp(c->argv[2]->ptr,"tcp-keepalive")) { 656 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 657 ll < 0 || ll > INT_MAX) goto badfmt; 658 server.tcpkeepalive = ll; 659 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) { 660 if (!strcasecmp(o->ptr,"no")) { 661 server.aof_fsync = AOF_FSYNC_NO; 662 } else if (!strcasecmp(o->ptr,"everysec")) { 663 server.aof_fsync = AOF_FSYNC_EVERYSEC; 664 } else if (!strcasecmp(o->ptr,"always")) { 665 server.aof_fsync = AOF_FSYNC_ALWAYS; 666 } else { 667 goto badfmt; 668 } 669 } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) { 670 int yn = yesnotoi(o->ptr); 671 672 if (yn == -1) goto badfmt; 673 server.aof_no_fsync_on_rewrite = yn; 674 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) { 675 int enable = yesnotoi(o->ptr); 676 677 if (enable == -1) goto badfmt; 678 if (enable == 0 && server.aof_state != REDIS_AOF_OFF) { 679 stopAppendOnly(); 680 } else if (enable && server.aof_state == REDIS_AOF_OFF) { 681 if (startAppendOnly() == REDIS_ERR) { 682 addReplyError(c, 683 "Unable to turn on AOF. Check server logs."); 684 return; 685 } 686 } 687 } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-percentage")) { 688 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 689 server.aof_rewrite_perc = ll; 690 } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-min-size")) { 691 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 692 server.aof_rewrite_min_size = ll; 693 } else if (!strcasecmp(c->argv[2]->ptr,"aof-rewrite-incremental-fsync")) { 694 int yn = yesnotoi(o->ptr); 695 696 if (yn == -1) goto badfmt; 697 server.aof_rewrite_incremental_fsync = yn; 698 } else if (!strcasecmp(c->argv[2]->ptr,"save")) { 699 int vlen, j; 700 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); 701 702 /* Perform sanity check before setting the new config: 703 * - Even number of args 704 * - Seconds >= 1, changes >= 0 */ 705 if (vlen & 1) { 706 sdsfreesplitres(v,vlen); 707 goto badfmt; 708 } 709 for (j = 0; j < vlen; j++) { 710 char *eptr; 711 long val; 712 713 val = strtoll(v[j], &eptr, 10); 714 if (eptr[0] != '\0' || 715 ((j & 1) == 0 && val < 1) || 716 ((j & 1) == 1 && val < 0)) { 717 sdsfreesplitres(v,vlen); 718 goto badfmt; 719 } 720 } 721 /* Finally set the new config */ 722 resetServerSaveParams(); 723 for (j = 0; j < vlen; j += 2) { 724 time_t seconds; 725 int changes; 726 727 seconds = strtoll(v[j],NULL,10); 728 changes = strtoll(v[j+1],NULL,10); 729 appendServerSaveParams(seconds, changes); 730 } 731 sdsfreesplitres(v,vlen); 732 } else if (!strcasecmp(c->argv[2]->ptr,"slave-serve-stale-data")) { 733 int yn = yesnotoi(o->ptr); 734 735 if (yn == -1) goto badfmt; 736 server.repl_serve_stale_data = yn; 737 } else if (!strcasecmp(c->argv[2]->ptr,"slave-read-only")) { 738 int yn = yesnotoi(o->ptr); 739 740 if (yn == -1) goto badfmt; 741 server.repl_slave_ro = yn; 742 } else if (!strcasecmp(c->argv[2]->ptr,"dir")) { 743 if (chdir((char*)o->ptr) == -1) { 744 addReplyErrorFormat(c,"Changing directory: %s", strerror(errno)); 745 return; 746 } 747 } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-entries")) { 748 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 749 server.hash_max_ziplist_entries = ll; 750 } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-value")) { 751 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 752 server.hash_max_ziplist_value = ll; 753 } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-entries")) { 754 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 755 server.list_max_ziplist_entries = ll; 756 } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-value")) { 757 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 758 server.list_max_ziplist_value = ll; 759 } else if (!strcasecmp(c->argv[2]->ptr,"set-max-intset-entries")) { 760 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 761 server.set_max_intset_entries = ll; 762 } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-entries")) { 763 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 764 server.zset_max_ziplist_entries = ll; 765 } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-value")) { 766 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 767 server.zset_max_ziplist_value = ll; 768 } else if (!strcasecmp(c->argv[2]->ptr,"lua-time-limit")) { 769 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 770 server.lua_time_limit = ll; 771 } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-log-slower-than")) { 772 if (getLongLongFromObject(o,&ll) == REDIS_ERR) goto badfmt; 773 server.slowlog_log_slower_than = ll; 774 } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-max-len")) { 775 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 776 server.slowlog_max_len = (unsigned)ll; 777 } else if (!strcasecmp(c->argv[2]->ptr,"loglevel")) { 778 if (!strcasecmp(o->ptr,"warning")) { 779 server.verbosity = REDIS_WARNING; 780 } else if (!strcasecmp(o->ptr,"notice")) { 781 server.verbosity = REDIS_NOTICE; 782 } else if (!strcasecmp(o->ptr,"verbose")) { 783 server.verbosity = REDIS_VERBOSE; 784 } else if (!strcasecmp(o->ptr,"debug")) { 785 server.verbosity = REDIS_DEBUG; 786 } else { 787 goto badfmt; 788 } 789 } else if (!strcasecmp(c->argv[2]->ptr,"client-output-buffer-limit")) { 790 int vlen, j; 791 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); 792 793 /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */ 794 if (vlen % 4) { 795 sdsfreesplitres(v,vlen); 796 goto badfmt; 797 } 798 799 /* Sanity check of single arguments, so that we either refuse the 800 * whole configuration string or accept it all, even if a single 801 * error in a single client class is present. */ 802 for (j = 0; j < vlen; j++) { 803 char *eptr; 804 long val; 805 806 if ((j % 4) == 0) { 807 if (getClientLimitClassByName(v[j]) == -1) { 808 sdsfreesplitres(v,vlen); 809 goto badfmt; 810 } 811 } else { 812 val = strtoll(v[j], &eptr, 10); 813 if (eptr[0] != '\0' || val < 0) { 814 sdsfreesplitres(v,vlen); 815 goto badfmt; 816 } 817 } 818 } 819 /* Finally set the new config */ 820 for (j = 0; j < vlen; j += 4) { 821 int class; 822 unsigned long long hard, soft; 823 int soft_seconds; 824 825 class = getClientLimitClassByName(v[j]); 826 hard = strtoll(v[j+1],NULL,10); 827 soft = strtoll(v[j+2],NULL,10); 828 soft_seconds = strtoll(v[j+3],NULL,10); 829 830 server.client_obuf_limits[class].hard_limit_bytes = hard; 831 server.client_obuf_limits[class].soft_limit_bytes = soft; 832 server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; 833 } 834 sdsfreesplitres(v,vlen); 835 } else if (!strcasecmp(c->argv[2]->ptr,"stop-writes-on-bgsave-error")) { 836 int yn = yesnotoi(o->ptr); 837 838 if (yn == -1) goto badfmt; 839 server.stop_writes_on_bgsave_err = yn; 840 } else if (!strcasecmp(c->argv[2]->ptr,"repl-ping-slave-period")) { 841 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt; 842 server.repl_ping_slave_period = ll; 843 } else if (!strcasecmp(c->argv[2]->ptr,"repl-timeout")) { 844 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt; 845 server.repl_timeout = ll; 846 } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-size")) { 847 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt; 848 resizeReplicationBacklog(ll); 849 } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-ttl")) { 850 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 851 server.repl_backlog_time_limit = ll; 852 } else if (!strcasecmp(c->argv[2]->ptr,"watchdog-period")) { 853 if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt; 854 if (ll) 855 enableWatchdog(ll); 856 else 857 disableWatchdog(); 858 } else if (!strcasecmp(c->argv[2]->ptr,"rdbcompression")) { 859 int yn = yesnotoi(o->ptr); 860 861 if (yn == -1) goto badfmt; 862 server.rdb_compression = yn; 863 } else if (!strcasecmp(c->argv[2]->ptr,"notify-keyspace-events")) { 864 int flags = keyspaceEventsStringToFlags(o->ptr); 865 866 if (flags == -1) goto badfmt; 867 server.notify_keyspace_events = flags; 868 } else if (!strcasecmp(c->argv[2]->ptr,"repl-disable-tcp-nodelay")) { 869 int yn = yesnotoi(o->ptr); 870 871 if (yn == -1) goto badfmt; 872 server.repl_disable_tcp_nodelay = yn; 873 } else if (!strcasecmp(c->argv[2]->ptr,"slave-priority")) { 874 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 875 ll < 0) goto badfmt; 876 server.slave_priority = ll; 877 } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-to-write")) { 878 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 879 ll < 0) goto badfmt; 880 server.repl_min_slaves_to_write = ll; 881 refreshGoodSlavesCount(); 882 } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-max-lag")) { 883 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 884 ll < 0) goto badfmt; 885 server.repl_min_slaves_max_lag = ll; 886 refreshGoodSlavesCount(); 887 } else if (!strcasecmp(c->argv[2]->ptr,"cluster-node-timeout")) { 888 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 889 ll <= 0) goto badfmt; 890 server.cluster_node_timeout = ll; 891 } else if (!strcasecmp(c->argv[2]->ptr,"cluster-migration-barrier")) { 892 if (getLongLongFromObject(o,&ll) == REDIS_ERR || 893 ll < 0) goto badfmt; 894 server.cluster_migration_barrier = ll; 895 } else { 896 addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s", 897 (char*)c->argv[2]->ptr); 898 return; 899 } 900 addReply(c,shared.ok); 901 return; 902 903 badfmt: /* Bad format errors */ 904 addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'", 905 (char*)o->ptr, 906 (char*)c->argv[2]->ptr); 907 } 908 909 /*----------------------------------------------------------------------------- 910 * CONFIG GET implementation 911 *----------------------------------------------------------------------------*/ 912 913 #define config_get_string_field(_name,_var) do { \ 914 if (stringmatch(pattern,_name,0)) { \ 915 addReplyBulkCString(c,_name); \ 916 addReplyBulkCString(c,_var ? _var : ""); \ 917 matches++; \ 918 } \ 919 } while(0); 920 921 #define config_get_bool_field(_name,_var) do { \ 922 if (stringmatch(pattern,_name,0)) { \ 923 addReplyBulkCString(c,_name); \ 924 addReplyBulkCString(c,_var ? "yes" : "no"); \ 925 matches++; \ 926 } \ 927 } while(0); 928 929 #define config_get_numerical_field(_name,_var) do { \ 930 if (stringmatch(pattern,_name,0)) { \ 931 ll2string(buf,sizeof(buf),_var); \ 932 addReplyBulkCString(c,_name); \ 933 addReplyBulkCString(c,buf); \ 934 matches++; \ 935 } \ 936 } while(0); 937 938 void configGetCommand(redisClient *c) { 939 robj *o = c->argv[2]; 940 void *replylen = addDeferredMultiBulkLength(c); 941 char *pattern = o->ptr; 942 char buf[128]; 943 int matches = 0; 944 redisAssertWithInfo(c,o,sdsEncodedObject(o)); 945 946 /* String values */ 947 config_get_string_field("dbfilename",server.rdb_filename); 948 config_get_string_field("requirepass",server.requirepass); 949 config_get_string_field("masterauth",server.masterauth); 950 config_get_string_field("unixsocket",server.unixsocket); 951 config_get_string_field("logfile",server.logfile); 952 config_get_string_field("pidfile",server.pidfile); 953 954 /* Numerical values */ 955 config_get_numerical_field("maxmemory",server.maxmemory); 956 config_get_numerical_field("maxmemory-samples",server.maxmemory_samples); 957 config_get_numerical_field("timeout",server.maxidletime); 958 config_get_numerical_field("tcp-keepalive",server.tcpkeepalive); 959 config_get_numerical_field("auto-aof-rewrite-percentage", 960 server.aof_rewrite_perc); 961 config_get_numerical_field("auto-aof-rewrite-min-size", 962 server.aof_rewrite_min_size); 963 config_get_numerical_field("hash-max-ziplist-entries", 964 server.hash_max_ziplist_entries); 965 config_get_numerical_field("hash-max-ziplist-value", 966 server.hash_max_ziplist_value); 967 config_get_numerical_field("list-max-ziplist-entries", 968 server.list_max_ziplist_entries); 969 config_get_numerical_field("list-max-ziplist-value", 970 server.list_max_ziplist_value); 971 config_get_numerical_field("set-max-intset-entries", 972 server.set_max_intset_entries); 973 config_get_numerical_field("zset-max-ziplist-entries", 974 server.zset_max_ziplist_entries); 975 config_get_numerical_field("zset-max-ziplist-value", 976 server.zset_max_ziplist_value); 977 config_get_numerical_field("lua-time-limit",server.lua_time_limit); 978 config_get_numerical_field("slowlog-log-slower-than", 979 server.slowlog_log_slower_than); 980 config_get_numerical_field("slowlog-max-len", 981 server.slowlog_max_len); 982 config_get_numerical_field("port",server.port); 983 config_get_numerical_field("tcp-backlog",server.tcp_backlog); 984 config_get_numerical_field("databases",server.dbnum); 985 config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period); 986 config_get_numerical_field("repl-timeout",server.repl_timeout); 987 config_get_numerical_field("repl-backlog-size",server.repl_backlog_size); 988 config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit); 989 config_get_numerical_field("maxclients",server.maxclients); 990 config_get_numerical_field("watchdog-period",server.watchdog_period); 991 config_get_numerical_field("slave-priority",server.slave_priority); 992 config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write); 993 config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag); 994 config_get_numerical_field("hz",server.hz); 995 config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout); 996 config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier); 997 998 /* Bool (yes/no) values */ 999 config_get_bool_field("no-appendfsync-on-rewrite", 1000 server.aof_no_fsync_on_rewrite); 1001 config_get_bool_field("slave-serve-stale-data", 1002 server.repl_serve_stale_data); 1003 config_get_bool_field("slave-read-only", 1004 server.repl_slave_ro); 1005 config_get_bool_field("stop-writes-on-bgsave-error", 1006 server.stop_writes_on_bgsave_err); 1007 config_get_bool_field("daemonize", server.daemonize); 1008 config_get_bool_field("rdbcompression", server.rdb_compression); 1009 config_get_bool_field("rdbchecksum", server.rdb_checksum); 1010 config_get_bool_field("activerehashing", server.activerehashing); 1011 config_get_bool_field("repl-disable-tcp-nodelay", 1012 server.repl_disable_tcp_nodelay); 1013 config_get_bool_field("aof-rewrite-incremental-fsync", 1014 server.aof_rewrite_incremental_fsync); 1015 1016 /* Everything we can't handle with macros follows. */ 1017 1018 if (stringmatch(pattern,"appendonly",0)) { 1019 addReplyBulkCString(c,"appendonly"); 1020 addReplyBulkCString(c,server.aof_state == REDIS_AOF_OFF ? "no" : "yes"); 1021 matches++; 1022 } 1023 if (stringmatch(pattern,"dir",0)) { 1024 char buf[1024]; 1025 1026 if (getcwd(buf,sizeof(buf)) == NULL) 1027 buf[0] = '\0'; 1028 1029 addReplyBulkCString(c,"dir"); 1030 addReplyBulkCString(c,buf); 1031 matches++; 1032 } 1033 if (stringmatch(pattern,"maxmemory-policy",0)) { 1034 char *s; 1035 1036 switch(server.maxmemory_policy) { 1037 case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break; 1038 case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break; 1039 case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break; 1040 case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break; 1041 case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break; 1042 case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break; 1043 default: s = "unknown"; break; /* too harmless to panic */ 1044 } 1045 addReplyBulkCString(c,"maxmemory-policy"); 1046 addReplyBulkCString(c,s); 1047 matches++; 1048 } 1049 if (stringmatch(pattern,"appendfsync",0)) { 1050 char *policy; 1051 1052 switch(server.aof_fsync) { 1053 case AOF_FSYNC_NO: policy = "no"; break; 1054 case AOF_FSYNC_EVERYSEC: policy = "everysec"; break; 1055 case AOF_FSYNC_ALWAYS: policy = "always"; break; 1056 default: policy = "unknown"; break; /* too harmless to panic */ 1057 } 1058 addReplyBulkCString(c,"appendfsync"); 1059 addReplyBulkCString(c,policy); 1060 matches++; 1061 } 1062 if (stringmatch(pattern,"save",0)) { 1063 sds buf = sdsempty(); 1064 int j; 1065 1066 for (j = 0; j < server.saveparamslen; j++) { 1067 buf = sdscatprintf(buf,"%jd %d", 1068 (intmax_t)server.saveparams[j].seconds, 1069 server.saveparams[j].changes); 1070 if (j != server.saveparamslen-1) 1071 buf = sdscatlen(buf," ",1); 1072 } 1073 addReplyBulkCString(c,"save"); 1074 addReplyBulkCString(c,buf); 1075 sdsfree(buf); 1076 matches++; 1077 } 1078 if (stringmatch(pattern,"loglevel",0)) { 1079 char *s; 1080 1081 switch(server.verbosity) { 1082 case REDIS_WARNING: s = "warning"; break; 1083 case REDIS_VERBOSE: s = "verbose"; break; 1084 case REDIS_NOTICE: s = "notice"; break; 1085 case REDIS_DEBUG: s = "debug"; break; 1086 default: s = "unknown"; break; /* too harmless to panic */ 1087 } 1088 addReplyBulkCString(c,"loglevel"); 1089 addReplyBulkCString(c,s); 1090 matches++; 1091 } 1092 if (stringmatch(pattern,"client-output-buffer-limit",0)) { 1093 sds buf = sdsempty(); 1094 int j; 1095 1096 for (j = 0; j < REDIS_CLIENT_LIMIT_NUM_CLASSES; j++) { 1097 buf = sdscatprintf(buf,"%s %llu %llu %ld", 1098 getClientLimitClassName(j), 1099 server.client_obuf_limits[j].hard_limit_bytes, 1100 server.client_obuf_limits[j].soft_limit_bytes, 1101 (long) server.client_obuf_limits[j].soft_limit_seconds); 1102 if (j != REDIS_CLIENT_LIMIT_NUM_CLASSES-1) 1103 buf = sdscatlen(buf," ",1); 1104 } 1105 addReplyBulkCString(c,"client-output-buffer-limit"); 1106 addReplyBulkCString(c,buf); 1107 sdsfree(buf); 1108 matches++; 1109 } 1110 if (stringmatch(pattern,"unixsocketperm",0)) { 1111 char buf[32]; 1112 snprintf(buf,sizeof(buf),"%o",server.unixsocketperm); 1113 addReplyBulkCString(c,"unixsocketperm"); 1114 addReplyBulkCString(c,buf); 1115 matches++; 1116 } 1117 if (stringmatch(pattern,"slaveof",0)) { 1118 char buf[256]; 1119 1120 addReplyBulkCString(c,"slaveof"); 1121 if (server.masterhost) 1122 snprintf(buf,sizeof(buf),"%s %d", 1123 server.masterhost, server.masterport); 1124 else 1125 buf[0] = '\0'; 1126 addReplyBulkCString(c,buf); 1127 matches++; 1128 } 1129 if (stringmatch(pattern,"notify-keyspace-events",0)) { 1130 robj *flagsobj = createObject(REDIS_STRING, 1131 keyspaceEventsFlagsToString(server.notify_keyspace_events)); 1132 1133 addReplyBulkCString(c,"notify-keyspace-events"); 1134 addReplyBulk(c,flagsobj); 1135 decrRefCount(flagsobj); 1136 matches++; 1137 } 1138 if (stringmatch(pattern,"bind",0)) { 1139 sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," "); 1140 1141 addReplyBulkCString(c,"bind"); 1142 addReplyBulkCString(c,aux); 1143 sdsfree(aux); 1144 matches++; 1145 } 1146 setDeferredMultiBulkLength(c,replylen,matches*2); 1147 } 1148 1149 /*----------------------------------------------------------------------------- 1150 * CONFIG REWRITE implementation 1151 *----------------------------------------------------------------------------*/ 1152 1153 #define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE" 1154 1155 /* We use the following dictionary type to store where a configuration 1156 * option is mentioned in the old configuration file, so it's 1157 * like "maxmemory" -> list of line numbers (first line is zero). */ 1158 unsigned int dictSdsCaseHash(const void *key); 1159 int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2); 1160 void dictSdsDestructor(void *privdata, void *val); 1161 void dictListDestructor(void *privdata, void *val); 1162 1163 /* Sentinel config rewriting is implemented inside sentinel.c by 1164 * rewriteConfigSentinelOption(). */ 1165 void rewriteConfigSentinelOption(struct rewriteConfigState *state); 1166 1167 dictType optionToLineDictType = { 1168 dictSdsCaseHash, /* hash function */ 1169 NULL, /* key dup */ 1170 NULL, /* val dup */ 1171 dictSdsKeyCaseCompare, /* key compare */ 1172 dictSdsDestructor, /* key destructor */ 1173 dictListDestructor /* val destructor */ 1174 }; 1175 1176 dictType optionSetDictType = { 1177 dictSdsCaseHash, /* hash function */ 1178 NULL, /* key dup */ 1179 NULL, /* val dup */ 1180 dictSdsKeyCaseCompare, /* key compare */ 1181 dictSdsDestructor, /* key destructor */ 1182 NULL /* val destructor */ 1183 }; 1184 1185 /* The config rewrite state. */ 1186 struct rewriteConfigState { 1187 dict *option_to_line; /* Option -> list of config file lines map */ 1188 dict *rewritten; /* Dictionary of already processed options */ 1189 int numlines; /* Number of lines in current config */ 1190 sds *lines; /* Current lines as an array of sds strings */ 1191 int has_tail; /* True if we already added directives that were 1192 not present in the original config file. */ 1193 }; 1194 1195 /* Append the new line to the current configuration state. */ 1196 void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) { 1197 state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1)); 1198 state->lines[state->numlines++] = line; 1199 } 1200 1201 /* Populate the option -> list of line numbers map. */ 1202 void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) { 1203 list *l = dictFetchValue(state->option_to_line,option); 1204 1205 if (l == NULL) { 1206 l = listCreate(); 1207 dictAdd(state->option_to_line,sdsdup(option),l); 1208 } 1209 listAddNodeTail(l,(void*)(long)linenum); 1210 } 1211 1212 /* Add the specified option to the set of processed options. 1213 * This is useful as only unused lines of processed options will be blanked 1214 * in the config file, while options the rewrite process does not understand 1215 * remain untouched. */ 1216 void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, char *option) { 1217 sds opt = sdsnew(option); 1218 1219 if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt); 1220 } 1221 1222 /* Read the old file, split it into lines to populate a newly created 1223 * config rewrite state, and return it to the caller. 1224 * 1225 * If it is impossible to read the old file, NULL is returned. 1226 * If the old file does not exist at all, an empty state is returned. */ 1227 struct rewriteConfigState *rewriteConfigReadOldFile(char *path) { 1228 FILE *fp = fopen(path,"r"); 1229 struct rewriteConfigState *state = zmalloc(sizeof(*state)); 1230 char buf[REDIS_CONFIGLINE_MAX+1]; 1231 int linenum = -1; 1232 1233 if (fp == NULL && errno != ENOENT) return NULL; 1234 1235 state->option_to_line = dictCreate(&optionToLineDictType,NULL); 1236 state->rewritten = dictCreate(&optionSetDictType,NULL); 1237 state->numlines = 0; 1238 state->lines = NULL; 1239 state->has_tail = 0; 1240 if (fp == NULL) return state; 1241 1242 /* Read the old file line by line, populate the state. */ 1243 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) { 1244 int argc; 1245 sds *argv; 1246 sds line = sdstrim(sdsnew(buf),"\r\n\t "); 1247 1248 linenum++; /* Zero based, so we init at -1 */ 1249 1250 /* Handle comments and empty lines. */ 1251 if (line[0] == '#' || line[0] == '\0') { 1252 if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE)) 1253 state->has_tail = 1; 1254 rewriteConfigAppendLine(state,line); 1255 continue; 1256 } 1257 1258 /* Not a comment, split into arguments. */ 1259 argv = sdssplitargs(line,&argc); 1260 if (argv == NULL) { 1261 /* Apparently the line is unparsable for some reason, for 1262 * instance it may have unbalanced quotes. Load it as a 1263 * comment. */ 1264 sds aux = sdsnew("# ??? "); 1265 aux = sdscatsds(aux,line); 1266 sdsfree(line); 1267 rewriteConfigAppendLine(state,aux); 1268 continue; 1269 } 1270 1271 sdstolower(argv[0]); /* We only want lowercase config directives. */ 1272 1273 /* Now we populate the state according to the content of this line. 1274 * Append the line and populate the option -> line numbers map. */ 1275 rewriteConfigAppendLine(state,line); 1276 rewriteConfigAddLineNumberToOption(state,argv[0],linenum); 1277 1278 sdsfreesplitres(argv,argc); 1279 } 1280 fclose(fp); 1281 return state; 1282 } 1283 1284 /* Rewrite the specified configuration option with the new "line". 1285 * It progressively uses lines of the file that were already used for the same 1286 * configuration option in the old version of the file, removing that line from 1287 * the map of options -> line numbers. 1288 * 1289 * If there are lines associated with a given configuration option and 1290 * "force" is non-zero, the line is appended to the configuration file. 1291 * Usually "force" is true when an option has not its default value, so it 1292 * must be rewritten even if not present previously. 1293 * 1294 * The first time a line is appended into a configuration file, a comment 1295 * is added to show that starting from that point the config file was generated 1296 * by CONFIG REWRITE. 1297 * 1298 * "line" is either used, or freed, so the caller does not need to free it 1299 * in any way. */ 1300 void rewriteConfigRewriteLine(struct rewriteConfigState *state, char *option, sds line, int force) { 1301 sds o = sdsnew(option); 1302 list *l = dictFetchValue(state->option_to_line,o); 1303 1304 rewriteConfigMarkAsProcessed(state,option); 1305 1306 if (!l && !force) { 1307 /* Option not used previously, and we are not forced to use it. */ 1308 sdsfree(line); 1309 sdsfree(o); 1310 return; 1311 } 1312 1313 if (l) { 1314 listNode *ln = listFirst(l); 1315 int linenum = (long) ln->value; 1316 1317 /* There are still lines in the old configuration file we can reuse 1318 * for this option. Replace the line with the new one. */ 1319 listDelNode(l,ln); 1320 if (listLength(l) == 0) dictDelete(state->option_to_line,o); 1321 sdsfree(state->lines[linenum]); 1322 state->lines[linenum] = line; 1323 } else { 1324 /* Append a new line. */ 1325 if (!state->has_tail) { 1326 rewriteConfigAppendLine(state, 1327 sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE)); 1328 state->has_tail = 1; 1329 } 1330 rewriteConfigAppendLine(state,line); 1331 } 1332 sdsfree(o); 1333 } 1334 1335 /* Write the long long 'bytes' value as a string in a way that is parsable 1336 * inside redis.conf. If possible uses the GB, MB, KB notation. */ 1337 int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) { 1338 int gb = 1024*1024*1024; 1339 int mb = 1024*1024; 1340 int kb = 1024; 1341 1342 if (bytes && (bytes % gb) == 0) { 1343 return snprintf(buf,len,"%lldgb",bytes/gb); 1344 } else if (bytes && (bytes % mb) == 0) { 1345 return snprintf(buf,len,"%lldmb",bytes/mb); 1346 } else if (bytes && (bytes % kb) == 0) { 1347 return snprintf(buf,len,"%lldkb",bytes/kb); 1348 } else { 1349 return snprintf(buf,len,"%lld",bytes); 1350 } 1351 } 1352 1353 /* Rewrite a simple "option-name <bytes>" configuration option. */ 1354 void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) { 1355 char buf[64]; 1356 int force = value != defvalue; 1357 sds line; 1358 1359 rewriteConfigFormatMemory(buf,sizeof(buf),value); 1360 line = sdscatprintf(sdsempty(),"%s %s",option,buf); 1361 rewriteConfigRewriteLine(state,option,line,force); 1362 } 1363 1364 /* Rewrite a yes/no option. */ 1365 void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) { 1366 int force = value != defvalue; 1367 sds line = sdscatprintf(sdsempty(),"%s %s",option, 1368 value ? "yes" : "no"); 1369 1370 rewriteConfigRewriteLine(state,option,line,force); 1371 } 1372 1373 /* Rewrite a string option. */ 1374 void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) { 1375 int force = 1; 1376 sds line; 1377 1378 /* String options set to NULL need to be not present at all in the 1379 * configuration file to be set to NULL again at the next reboot. */ 1380 if (value == NULL) { 1381 rewriteConfigMarkAsProcessed(state,option); 1382 return; 1383 } 1384 1385 /* Compare the strings as sds strings to have a binary safe comparison. */ 1386 if (defvalue && strcmp(value,defvalue) == 0) force = 0; 1387 1388 line = sdsnew(option); 1389 line = sdscatlen(line, " ", 1); 1390 line = sdscatrepr(line, value, strlen(value)); 1391 1392 rewriteConfigRewriteLine(state,option,line,force); 1393 } 1394 1395 /* Rewrite a numerical (long long range) option. */ 1396 void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) { 1397 int force = value != defvalue; 1398 sds line = sdscatprintf(sdsempty(),"%s %lld",option,value); 1399 1400 rewriteConfigRewriteLine(state,option,line,force); 1401 } 1402 1403 /* Rewrite a octal option. */ 1404 void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) { 1405 int force = value != defvalue; 1406 sds line = sdscatprintf(sdsempty(),"%s %o",option,value); 1407 1408 rewriteConfigRewriteLine(state,option,line,force); 1409 } 1410 1411 /* Rewrite an enumeration option, after the "value" every enum/value pair 1412 * is specified, terminated by NULL. After NULL the default value is 1413 * specified. See how the function is used for more information. */ 1414 void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, ...) { 1415 va_list ap; 1416 char *enum_name, *matching_name = NULL; 1417 int enum_val, def_val, force; 1418 sds line; 1419 1420 va_start(ap, value); 1421 while(1) { 1422 enum_name = va_arg(ap,char*); 1423 enum_val = va_arg(ap,int); 1424 if (enum_name == NULL) { 1425 def_val = enum_val; 1426 break; 1427 } 1428 if (value == enum_val) matching_name = enum_name; 1429 } 1430 va_end(ap); 1431 1432 force = value != def_val; 1433 line = sdscatprintf(sdsempty(),"%s %s",option,matching_name); 1434 rewriteConfigRewriteLine(state,option,line,force); 1435 } 1436 1437 /* Rewrite the syslog-fability option. */ 1438 void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) { 1439 int value = server.syslog_facility, j; 1440 int force = value != LOG_LOCAL0; 1441 char *name = NULL, *option = "syslog-facility"; 1442 sds line; 1443 1444 for (j = 0; validSyslogFacilities[j].name; j++) { 1445 if (validSyslogFacilities[j].value == value) { 1446 name = (char*) validSyslogFacilities[j].name; 1447 break; 1448 } 1449 } 1450 line = sdscatprintf(sdsempty(),"%s %s",option,name); 1451 rewriteConfigRewriteLine(state,option,line,force); 1452 } 1453 1454 /* Rewrite the save option. */ 1455 void rewriteConfigSaveOption(struct rewriteConfigState *state) { 1456 int j; 1457 sds line; 1458 1459 /* Note that if there are no save parameters at all, all the current 1460 * config line with "save" will be detected as orphaned and deleted, 1461 * resulting into no RDB persistence as expected. */ 1462 for (j = 0; j < server.saveparamslen; j++) { 1463 line = sdscatprintf(sdsempty(),"save %ld %d", 1464 (long) server.saveparams[j].seconds, server.saveparams[j].changes); 1465 rewriteConfigRewriteLine(state,"save",line,1); 1466 } 1467 /* Mark "save" as processed in case server.saveparamslen is zero. */ 1468 rewriteConfigMarkAsProcessed(state,"save"); 1469 } 1470 1471 /* Rewrite the dir option, always using absolute paths.*/ 1472 void rewriteConfigDirOption(struct rewriteConfigState *state) { 1473 char cwd[1024]; 1474 1475 if (getcwd(cwd,sizeof(cwd)) == NULL) { 1476 rewriteConfigMarkAsProcessed(state,"dir"); 1477 return; /* no rewrite on error. */ 1478 } 1479 rewriteConfigStringOption(state,"dir",cwd,NULL); 1480 } 1481 1482 /* Rewrite the slaveof option. */ 1483 void rewriteConfigSlaveofOption(struct rewriteConfigState *state) { 1484 char *option = "slaveof"; 1485 sds line; 1486 1487 /* If this is a master, we want all the slaveof config options 1488 * in the file to be removed. Note that if this is a cluster instance 1489 * we don't want a slaveof directive inside redis.conf. */ 1490 if (server.cluster_enabled || server.masterhost == NULL) { 1491 rewriteConfigMarkAsProcessed(state,"slaveof"); 1492 return; 1493 } 1494 line = sdscatprintf(sdsempty(),"%s %s %d", option, 1495 server.masterhost, server.masterport); 1496 rewriteConfigRewriteLine(state,option,line,1); 1497 } 1498 1499 /* Rewrite the notify-keyspace-events option. */ 1500 void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) { 1501 int force = server.notify_keyspace_events != 0; 1502 char *option = "notify-keyspace-events"; 1503 sds line, flags; 1504 1505 flags = keyspaceEventsFlagsToString(server.notify_keyspace_events); 1506 line = sdsnew(option); 1507 line = sdscatlen(line, " ", 1); 1508 line = sdscatrepr(line, flags, sdslen(flags)); 1509 sdsfree(flags); 1510 rewriteConfigRewriteLine(state,option,line,force); 1511 } 1512 1513 /* Rewrite the client-output-buffer-limit option. */ 1514 void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) { 1515 int j; 1516 char *option = "client-output-buffer-limit"; 1517 1518 for (j = 0; j < REDIS_CLIENT_LIMIT_NUM_CLASSES; j++) { 1519 int force = (server.client_obuf_limits[j].hard_limit_bytes != 1520 clientBufferLimitsDefaults[j].hard_limit_bytes) || 1521 (server.client_obuf_limits[j].soft_limit_bytes != 1522 clientBufferLimitsDefaults[j].soft_limit_bytes) || 1523 (server.client_obuf_limits[j].soft_limit_seconds != 1524 clientBufferLimitsDefaults[j].soft_limit_seconds); 1525 sds line; 1526 char hard[64], soft[64]; 1527 1528 rewriteConfigFormatMemory(hard,sizeof(hard), 1529 server.client_obuf_limits[j].hard_limit_bytes); 1530 rewriteConfigFormatMemory(soft,sizeof(soft), 1531 server.client_obuf_limits[j].soft_limit_bytes); 1532 1533 line = sdscatprintf(sdsempty(),"%s %s %s %s %ld", 1534 option, getClientLimitClassName(j), hard, soft, 1535 (long) server.client_obuf_limits[j].soft_limit_seconds); 1536 rewriteConfigRewriteLine(state,option,line,force); 1537 } 1538 } 1539 1540 /* Rewrite the bind option. */ 1541 void rewriteConfigBindOption(struct rewriteConfigState *state) { 1542 int force = 1; 1543 sds line, addresses; 1544 char *option = "bind"; 1545 1546 /* Nothing to rewrite if we don't have bind addresses. */ 1547 if (server.bindaddr_count == 0) { 1548 rewriteConfigMarkAsProcessed(state,option); 1549 return; 1550 } 1551 1552 /* Rewrite as bind <addr1> <addr2> ... <addrN> */ 1553 addresses = sdsjoin(server.bindaddr,server.bindaddr_count," "); 1554 line = sdsnew(option); 1555 line = sdscatlen(line, " ", 1); 1556 line = sdscatsds(line, addresses); 1557 sdsfree(addresses); 1558 1559 rewriteConfigRewriteLine(state,option,line,force); 1560 } 1561 1562 /* Glue together the configuration lines in the current configuration 1563 * rewrite state into a single string, stripping multiple empty lines. */ 1564 sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) { 1565 sds content = sdsempty(); 1566 int j, was_empty = 0; 1567 1568 for (j = 0; j < state->numlines; j++) { 1569 /* Every cluster of empty lines is turned into a single empty line. */ 1570 if (sdslen(state->lines[j]) == 0) { 1571 if (was_empty) continue; 1572 was_empty = 1; 1573 } else { 1574 was_empty = 0; 1575 } 1576 content = sdscatsds(content,state->lines[j]); 1577 content = sdscatlen(content,"\n",1); 1578 } 1579 return content; 1580 } 1581 1582 /* Free the configuration rewrite state. */ 1583 void rewriteConfigReleaseState(struct rewriteConfigState *state) { 1584 sdsfreesplitres(state->lines,state->numlines); 1585 dictRelease(state->option_to_line); 1586 dictRelease(state->rewritten); 1587 zfree(state); 1588 } 1589 1590 /* At the end of the rewrite process the state contains the remaining 1591 * map between "option name" => "lines in the original config file". 1592 * Lines used by the rewrite process were removed by the function 1593 * rewriteConfigRewriteLine(), all the other lines are "orphaned" and 1594 * should be replaced by empty lines. 1595 * 1596 * This function does just this, iterating all the option names and 1597 * blanking all the lines still associated. */ 1598 void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) { 1599 dictIterator *di = dictGetIterator(state->option_to_line); 1600 dictEntry *de; 1601 1602 while((de = dictNext(di)) != NULL) { 1603 list *l = dictGetVal(de); 1604 sds option = dictGetKey(de); 1605 1606 /* Don't blank lines about options the rewrite process 1607 * don't understand. */ 1608 if (dictFind(state->rewritten,option) == NULL) { 1609 redisLog(REDIS_DEBUG,"Not rewritten option: %s", option); 1610 continue; 1611 } 1612 1613 while(listLength(l)) { 1614 listNode *ln = listFirst(l); 1615 int linenum = (long) ln->value; 1616 1617 sdsfree(state->lines[linenum]); 1618 state->lines[linenum] = sdsempty(); 1619 listDelNode(l,ln); 1620 } 1621 } 1622 dictReleaseIterator(di); 1623 } 1624 1625 /* This function overwrites the old configuration file with the new content. 1626 * 1627 * 1) The old file length is obtained. 1628 * 2) If the new content is smaller, padding is added. 1629 * 3) A single write(2) call is used to replace the content of the file. 1630 * 4) Later the file is truncated to the length of the new content. 1631 * 1632 * This way we are sure the file is left in a consistent state even if the 1633 * process is stopped between any of the four operations. 1634 * 1635 * The function returns 0 on success, otherwise -1 is returned and errno 1636 * set accordingly. */ 1637 int rewriteConfigOverwriteFile(char *configfile, sds content) { 1638 int retval = 0; 1639 int fd = open(configfile,O_RDWR|O_CREAT,0644); 1640 int content_size = sdslen(content), padding = 0; 1641 struct stat sb; 1642 sds content_padded; 1643 1644 /* 1) Open the old file (or create a new one if it does not 1645 * exist), get the size. */ 1646 if (fd == -1) return -1; /* errno set by open(). */ 1647 if (fstat(fd,&sb) == -1) { 1648 close(fd); 1649 return -1; /* errno set by fstat(). */ 1650 } 1651 1652 /* 2) Pad the content at least match the old file size. */ 1653 content_padded = sdsdup(content); 1654 if (content_size < sb.st_size) { 1655 /* If the old file was bigger, pad the content with 1656 * a newline plus as many "#" chars as required. */ 1657 padding = sb.st_size - content_size; 1658 content_padded = sdsgrowzero(content_padded,sb.st_size); 1659 content_padded[content_size] = '\n'; 1660 memset(content_padded+content_size+1,'#',padding-1); 1661 } 1662 1663 /* 3) Write the new content using a single write(2). */ 1664 if (write(fd,content_padded,strlen(content_padded)) == -1) { 1665 retval = -1; 1666 goto cleanup; 1667 } 1668 1669 /* 4) Truncate the file to the right length if we used padding. */ 1670 if (padding) { 1671 if (ftruncate(fd,content_size) == -1) { 1672 /* Non critical error... */ 1673 } 1674 } 1675 1676 cleanup: 1677 sdsfree(content_padded); 1678 close(fd); 1679 return retval; 1680 } 1681 1682 /* Rewrite the configuration file at "path". 1683 * If the configuration file already exists, we try at best to retain comments 1684 * and overall structure. 1685 * 1686 * Configuration parameters that are at their default value, unless already 1687 * explicitly included in the old configuration file, are not rewritten. 1688 * 1689 * On error -1 is returned and errno is set accordingly, otherwise 0. */ 1690 int rewriteConfig(char *path) { 1691 struct rewriteConfigState *state; 1692 sds newcontent; 1693 int retval; 1694 1695 /* Step 1: read the old config into our rewrite state. */ 1696 if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1; 1697 1698 /* Step 2: rewrite every single option, replacing or appending it inside 1699 * the rewrite state. */ 1700 1701 rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0); 1702 rewriteConfigStringOption(state,"pidfile",server.pidfile,REDIS_DEFAULT_PID_FILE); 1703 rewriteConfigNumericalOption(state,"port",server.port,REDIS_SERVERPORT); 1704 rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,REDIS_TCP_BACKLOG); 1705 rewriteConfigBindOption(state); 1706 rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL); 1707 rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,REDIS_DEFAULT_UNIX_SOCKET_PERM); 1708 rewriteConfigNumericalOption(state,"timeout",server.maxidletime,REDIS_MAXIDLETIME); 1709 rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,REDIS_DEFAULT_TCP_KEEPALIVE); 1710 rewriteConfigEnumOption(state,"loglevel",server.verbosity, 1711 "debug", REDIS_DEBUG, 1712 "verbose", REDIS_VERBOSE, 1713 "notice", REDIS_NOTICE, 1714 "warning", REDIS_WARNING, 1715 NULL, REDIS_DEFAULT_VERBOSITY); 1716 rewriteConfigStringOption(state,"logfile",server.logfile,REDIS_DEFAULT_LOGFILE); 1717 rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,REDIS_DEFAULT_SYSLOG_ENABLED); 1718 rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,REDIS_DEFAULT_SYSLOG_IDENT); 1719 rewriteConfigSyslogfacilityOption(state); 1720 rewriteConfigSaveOption(state); 1721 rewriteConfigNumericalOption(state,"databases",server.dbnum,REDIS_DEFAULT_DBNUM); 1722 rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,REDIS_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR); 1723 rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,REDIS_DEFAULT_RDB_COMPRESSION); 1724 rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,REDIS_DEFAULT_RDB_CHECKSUM); 1725 rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,REDIS_DEFAULT_RDB_FILENAME); 1726 rewriteConfigDirOption(state); 1727 rewriteConfigSlaveofOption(state); 1728 rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL); 1729 rewriteConfigYesNoOption(state,"slave-serve-stale-data",server.repl_serve_stale_data,REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA); 1730 rewriteConfigYesNoOption(state,"slave-read-only",server.repl_slave_ro,REDIS_DEFAULT_SLAVE_READ_ONLY); 1731 rewriteConfigNumericalOption(state,"repl-ping-slave-period",server.repl_ping_slave_period,REDIS_REPL_PING_SLAVE_PERIOD); 1732 rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,REDIS_REPL_TIMEOUT); 1733 rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,REDIS_DEFAULT_REPL_BACKLOG_SIZE); 1734 rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT); 1735 rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY); 1736 rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,REDIS_DEFAULT_SLAVE_PRIORITY); 1737 rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,REDIS_DEFAULT_MIN_SLAVES_TO_WRITE); 1738 rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,REDIS_DEFAULT_MIN_SLAVES_MAX_LAG); 1739 rewriteConfigStringOption(state,"requirepass",server.requirepass,NULL); 1740 rewriteConfigNumericalOption(state,"maxclients",server.maxclients,REDIS_MAX_CLIENTS); 1741 rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,REDIS_DEFAULT_MAXMEMORY); 1742 rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy, 1743 "volatile-lru", REDIS_MAXMEMORY_VOLATILE_LRU, 1744 "allkeys-lru", REDIS_MAXMEMORY_ALLKEYS_LRU, 1745 "volatile-random", REDIS_MAXMEMORY_VOLATILE_RANDOM, 1746 "allkeys-random", REDIS_MAXMEMORY_ALLKEYS_RANDOM, 1747 "volatile-ttl", REDIS_MAXMEMORY_VOLATILE_TTL, 1748 "noeviction", REDIS_MAXMEMORY_NO_EVICTION, 1749 NULL, REDIS_DEFAULT_MAXMEMORY_POLICY); 1750 rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,REDIS_DEFAULT_MAXMEMORY_SAMPLES); 1751 rewriteConfigYesNoOption(state,"appendonly",server.aof_state != REDIS_AOF_OFF,0); 1752 rewriteConfigStringOption(state,"appendfilename",server.aof_filename,REDIS_DEFAULT_AOF_FILENAME); 1753 rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync, 1754 "everysec", AOF_FSYNC_EVERYSEC, 1755 "always", AOF_FSYNC_ALWAYS, 1756 "no", AOF_FSYNC_NO, 1757 NULL, REDIS_DEFAULT_AOF_FSYNC); 1758 rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE); 1759 rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,REDIS_AOF_REWRITE_PERC); 1760 rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,REDIS_AOF_REWRITE_MIN_SIZE); 1761 rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,REDIS_LUA_TIME_LIMIT); 1762 rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0); 1763 rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,REDIS_DEFAULT_CLUSTER_CONFIG_FILE); 1764 rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT); 1765 rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER); 1766 rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,REDIS_SLOWLOG_LOG_SLOWER_THAN); 1767 rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,REDIS_SLOWLOG_MAX_LEN); 1768 rewriteConfigNotifykeyspaceeventsOption(state); 1769 rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,REDIS_HASH_MAX_ZIPLIST_ENTRIES); 1770 rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,REDIS_HASH_MAX_ZIPLIST_VALUE); 1771 rewriteConfigNumericalOption(state,"list-max-ziplist-entries",server.list_max_ziplist_entries,REDIS_LIST_MAX_ZIPLIST_ENTRIES); 1772 rewriteConfigNumericalOption(state,"list-max-ziplist-value",server.list_max_ziplist_value,REDIS_LIST_MAX_ZIPLIST_VALUE); 1773 rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,REDIS_SET_MAX_INTSET_ENTRIES); 1774 rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,REDIS_ZSET_MAX_ZIPLIST_ENTRIES); 1775 rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,REDIS_ZSET_MAX_ZIPLIST_VALUE); 1776 rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,REDIS_DEFAULT_ACTIVE_REHASHING); 1777 rewriteConfigClientoutputbufferlimitOption(state); 1778 rewriteConfigNumericalOption(state,"hz",server.hz,REDIS_DEFAULT_HZ); 1779 rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC); 1780 if (server.sentinel_mode) rewriteConfigSentinelOption(state); 1781 1782 /* Step 3: remove all the orphaned lines in the old file, that is, lines 1783 * that were used by a config option and are no longer used, like in case 1784 * of multiple "save" options or duplicated options. */ 1785 rewriteConfigRemoveOrphaned(state); 1786 1787 /* Step 4: generate a new configuration file from the modified state 1788 * and write it into the original file. */ 1789 newcontent = rewriteConfigGetContentFromState(state); 1790 retval = rewriteConfigOverwriteFile(server.configfile,newcontent); 1791 1792 sdsfree(newcontent); 1793 rewriteConfigReleaseState(state); 1794 return retval; 1795 } 1796 1797 /*----------------------------------------------------------------------------- 1798 * CONFIG command entry point 1799 *----------------------------------------------------------------------------*/ 1800 1801 void configCommand(redisClient *c) { 1802 if (!strcasecmp(c->argv[1]->ptr,"set")) { 1803 if (c->argc != 4) goto badarity; 1804 configSetCommand(c); 1805 } else if (!strcasecmp(c->argv[1]->ptr,"get")) { 1806 if (c->argc != 3) goto badarity; 1807 configGetCommand(c); 1808 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) { 1809 if (c->argc != 2) goto badarity; 1810 resetServerStats(); 1811 resetCommandTableStats(); 1812 addReply(c,shared.ok); 1813 } else if (!strcasecmp(c->argv[1]->ptr,"rewrite")) { 1814 if (c->argc != 2) goto badarity; 1815 if (server.configfile == NULL) { 1816 addReplyError(c,"The server is running without a config file"); 1817 return; 1818 } 1819 if (rewriteConfig(server.configfile) == -1) { 1820 redisLog(REDIS_WARNING,"CONFIG REWRITE failed: %s", strerror(errno)); 1821 addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno)); 1822 } else { 1823 redisLog(REDIS_WARNING,"CONFIG REWRITE executed with success."); 1824 addReply(c,shared.ok); 1825 } 1826 } else { 1827 addReplyError(c, 1828 "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE"); 1829 } 1830 return; 1831 1832 badarity: 1833 addReplyErrorFormat(c,"Wrong number of arguments for CONFIG %s", 1834 (char*) c->argv[1]->ptr); 1835 } 1836