1 /*
2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #include "server.h"
31 #include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
32 #include "crc64.h"
33
34 #include <arpa/inet.h>
35 #include <signal.h>
36
37 #ifdef HAVE_BACKTRACE
38 #include <execinfo.h>
39 #include <ucontext.h>
40 #include <fcntl.h>
41 #include "bio.h"
42 #endif /* HAVE_BACKTRACE */
43
44 #ifdef __CYGWIN__
45 #ifndef SA_ONSTACK
46 #define SA_ONSTACK 0x08000000
47 #endif
48 #endif
49
50 /* ================================= Debugging ============================== */
51
52 /* Compute the sha1 of string at 's' with 'len' bytes long.
53 * The SHA1 is then xored against the string pointed by digest.
54 * Since xor is commutative, this operation is used in order to
55 * "add" digests relative to unordered elements.
56 *
57 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
xorDigest(unsigned char * digest,void * ptr,size_t len)58 void xorDigest(unsigned char *digest, void *ptr, size_t len) {
59 SHA1_CTX ctx;
60 unsigned char hash[20], *s = ptr;
61 int j;
62
63 SHA1Init(&ctx);
64 SHA1Update(&ctx,s,len);
65 SHA1Final(hash,&ctx);
66
67 for (j = 0; j < 20; j++)
68 digest[j] ^= hash[j];
69 }
70
xorObjectDigest(unsigned char * digest,robj * o)71 void xorObjectDigest(unsigned char *digest, robj *o) {
72 o = getDecodedObject(o);
73 xorDigest(digest,o->ptr,sdslen(o->ptr));
74 decrRefCount(o);
75 }
76
77 /* This function instead of just computing the SHA1 and xoring it
78 * against digest, also perform the digest of "digest" itself and
79 * replace the old value with the new one.
80 *
81 * So the final digest will be:
82 *
83 * digest = SHA1(digest xor SHA1(data))
84 *
85 * This function is used every time we want to preserve the order so
86 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
87 *
88 * Also note that mixdigest("foo") followed by mixdigest("bar")
89 * will lead to a different digest compared to "fo", "obar".
90 */
mixDigest(unsigned char * digest,void * ptr,size_t len)91 void mixDigest(unsigned char *digest, void *ptr, size_t len) {
92 SHA1_CTX ctx;
93 char *s = ptr;
94
95 xorDigest(digest,s,len);
96 SHA1Init(&ctx);
97 SHA1Update(&ctx,digest,20);
98 SHA1Final(digest,&ctx);
99 }
100
mixObjectDigest(unsigned char * digest,robj * o)101 void mixObjectDigest(unsigned char *digest, robj *o) {
102 o = getDecodedObject(o);
103 mixDigest(digest,o->ptr,sdslen(o->ptr));
104 decrRefCount(o);
105 }
106
107 /* Compute the dataset digest. Since keys, sets elements, hashes elements
108 * are not ordered, we use a trick: every aggregate digest is the xor
109 * of the digests of their elements. This way the order will not change
110 * the result. For list instead we use a feedback entering the output digest
111 * as input in order to ensure that a different ordered list will result in
112 * a different digest. */
computeDatasetDigest(unsigned char * final)113 void computeDatasetDigest(unsigned char *final) {
114 unsigned char digest[20];
115 char buf[128];
116 dictIterator *di = NULL;
117 dictEntry *de;
118 int j;
119 uint32_t aux;
120
121 memset(final,0,20); /* Start with a clean result */
122
123 for (j = 0; j < server.dbnum; j++) {
124 redisDb *db = server.db+j;
125
126 if (dictSize(db->dict) == 0) continue;
127 di = dictGetIterator(db->dict);
128
129 /* hash the DB id, so the same dataset moved in a different
130 * DB will lead to a different digest */
131 aux = htonl(j);
132 mixDigest(final,&aux,sizeof(aux));
133
134 /* Iterate this DB writing every entry */
135 while((de = dictNext(di)) != NULL) {
136 sds key;
137 robj *keyobj, *o;
138 long long expiretime;
139
140 memset(digest,0,20); /* This key-val digest */
141 key = dictGetKey(de);
142 keyobj = createStringObject(key,sdslen(key));
143
144 mixDigest(digest,key,sdslen(key));
145
146 o = dictGetVal(de);
147
148 aux = htonl(o->type);
149 mixDigest(digest,&aux,sizeof(aux));
150 expiretime = getExpire(db,keyobj);
151
152 /* Save the key and associated value */
153 if (o->type == OBJ_STRING) {
154 mixObjectDigest(digest,o);
155 } else if (o->type == OBJ_LIST) {
156 listTypeIterator *li = listTypeInitIterator(o,0,LIST_TAIL);
157 listTypeEntry entry;
158 while(listTypeNext(li,&entry)) {
159 robj *eleobj = listTypeGet(&entry);
160 mixObjectDigest(digest,eleobj);
161 decrRefCount(eleobj);
162 }
163 listTypeReleaseIterator(li);
164 } else if (o->type == OBJ_SET) {
165 setTypeIterator *si = setTypeInitIterator(o);
166 robj *ele;
167 while((ele = setTypeNextObject(si)) != NULL) {
168 xorObjectDigest(digest,ele);
169 decrRefCount(ele);
170 }
171 setTypeReleaseIterator(si);
172 } else if (o->type == OBJ_ZSET) {
173 unsigned char eledigest[20];
174
175 if (o->encoding == OBJ_ENCODING_ZIPLIST) {
176 unsigned char *zl = o->ptr;
177 unsigned char *eptr, *sptr;
178 unsigned char *vstr;
179 unsigned int vlen;
180 long long vll;
181 double score;
182
183 eptr = ziplistIndex(zl,0);
184 serverAssert(eptr != NULL);
185 sptr = ziplistNext(zl,eptr);
186 serverAssert(sptr != NULL);
187
188 while (eptr != NULL) {
189 serverAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
190 score = zzlGetScore(sptr);
191
192 memset(eledigest,0,20);
193 if (vstr != NULL) {
194 mixDigest(eledigest,vstr,vlen);
195 } else {
196 ll2string(buf,sizeof(buf),vll);
197 mixDigest(eledigest,buf,strlen(buf));
198 }
199
200 snprintf(buf,sizeof(buf),"%.17g",score);
201 mixDigest(eledigest,buf,strlen(buf));
202 xorDigest(digest,eledigest,20);
203 zzlNext(zl,&eptr,&sptr);
204 }
205 } else if (o->encoding == OBJ_ENCODING_SKIPLIST) {
206 zset *zs = o->ptr;
207 dictIterator *di = dictGetIterator(zs->dict);
208 dictEntry *de;
209
210 while((de = dictNext(di)) != NULL) {
211 robj *eleobj = dictGetKey(de);
212 double *score = dictGetVal(de);
213
214 snprintf(buf,sizeof(buf),"%.17g",*score);
215 memset(eledigest,0,20);
216 mixObjectDigest(eledigest,eleobj);
217 mixDigest(eledigest,buf,strlen(buf));
218 xorDigest(digest,eledigest,20);
219 }
220 dictReleaseIterator(di);
221 } else {
222 serverPanic("Unknown sorted set encoding");
223 }
224 } else if (o->type == OBJ_HASH) {
225 hashTypeIterator *hi;
226 robj *obj;
227
228 hi = hashTypeInitIterator(o);
229 while (hashTypeNext(hi) != C_ERR) {
230 unsigned char eledigest[20];
231
232 memset(eledigest,0,20);
233 obj = hashTypeCurrentObject(hi,OBJ_HASH_KEY);
234 mixObjectDigest(eledigest,obj);
235 decrRefCount(obj);
236 obj = hashTypeCurrentObject(hi,OBJ_HASH_VALUE);
237 mixObjectDigest(eledigest,obj);
238 decrRefCount(obj);
239 xorDigest(digest,eledigest,20);
240 }
241 hashTypeReleaseIterator(hi);
242 } else {
243 serverPanic("Unknown object type");
244 }
245 /* If the key has an expire, add it to the mix */
246 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
247 /* We can finally xor the key-val digest to the final digest */
248 xorDigest(final,digest,20);
249 decrRefCount(keyobj);
250 }
251 dictReleaseIterator(di);
252 }
253 }
254
255 #if defined(USE_JEMALLOC)
inputCatSds(void * result,const char * str)256 void inputCatSds(void *result, const char *str) {
257 /* result is actually a (sds *), so re-cast it here */
258 sds *info = (sds *)result;
259 *info = sdscat(*info, str);
260 }
261 #endif
262
debugCommand(client * c)263 void debugCommand(client *c) {
264 if (c->argc == 1) {
265 addReplyError(c,"You must specify a subcommand for DEBUG. Try DEBUG HELP for info.");
266 return;
267 }
268
269 if (!strcasecmp(c->argv[1]->ptr,"help")) {
270 void *blenp = addDeferredMultiBulkLength(c);
271 int blen = 0;
272 blen++; addReplyStatus(c,
273 "DEBUG <subcommand> arg arg ... arg. Subcommands:");
274 blen++; addReplyStatus(c,
275 "segfault -- Crash the server with sigsegv.");
276 blen++; addReplyStatus(c,
277 "restart -- Graceful restart: save config, db, restart.");
278 blen++; addReplyStatus(c,
279 "crash-and-recovery <milliseconds> -- Hard crash and restart after <milliseconds> delay.");
280 blen++; addReplyStatus(c,
281 "assert -- Crash by assertion failed.");
282 blen++; addReplyStatus(c,
283 "reload -- Save the RDB on disk and reload it back in memory.");
284 blen++; addReplyStatus(c,
285 "loadaof -- Flush the AOF buffers on disk and reload the AOF in memory.");
286 blen++; addReplyStatus(c,
287 "object <key> -- Show low level info about key and associated value.");
288 blen++; addReplyStatus(c,
289 "sdslen <key> -- Show low level SDS string info representing key and value.");
290 blen++; addReplyStatus(c,
291 "populate <count> [prefix] -- Create <count> string keys named key:<num>. If a prefix is specified is used instead of the 'key' prefix.");
292 blen++; addReplyStatus(c,
293 "digest -- Outputs an hex signature representing the current DB content.");
294 blen++; addReplyStatus(c,
295 "sleep <seconds> -- Stop the server for <seconds>. Decimals allowed.");
296 blen++; addReplyStatus(c,
297 "set-active-expire (0|1) -- Setting it to 0 disables expiring keys in background when they are not accessed (otherwise the Redis behavior). Setting it to 1 reenables back the default.");
298 blen++; addReplyStatus(c,
299 "lua-always-replicate-commands (0|1) -- Setting it to 1 makes Lua replication defaulting to replicating single commands, without the script having to enable effects replication.");
300 blen++; addReplyStatus(c,
301 "error <string> -- Return a Redis protocol error with <string> as message. Useful for clients unit tests to simulate Redis errors.");
302 blen++; addReplyStatus(c,
303 "structsize -- Return the size of different Redis core C structures.");
304 blen++; addReplyStatus(c,
305 "htstats <dbid> -- Return hash table statistics of the specified Redis database.");
306 blen++; addReplyStatus(c,
307 "jemalloc info -- Show internal jemalloc statistics.");
308 blen++; addReplyStatus(c,
309 "jemalloc purge -- Force jemalloc to release unused memory.");
310 setDeferredMultiBulkLength(c,blenp,blen);
311 } else if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
312 *((char*)-1) = 'x';
313 } else if (!strcasecmp(c->argv[1]->ptr,"restart") ||
314 !strcasecmp(c->argv[1]->ptr,"crash-and-recover"))
315 {
316 long long delay = 0;
317 if (c->argc >= 3) {
318 if (getLongLongFromObjectOrReply(c, c->argv[2], &delay, NULL)
319 != C_OK) return;
320 if (delay < 0) delay = 0;
321 }
322 int flags = !strcasecmp(c->argv[1]->ptr,"restart") ?
323 (RESTART_SERVER_GRACEFULLY|RESTART_SERVER_CONFIG_REWRITE) :
324 RESTART_SERVER_NONE;
325 restartServer(flags,delay);
326 addReplyError(c,"failed to restart the server. Check server logs.");
327 } else if (!strcasecmp(c->argv[1]->ptr,"oom")) {
328 void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */
329 zfree(ptr);
330 addReply(c,shared.ok);
331 } else if (!strcasecmp(c->argv[1]->ptr,"assert")) {
332 if (c->argc >= 3) c->argv[2] = tryObjectEncoding(c->argv[2]);
333 serverAssertWithInfo(c,c->argv[0],1 == 2);
334 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
335 if (rdbSave(server.rdb_filename) != C_OK) {
336 addReply(c,shared.err);
337 return;
338 }
339 emptyDb(NULL);
340 if (rdbLoad(server.rdb_filename) != C_OK) {
341 addReplyError(c,"Error trying to load the RDB dump");
342 return;
343 }
344 serverLog(LL_WARNING,"DB reloaded by DEBUG RELOAD");
345 addReply(c,shared.ok);
346 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
347 if (server.aof_state == AOF_ON) flushAppendOnlyFile(1);
348 emptyDb(NULL);
349 if (loadAppendOnlyFile(server.aof_filename) != C_OK) {
350 addReply(c,shared.err);
351 return;
352 }
353 server.dirty = 0; /* Prevent AOF / replication */
354 serverLog(LL_WARNING,"Append Only File loaded by DEBUG LOADAOF");
355 addReply(c,shared.ok);
356 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
357 dictEntry *de;
358 robj *val;
359 char *strenc;
360
361 if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
362 addReply(c,shared.nokeyerr);
363 return;
364 }
365 val = dictGetVal(de);
366 strenc = strEncoding(val->encoding);
367
368 char extra[128] = {0};
369 if (val->encoding == OBJ_ENCODING_QUICKLIST) {
370 char *nextra = extra;
371 int remaining = sizeof(extra);
372 quicklist *ql = val->ptr;
373 /* Add number of quicklist nodes */
374 int used = snprintf(nextra, remaining, " ql_nodes:%u", ql->len);
375 nextra += used;
376 remaining -= used;
377 /* Add average quicklist fill factor */
378 double avg = (double)ql->count/ql->len;
379 used = snprintf(nextra, remaining, " ql_avg_node:%.2f", avg);
380 nextra += used;
381 remaining -= used;
382 /* Add quicklist fill level / max ziplist size */
383 used = snprintf(nextra, remaining, " ql_ziplist_max:%d", ql->fill);
384 nextra += used;
385 remaining -= used;
386 /* Add isCompressed? */
387 int compressed = ql->compress != 0;
388 used = snprintf(nextra, remaining, " ql_compressed:%d", compressed);
389 nextra += used;
390 remaining -= used;
391 /* Add total uncompressed size */
392 unsigned long sz = 0;
393 for (quicklistNode *node = ql->head; node; node = node->next) {
394 sz += node->sz;
395 }
396 used = snprintf(nextra, remaining, " ql_uncompressed_size:%lu", sz);
397 nextra += used;
398 remaining -= used;
399 }
400
401 addReplyStatusFormat(c,
402 "Value at:%p refcount:%d "
403 "encoding:%s serializedlength:%zu "
404 "lru:%d lru_seconds_idle:%llu%s",
405 (void*)val, val->refcount,
406 strenc, rdbSavedObjectLen(val),
407 val->lru, estimateObjectIdleTime(val)/1000, extra);
408 } else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) {
409 dictEntry *de;
410 robj *val;
411 sds key;
412
413 if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
414 addReply(c,shared.nokeyerr);
415 return;
416 }
417 val = dictGetVal(de);
418 key = dictGetKey(de);
419
420 if (val->type != OBJ_STRING || !sdsEncodedObject(val)) {
421 addReplyError(c,"Not an sds encoded string.");
422 } else {
423 addReplyStatusFormat(c,
424 "key_sds_len:%lld, key_sds_avail:%lld, "
425 "val_sds_len:%lld, val_sds_avail:%lld",
426 (long long) sdslen(key),
427 (long long) sdsavail(key),
428 (long long) sdslen(val->ptr),
429 (long long) sdsavail(val->ptr));
430 }
431 } else if (!strcasecmp(c->argv[1]->ptr,"populate") &&
432 (c->argc == 3 || c->argc == 4)) {
433 long keys, j;
434 robj *key, *val;
435 char buf[128];
436
437 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != C_OK)
438 return;
439 dictExpand(c->db->dict,keys);
440 for (j = 0; j < keys; j++) {
441 snprintf(buf,sizeof(buf),"%s:%lu",
442 (c->argc == 3) ? "key" : (char*)c->argv[3]->ptr, j);
443 key = createStringObject(buf,strlen(buf));
444 if (lookupKeyWrite(c->db,key) != NULL) {
445 decrRefCount(key);
446 continue;
447 }
448 snprintf(buf,sizeof(buf),"value:%lu",j);
449 val = createStringObject(buf,strlen(buf));
450 dbAdd(c->db,key,val);
451 signalModifiedKey(c->db,key);
452 decrRefCount(key);
453 }
454 addReply(c,shared.ok);
455 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
456 unsigned char digest[20];
457 sds d = sdsempty();
458 int j;
459
460 computeDatasetDigest(digest);
461 for (j = 0; j < 20; j++)
462 d = sdscatprintf(d, "%02x",digest[j]);
463 addReplyStatus(c,d);
464 sdsfree(d);
465 } else if (!strcasecmp(c->argv[1]->ptr,"sleep") && c->argc == 3) {
466 double dtime = strtod(c->argv[2]->ptr,NULL);
467 long long utime = dtime*1000000;
468 struct timespec tv;
469
470 tv.tv_sec = utime / 1000000;
471 tv.tv_nsec = (utime % 1000000) * 1000;
472 nanosleep(&tv, NULL);
473 addReply(c,shared.ok);
474 } else if (!strcasecmp(c->argv[1]->ptr,"set-active-expire") &&
475 c->argc == 3)
476 {
477 server.active_expire_enabled = atoi(c->argv[2]->ptr);
478 addReply(c,shared.ok);
479 } else if (!strcasecmp(c->argv[1]->ptr,"lua-always-replicate-commands") &&
480 c->argc == 3)
481 {
482 server.lua_always_replicate_commands = atoi(c->argv[2]->ptr);
483 addReply(c,shared.ok);
484 } else if (!strcasecmp(c->argv[1]->ptr,"error") && c->argc == 3) {
485 sds errstr = sdsnewlen("-",1);
486
487 errstr = sdscatsds(errstr,c->argv[2]->ptr);
488 errstr = sdsmapchars(errstr,"\n\r"," ",2); /* no newlines in errors. */
489 errstr = sdscatlen(errstr,"\r\n",2);
490 addReplySds(c,errstr);
491 } else if (!strcasecmp(c->argv[1]->ptr,"structsize") && c->argc == 2) {
492 sds sizes = sdsempty();
493 sizes = sdscatprintf(sizes,"bits:%d ",(sizeof(void*) == 8)?64:32);
494 sizes = sdscatprintf(sizes,"robj:%d ",(int)sizeof(robj));
495 sizes = sdscatprintf(sizes,"dictentry:%d ",(int)sizeof(dictEntry));
496 sizes = sdscatprintf(sizes,"sdshdr5:%d ",(int)sizeof(struct sdshdr5));
497 sizes = sdscatprintf(sizes,"sdshdr8:%d ",(int)sizeof(struct sdshdr8));
498 sizes = sdscatprintf(sizes,"sdshdr16:%d ",(int)sizeof(struct sdshdr16));
499 sizes = sdscatprintf(sizes,"sdshdr32:%d ",(int)sizeof(struct sdshdr32));
500 sizes = sdscatprintf(sizes,"sdshdr64:%d ",(int)sizeof(struct sdshdr64));
501 addReplyBulkSds(c,sizes);
502 } else if (!strcasecmp(c->argv[1]->ptr,"htstats") && c->argc == 3) {
503 long dbid;
504 sds stats = sdsempty();
505 char buf[4096];
506
507 if (getLongFromObjectOrReply(c, c->argv[2], &dbid, NULL) != C_OK)
508 return;
509 if (dbid < 0 || dbid >= server.dbnum) {
510 addReplyError(c,"Out of range database");
511 return;
512 }
513
514 stats = sdscatprintf(stats,"[Dictionary HT]\n");
515 dictGetStats(buf,sizeof(buf),server.db[dbid].dict);
516 stats = sdscat(stats,buf);
517
518 stats = sdscatprintf(stats,"[Expires HT]\n");
519 dictGetStats(buf,sizeof(buf),server.db[dbid].expires);
520 stats = sdscat(stats,buf);
521
522 addReplyBulkSds(c,stats);
523 } else if (!strcasecmp(c->argv[1]->ptr,"jemalloc") && c->argc == 3) {
524 #if defined(USE_JEMALLOC)
525 if (!strcasecmp(c->argv[2]->ptr, "info")) {
526 sds info = sdsempty();
527 je_malloc_stats_print(inputCatSds, &info, NULL);
528 addReplyBulkSds(c, info);
529 } else if (!strcasecmp(c->argv[2]->ptr, "purge")) {
530 char tmp[32];
531 unsigned narenas = 0;
532 size_t sz = sizeof(unsigned);
533 if (!je_mallctl("arenas.narenas", &narenas, &sz, NULL, 0)) {
534 sprintf(tmp, "arena.%d.purge", narenas);
535 if (!je_mallctl(tmp, NULL, 0, NULL, 0)) {
536 addReply(c, shared.ok);
537 return;
538 }
539 }
540 addReplyError(c, "Error purging dirty pages");
541 } else {
542 addReplyErrorFormat(c, "Valid jemalloc debug fields: info, purge");
543 }
544 #else
545 addReplyErrorFormat(c, "jemalloc support not available");
546 #endif
547 } else {
548 addReplyErrorFormat(c, "Unknown DEBUG subcommand or wrong number of arguments for '%s'",
549 (char*)c->argv[1]->ptr);
550 }
551 }
552
553 /* =========================== Crash handling ============================== */
554
_serverAssert(char * estr,char * file,int line)555 void _serverAssert(char *estr, char *file, int line) {
556 bugReportStart();
557 serverLog(LL_WARNING,"=== ASSERTION FAILED ===");
558 serverLog(LL_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
559 #ifdef HAVE_BACKTRACE
560 server.assert_failed = estr;
561 server.assert_file = file;
562 server.assert_line = line;
563 serverLog(LL_WARNING,"(forcing SIGSEGV to print the bug report.)");
564 #endif
565 *((char*)-1) = 'x';
566 }
567
_serverAssertPrintClientInfo(client * c)568 void _serverAssertPrintClientInfo(client *c) {
569 int j;
570
571 bugReportStart();
572 serverLog(LL_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ===");
573 serverLog(LL_WARNING,"client->flags = %d", c->flags);
574 serverLog(LL_WARNING,"client->fd = %d", c->fd);
575 serverLog(LL_WARNING,"client->argc = %d", c->argc);
576 for (j=0; j < c->argc; j++) {
577 char buf[128];
578 char *arg;
579
580 if (c->argv[j]->type == OBJ_STRING && sdsEncodedObject(c->argv[j])) {
581 arg = (char*) c->argv[j]->ptr;
582 } else {
583 snprintf(buf,sizeof(buf),"Object type: %u, encoding: %u",
584 c->argv[j]->type, c->argv[j]->encoding);
585 arg = buf;
586 }
587 serverLog(LL_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)",
588 j, arg, c->argv[j]->refcount);
589 }
590 }
591
serverLogObjectDebugInfo(robj * o)592 void serverLogObjectDebugInfo(robj *o) {
593 serverLog(LL_WARNING,"Object type: %d", o->type);
594 serverLog(LL_WARNING,"Object encoding: %d", o->encoding);
595 serverLog(LL_WARNING,"Object refcount: %d", o->refcount);
596 if (o->type == OBJ_STRING && sdsEncodedObject(o)) {
597 serverLog(LL_WARNING,"Object raw string len: %zu", sdslen(o->ptr));
598 if (sdslen(o->ptr) < 4096) {
599 sds repr = sdscatrepr(sdsempty(),o->ptr,sdslen(o->ptr));
600 serverLog(LL_WARNING,"Object raw string content: %s", repr);
601 sdsfree(repr);
602 }
603 } else if (o->type == OBJ_LIST) {
604 serverLog(LL_WARNING,"List length: %d", (int) listTypeLength(o));
605 } else if (o->type == OBJ_SET) {
606 serverLog(LL_WARNING,"Set size: %d", (int) setTypeSize(o));
607 } else if (o->type == OBJ_HASH) {
608 serverLog(LL_WARNING,"Hash size: %d", (int) hashTypeLength(o));
609 } else if (o->type == OBJ_ZSET) {
610 serverLog(LL_WARNING,"Sorted set size: %d", (int) zsetLength(o));
611 if (o->encoding == OBJ_ENCODING_SKIPLIST)
612 serverLog(LL_WARNING,"Skiplist level: %d", (int) ((zset*)o->ptr)->zsl->level);
613 }
614 }
615
_serverAssertPrintObject(robj * o)616 void _serverAssertPrintObject(robj *o) {
617 bugReportStart();
618 serverLog(LL_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ===");
619 serverLogObjectDebugInfo(o);
620 }
621
_serverAssertWithInfo(client * c,robj * o,char * estr,char * file,int line)622 void _serverAssertWithInfo(client *c, robj *o, char *estr, char *file, int line) {
623 if (c) _serverAssertPrintClientInfo(c);
624 if (o) _serverAssertPrintObject(o);
625 _serverAssert(estr,file,line);
626 }
627
_serverPanic(char * msg,char * file,int line)628 void _serverPanic(char *msg, char *file, int line) {
629 bugReportStart();
630 serverLog(LL_WARNING,"------------------------------------------------");
631 serverLog(LL_WARNING,"!!! Software Failure. Press left mouse button to continue");
632 serverLog(LL_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
633 #ifdef HAVE_BACKTRACE
634 serverLog(LL_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
635 #endif
636 serverLog(LL_WARNING,"------------------------------------------------");
637 *((char*)-1) = 'x';
638 }
639
bugReportStart(void)640 void bugReportStart(void) {
641 if (server.bug_report_start == 0) {
642 serverLogRaw(LL_WARNING|LL_RAW,
643 "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===\n");
644 server.bug_report_start = 1;
645 }
646 }
647
648 #ifdef HAVE_BACKTRACE
getMcontextEip(ucontext_t * uc)649 static void *getMcontextEip(ucontext_t *uc) {
650 #if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
651 /* OSX < 10.6 */
652 #if defined(__x86_64__)
653 return (void*) uc->uc_mcontext->__ss.__rip;
654 #elif defined(__i386__)
655 return (void*) uc->uc_mcontext->__ss.__eip;
656 #else
657 return (void*) uc->uc_mcontext->__ss.__srr0;
658 #endif
659 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
660 /* OSX >= 10.6 */
661 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
662 return (void*) uc->uc_mcontext->__ss.__rip;
663 #else
664 return (void*) uc->uc_mcontext->__ss.__eip;
665 #endif
666 #elif defined(__linux__)
667 /* Linux */
668 #if defined(__i386__)
669 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
670 #elif defined(__X86_64__) || defined(__x86_64__)
671 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
672 #elif defined(__ia64__) /* Linux IA64 */
673 return (void*) uc->uc_mcontext.sc_ip;
674 #endif
675 #else
676 return NULL;
677 #endif
678 }
679
logStackContent(void ** sp)680 void logStackContent(void **sp) {
681 int i;
682 for (i = 15; i >= 0; i--) {
683 unsigned long addr = (unsigned long) sp+i;
684 unsigned long val = (unsigned long) sp[i];
685
686 if (sizeof(long) == 4)
687 serverLog(LL_WARNING, "(%08lx) -> %08lx", addr, val);
688 else
689 serverLog(LL_WARNING, "(%016lx) -> %016lx", addr, val);
690 }
691 }
692
logRegisters(ucontext_t * uc)693 void logRegisters(ucontext_t *uc) {
694 serverLog(LL_WARNING|LL_RAW, "\n------ REGISTERS ------\n");
695
696 /* OSX */
697 #if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
698 /* OSX AMD64 */
699 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
700 serverLog(LL_WARNING,
701 "\n"
702 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
703 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
704 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
705 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
706 "RIP:%016lx EFL:%016lx\nCS :%016lx FS:%016lx GS:%016lx",
707 (unsigned long) uc->uc_mcontext->__ss.__rax,
708 (unsigned long) uc->uc_mcontext->__ss.__rbx,
709 (unsigned long) uc->uc_mcontext->__ss.__rcx,
710 (unsigned long) uc->uc_mcontext->__ss.__rdx,
711 (unsigned long) uc->uc_mcontext->__ss.__rdi,
712 (unsigned long) uc->uc_mcontext->__ss.__rsi,
713 (unsigned long) uc->uc_mcontext->__ss.__rbp,
714 (unsigned long) uc->uc_mcontext->__ss.__rsp,
715 (unsigned long) uc->uc_mcontext->__ss.__r8,
716 (unsigned long) uc->uc_mcontext->__ss.__r9,
717 (unsigned long) uc->uc_mcontext->__ss.__r10,
718 (unsigned long) uc->uc_mcontext->__ss.__r11,
719 (unsigned long) uc->uc_mcontext->__ss.__r12,
720 (unsigned long) uc->uc_mcontext->__ss.__r13,
721 (unsigned long) uc->uc_mcontext->__ss.__r14,
722 (unsigned long) uc->uc_mcontext->__ss.__r15,
723 (unsigned long) uc->uc_mcontext->__ss.__rip,
724 (unsigned long) uc->uc_mcontext->__ss.__rflags,
725 (unsigned long) uc->uc_mcontext->__ss.__cs,
726 (unsigned long) uc->uc_mcontext->__ss.__fs,
727 (unsigned long) uc->uc_mcontext->__ss.__gs
728 );
729 logStackContent((void**)uc->uc_mcontext->__ss.__rsp);
730 #else
731 /* OSX x86 */
732 serverLog(LL_WARNING,
733 "\n"
734 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
735 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
736 "SS:%08lx EFL:%08lx EIP:%08lx CS :%08lx\n"
737 "DS:%08lx ES:%08lx FS :%08lx GS :%08lx",
738 (unsigned long) uc->uc_mcontext->__ss.__eax,
739 (unsigned long) uc->uc_mcontext->__ss.__ebx,
740 (unsigned long) uc->uc_mcontext->__ss.__ecx,
741 (unsigned long) uc->uc_mcontext->__ss.__edx,
742 (unsigned long) uc->uc_mcontext->__ss.__edi,
743 (unsigned long) uc->uc_mcontext->__ss.__esi,
744 (unsigned long) uc->uc_mcontext->__ss.__ebp,
745 (unsigned long) uc->uc_mcontext->__ss.__esp,
746 (unsigned long) uc->uc_mcontext->__ss.__ss,
747 (unsigned long) uc->uc_mcontext->__ss.__eflags,
748 (unsigned long) uc->uc_mcontext->__ss.__eip,
749 (unsigned long) uc->uc_mcontext->__ss.__cs,
750 (unsigned long) uc->uc_mcontext->__ss.__ds,
751 (unsigned long) uc->uc_mcontext->__ss.__es,
752 (unsigned long) uc->uc_mcontext->__ss.__fs,
753 (unsigned long) uc->uc_mcontext->__ss.__gs
754 );
755 logStackContent((void**)uc->uc_mcontext->__ss.__esp);
756 #endif
757 /* Linux */
758 #elif defined(__linux__)
759 /* Linux x86 */
760 #if defined(__i386__)
761 serverLog(LL_WARNING,
762 "\n"
763 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
764 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
765 "SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\n"
766 "DS :%08lx ES :%08lx FS :%08lx GS:%08lx",
767 (unsigned long) uc->uc_mcontext.gregs[11],
768 (unsigned long) uc->uc_mcontext.gregs[8],
769 (unsigned long) uc->uc_mcontext.gregs[10],
770 (unsigned long) uc->uc_mcontext.gregs[9],
771 (unsigned long) uc->uc_mcontext.gregs[4],
772 (unsigned long) uc->uc_mcontext.gregs[5],
773 (unsigned long) uc->uc_mcontext.gregs[6],
774 (unsigned long) uc->uc_mcontext.gregs[7],
775 (unsigned long) uc->uc_mcontext.gregs[18],
776 (unsigned long) uc->uc_mcontext.gregs[17],
777 (unsigned long) uc->uc_mcontext.gregs[14],
778 (unsigned long) uc->uc_mcontext.gregs[15],
779 (unsigned long) uc->uc_mcontext.gregs[3],
780 (unsigned long) uc->uc_mcontext.gregs[2],
781 (unsigned long) uc->uc_mcontext.gregs[1],
782 (unsigned long) uc->uc_mcontext.gregs[0]
783 );
784 logStackContent((void**)uc->uc_mcontext.gregs[7]);
785 #elif defined(__X86_64__) || defined(__x86_64__)
786 /* Linux AMD64 */
787 serverLog(LL_WARNING,
788 "\n"
789 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
790 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
791 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
792 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
793 "RIP:%016lx EFL:%016lx\nCSGSFS:%016lx",
794 (unsigned long) uc->uc_mcontext.gregs[13],
795 (unsigned long) uc->uc_mcontext.gregs[11],
796 (unsigned long) uc->uc_mcontext.gregs[14],
797 (unsigned long) uc->uc_mcontext.gregs[12],
798 (unsigned long) uc->uc_mcontext.gregs[8],
799 (unsigned long) uc->uc_mcontext.gregs[9],
800 (unsigned long) uc->uc_mcontext.gregs[10],
801 (unsigned long) uc->uc_mcontext.gregs[15],
802 (unsigned long) uc->uc_mcontext.gregs[0],
803 (unsigned long) uc->uc_mcontext.gregs[1],
804 (unsigned long) uc->uc_mcontext.gregs[2],
805 (unsigned long) uc->uc_mcontext.gregs[3],
806 (unsigned long) uc->uc_mcontext.gregs[4],
807 (unsigned long) uc->uc_mcontext.gregs[5],
808 (unsigned long) uc->uc_mcontext.gregs[6],
809 (unsigned long) uc->uc_mcontext.gregs[7],
810 (unsigned long) uc->uc_mcontext.gregs[16],
811 (unsigned long) uc->uc_mcontext.gregs[17],
812 (unsigned long) uc->uc_mcontext.gregs[18]
813 );
814 logStackContent((void**)uc->uc_mcontext.gregs[15]);
815 #endif
816 #else
817 serverLog(LL_WARNING,
818 " Dumping of registers not supported for this OS/arch");
819 #endif
820 }
821
822 /* Return a file descriptor to write directly to the Redis log with the
823 * write(2) syscall, that can be used in critical sections of the code
824 * where the rest of Redis can't be trusted (for example during the memory
825 * test) or when an API call requires a raw fd.
826 *
827 * Close it with closeDirectLogFiledes(). */
openDirectLogFiledes(void)828 int openDirectLogFiledes(void) {
829 int log_to_stdout = server.logfile[0] == '\0';
830 int fd = log_to_stdout ?
831 STDOUT_FILENO :
832 open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);
833 return fd;
834 }
835
836 /* Used to close what closeDirectLogFiledes() returns. */
closeDirectLogFiledes(int fd)837 void closeDirectLogFiledes(int fd) {
838 int log_to_stdout = server.logfile[0] == '\0';
839 if (!log_to_stdout) close(fd);
840 }
841
842 /* Logs the stack trace using the backtrace() call. This function is designed
843 * to be called from signal handlers safely. */
logStackTrace(ucontext_t * uc)844 void logStackTrace(ucontext_t *uc) {
845 void *trace[101];
846 int trace_size = 0, fd = openDirectLogFiledes();
847
848 if (fd == -1) return; /* If we can't log there is anything to do. */
849
850 /* Generate the stack trace */
851 trace_size = backtrace(trace+1, 100);
852
853 if (getMcontextEip(uc) != NULL) {
854 char *msg1 = "EIP:\n";
855 char *msg2 = "\nBacktrace:\n";
856 if (write(fd,msg1,strlen(msg1)) == -1) {/* Avoid warning. */};
857 trace[0] = getMcontextEip(uc);
858 backtrace_symbols_fd(trace, 1, fd);
859 if (write(fd,msg2,strlen(msg2)) == -1) {/* Avoid warning. */};
860 }
861
862 /* Write symbols to log file */
863 backtrace_symbols_fd(trace+1, trace_size, fd);
864
865 /* Cleanup */
866 closeDirectLogFiledes(fd);
867 }
868
869 /* Log information about the "current" client, that is, the client that is
870 * currently being served by Redis. May be NULL if Redis is not serving a
871 * client right now. */
logCurrentClient(void)872 void logCurrentClient(void) {
873 if (server.current_client == NULL) return;
874
875 client *cc = server.current_client;
876 sds client;
877 int j;
878
879 serverLogRaw(LL_WARNING|LL_RAW, "\n------ CURRENT CLIENT INFO ------\n");
880 client = catClientInfoString(sdsempty(),cc);
881 serverLog(LL_WARNING|LL_RAW,"%s\n", client);
882 sdsfree(client);
883 for (j = 0; j < cc->argc; j++) {
884 robj *decoded;
885
886 decoded = getDecodedObject(cc->argv[j]);
887 serverLog(LL_WARNING|LL_RAW,"argv[%d]: '%s'\n", j,
888 (char*)decoded->ptr);
889 decrRefCount(decoded);
890 }
891 /* Check if the first argument, usually a key, is found inside the
892 * selected DB, and if so print info about the associated object. */
893 if (cc->argc >= 1) {
894 robj *val, *key;
895 dictEntry *de;
896
897 key = getDecodedObject(cc->argv[1]);
898 de = dictFind(cc->db->dict, key->ptr);
899 if (de) {
900 val = dictGetVal(de);
901 serverLog(LL_WARNING,"key '%s' found in DB containing the following object:", (char*)key->ptr);
902 serverLogObjectDebugInfo(val);
903 }
904 decrRefCount(key);
905 }
906 }
907
908 #if defined(HAVE_PROC_MAPS)
909
910 #define MEMTEST_MAX_REGIONS 128
911
912 /* A non destructive memory test executed during segfauls. */
memtest_test_linux_anonymous_maps(void)913 int memtest_test_linux_anonymous_maps(void) {
914 FILE *fp;
915 char line[1024];
916 char logbuf[1024];
917 size_t start_addr, end_addr, size;
918 size_t start_vect[MEMTEST_MAX_REGIONS];
919 size_t size_vect[MEMTEST_MAX_REGIONS];
920 int regions = 0, j;
921
922 int fd = openDirectLogFiledes();
923 if (!fd) return 0;
924
925 fp = fopen("/proc/self/maps","r");
926 if (!fp) return 0;
927 while(fgets(line,sizeof(line),fp) != NULL) {
928 char *start, *end, *p = line;
929
930 start = p;
931 p = strchr(p,'-');
932 if (!p) continue;
933 *p++ = '\0';
934 end = p;
935 p = strchr(p,' ');
936 if (!p) continue;
937 *p++ = '\0';
938 if (strstr(p,"stack") ||
939 strstr(p,"vdso") ||
940 strstr(p,"vsyscall")) continue;
941 if (!strstr(p,"00:00")) continue;
942 if (!strstr(p,"rw")) continue;
943
944 start_addr = strtoul(start,NULL,16);
945 end_addr = strtoul(end,NULL,16);
946 size = end_addr-start_addr;
947
948 start_vect[regions] = start_addr;
949 size_vect[regions] = size;
950 snprintf(logbuf,sizeof(logbuf),
951 "*** Preparing to test memory region %lx (%lu bytes)\n",
952 (unsigned long) start_vect[regions],
953 (unsigned long) size_vect[regions]);
954 if (write(fd,logbuf,strlen(logbuf)) == -1) { /* Nothing to do. */ }
955 regions++;
956 }
957
958 int errors = 0;
959 for (j = 0; j < regions; j++) {
960 if (write(fd,".",1) == -1) { /* Nothing to do. */ }
961 errors += memtest_preserving_test((void*)start_vect[j],size_vect[j],1);
962 if (write(fd, errors ? "E" : "O",1) == -1) { /* Nothing to do. */ }
963 }
964 if (write(fd,"\n",1) == -1) { /* Nothing to do. */ }
965
966 /* NOTE: It is very important to close the file descriptor only now
967 * because closing it before may result into unmapping of some memory
968 * region that we are testing. */
969 fclose(fp);
970 closeDirectLogFiledes(fd);
971 return errors;
972 }
973 #endif
974
sigsegvHandler(int sig,siginfo_t * info,void * secret)975 void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
976 ucontext_t *uc = (ucontext_t*) secret;
977 void *eip = getMcontextEip(uc);
978 sds infostring, clients;
979 struct sigaction act;
980 UNUSED(info);
981
982 bugReportStart();
983 serverLog(LL_WARNING,
984 "Redis %s crashed by signal: %d", REDIS_VERSION, sig);
985 if (eip != NULL) {
986 serverLog(LL_WARNING,
987 "Crashed running the instuction at: %p", eip);
988 }
989 if (sig == SIGSEGV || sig == SIGBUS) {
990 serverLog(LL_WARNING,
991 "Accessing address: %p", (void*)info->si_addr);
992 }
993 serverLog(LL_WARNING,
994 "Failed assertion: %s (%s:%d)", server.assert_failed,
995 server.assert_file, server.assert_line);
996
997 /* Log the stack trace */
998 serverLogRaw(LL_WARNING|LL_RAW, "\n------ STACK TRACE ------\n");
999 logStackTrace(uc);
1000
1001 /* Log INFO and CLIENT LIST */
1002 serverLogRaw(LL_WARNING|LL_RAW, "\n------ INFO OUTPUT ------\n");
1003 infostring = genRedisInfoString("all");
1004 infostring = sdscatprintf(infostring, "hash_init_value: %u\n",
1005 dictGetHashFunctionSeed());
1006 serverLogRaw(LL_WARNING|LL_RAW, infostring);
1007 serverLogRaw(LL_WARNING|LL_RAW, "\n------ CLIENT LIST OUTPUT ------\n");
1008 clients = getAllClientsInfoString();
1009 serverLogRaw(LL_WARNING|LL_RAW, clients);
1010 sdsfree(infostring);
1011 sdsfree(clients);
1012
1013 /* Log the current client */
1014 logCurrentClient();
1015
1016 /* Log dump of processor registers */
1017 logRegisters(uc);
1018
1019 #if defined(HAVE_PROC_MAPS)
1020 /* Test memory */
1021 serverLogRaw(LL_WARNING|LL_RAW, "\n------ FAST MEMORY TEST ------\n");
1022 bioKillThreads();
1023 if (memtest_test_linux_anonymous_maps()) {
1024 serverLogRaw(LL_WARNING|LL_RAW,
1025 "!!! MEMORY ERROR DETECTED! Check your memory ASAP !!!");
1026 } else {
1027 serverLogRaw(LL_WARNING|LL_RAW,
1028 "Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible.");
1029 }
1030 #endif
1031
1032 serverLogRaw(LL_WARNING|LL_RAW,
1033 "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
1034 " Please report the crash by opening an issue on github:\n\n"
1035 " http://github.com/antirez/redis/issues\n\n"
1036 " Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
1037 );
1038 /* free(messages); Don't call free() with possibly corrupted memory. */
1039 if (server.daemonize && server.supervised == 0) unlink(server.pidfile);
1040
1041 /* Make sure we exit with the right signal at the end. So for instance
1042 * the core will be dumped if enabled. */
1043 sigemptyset (&act.sa_mask);
1044 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1045 act.sa_handler = SIG_DFL;
1046 sigaction (sig, &act, NULL);
1047 kill(getpid(),sig);
1048 }
1049 #endif /* HAVE_BACKTRACE */
1050
1051 /* ==================== Logging functions for debugging ===================== */
1052
serverLogHexDump(int level,char * descr,void * value,size_t len)1053 void serverLogHexDump(int level, char *descr, void *value, size_t len) {
1054 char buf[65], *b;
1055 unsigned char *v = value;
1056 char charset[] = "0123456789abcdef";
1057
1058 serverLog(level,"%s (hexdump):", descr);
1059 b = buf;
1060 while(len) {
1061 b[0] = charset[(*v)>>4];
1062 b[1] = charset[(*v)&0xf];
1063 b[2] = '\0';
1064 b += 2;
1065 len--;
1066 v++;
1067 if (b-buf == 64 || len == 0) {
1068 serverLogRaw(level|LL_RAW,buf);
1069 b = buf;
1070 }
1071 }
1072 serverLogRaw(level|LL_RAW,"\n");
1073 }
1074
1075 /* =========================== Software Watchdog ============================ */
1076 #include <sys/time.h>
1077
watchdogSignalHandler(int sig,siginfo_t * info,void * secret)1078 void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {
1079 #ifdef HAVE_BACKTRACE
1080 ucontext_t *uc = (ucontext_t*) secret;
1081 #endif
1082 UNUSED(info);
1083 UNUSED(sig);
1084
1085 serverLogFromHandler(LL_WARNING,"\n--- WATCHDOG TIMER EXPIRED ---");
1086 #ifdef HAVE_BACKTRACE
1087 logStackTrace(uc);
1088 #else
1089 serverLogFromHandler(LL_WARNING,"Sorry: no support for backtrace().");
1090 #endif
1091 serverLogFromHandler(LL_WARNING,"--------\n");
1092 }
1093
1094 /* Schedule a SIGALRM delivery after the specified period in milliseconds.
1095 * If a timer is already scheduled, this function will re-schedule it to the
1096 * specified time. If period is 0 the current timer is disabled. */
watchdogScheduleSignal(int period)1097 void watchdogScheduleSignal(int period) {
1098 struct itimerval it;
1099
1100 /* Will stop the timer if period is 0. */
1101 it.it_value.tv_sec = period/1000;
1102 it.it_value.tv_usec = (period%1000)*1000;
1103 /* Don't automatically restart. */
1104 it.it_interval.tv_sec = 0;
1105 it.it_interval.tv_usec = 0;
1106 setitimer(ITIMER_REAL, &it, NULL);
1107 }
1108
1109 /* Enable the software watchdog with the specified period in milliseconds. */
enableWatchdog(int period)1110 void enableWatchdog(int period) {
1111 int min_period;
1112
1113 if (server.watchdog_period == 0) {
1114 struct sigaction act;
1115
1116 /* Watchdog was actually disabled, so we have to setup the signal
1117 * handler. */
1118 sigemptyset(&act.sa_mask);
1119 act.sa_flags = SA_ONSTACK | SA_SIGINFO;
1120 act.sa_sigaction = watchdogSignalHandler;
1121 sigaction(SIGALRM, &act, NULL);
1122 }
1123 /* If the configured period is smaller than twice the timer period, it is
1124 * too short for the software watchdog to work reliably. Fix it now
1125 * if needed. */
1126 min_period = (1000/server.hz)*2;
1127 if (period < min_period) period = min_period;
1128 watchdogScheduleSignal(period); /* Adjust the current timer. */
1129 server.watchdog_period = period;
1130 }
1131
1132 /* Disable the software watchdog. */
disableWatchdog(void)1133 void disableWatchdog(void) {
1134 struct sigaction act;
1135 if (server.watchdog_period == 0) return; /* Already disabled. */
1136 watchdogScheduleSignal(0); /* Stop the current timer. */
1137
1138 /* Set the signal handler to SIG_IGN, this will also remove pending
1139 * signals from the queue. */
1140 sigemptyset(&act.sa_mask);
1141 act.sa_flags = 0;
1142 act.sa_handler = SIG_IGN;
1143 sigaction(SIGALRM, &act, NULL);
1144 server.watchdog_period = 0;
1145 }
1146