]> git.saurik.com Git - redis.git/blob - src/rdb.c
fixed two diskstore issues, a quasi-deadlock creating problems with I/O speed and...
[redis.git] / src / rdb.c
1 #include "redis.h"
2 #include "lzf.h" /* LZF compression library */
3
4 #include <math.h>
5 #include <sys/types.h>
6 #include <sys/time.h>
7 #include <sys/resource.h>
8 #include <sys/wait.h>
9 #include <arpa/inet.h>
10 #include <sys/stat.h>
11
12 /* Convenience wrapper around fwrite, that returns the number of bytes written
13 * to the file instead of the number of objects (see fwrite(3)) and -1 in the
14 * case of an error. It also supports a NULL *fp to skip writing altogether
15 * instead of writing to /dev/null. */
16 static int rdbWriteRaw(FILE *fp, void *p, size_t len) {
17 if (fp != NULL && fwrite(p,len,1,fp) == 0) return -1;
18 return len;
19 }
20
21 int rdbSaveType(FILE *fp, unsigned char type) {
22 return rdbWriteRaw(fp,&type,1);
23 }
24
25 int rdbSaveTime(FILE *fp, time_t t) {
26 int32_t t32 = (int32_t) t;
27 return rdbWriteRaw(fp,&t32,4);
28 }
29
30 /* check rdbLoadLen() comments for more info */
31 int rdbSaveLen(FILE *fp, uint32_t len) {
32 unsigned char buf[2];
33 int nwritten;
34
35 if (len < (1<<6)) {
36 /* Save a 6 bit len */
37 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
38 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
39 nwritten = 1;
40 } else if (len < (1<<14)) {
41 /* Save a 14 bit len */
42 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
43 buf[1] = len&0xFF;
44 if (rdbWriteRaw(fp,buf,2) == -1) return -1;
45 nwritten = 2;
46 } else {
47 /* Save a 32 bit len */
48 buf[0] = (REDIS_RDB_32BITLEN<<6);
49 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
50 len = htonl(len);
51 if (rdbWriteRaw(fp,&len,4) == -1) return -1;
52 nwritten = 1+4;
53 }
54 return nwritten;
55 }
56
57 /* Encode 'value' as an integer if possible (if integer will fit the
58 * supported range). If the function sucessful encoded the integer
59 * then the (up to 5 bytes) encoded representation is written in the
60 * string pointed by 'enc' and the length is returned. Otherwise
61 * 0 is returned. */
62 int rdbEncodeInteger(long long value, unsigned char *enc) {
63 /* Finally check if it fits in our ranges */
64 if (value >= -(1<<7) && value <= (1<<7)-1) {
65 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
66 enc[1] = value&0xFF;
67 return 2;
68 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
69 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
70 enc[1] = value&0xFF;
71 enc[2] = (value>>8)&0xFF;
72 return 3;
73 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
74 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
75 enc[1] = value&0xFF;
76 enc[2] = (value>>8)&0xFF;
77 enc[3] = (value>>16)&0xFF;
78 enc[4] = (value>>24)&0xFF;
79 return 5;
80 } else {
81 return 0;
82 }
83 }
84
85 /* String objects in the form "2391" "-100" without any space and with a
86 * range of values that can fit in an 8, 16 or 32 bit signed value can be
87 * encoded as integers to save space */
88 int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
89 long long value;
90 char *endptr, buf[32];
91
92 /* Check if it's possible to encode this value as a number */
93 value = strtoll(s, &endptr, 10);
94 if (endptr[0] != '\0') return 0;
95 ll2string(buf,32,value);
96
97 /* If the number converted back into a string is not identical
98 * then it's not possible to encode the string as integer */
99 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
100
101 return rdbEncodeInteger(value,enc);
102 }
103
104 int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
105 size_t comprlen, outlen;
106 unsigned char byte;
107 int n, nwritten = 0;
108 void *out;
109
110 /* We require at least four bytes compression for this to be worth it */
111 if (len <= 4) return 0;
112 outlen = len-4;
113 if ((out = zmalloc(outlen+1)) == NULL) return 0;
114 comprlen = lzf_compress(s, len, out, outlen);
115 if (comprlen == 0) {
116 zfree(out);
117 return 0;
118 }
119 /* Data compressed! Let's save it on disk */
120 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
121 if ((n = rdbWriteRaw(fp,&byte,1)) == -1) goto writeerr;
122 nwritten += n;
123
124 if ((n = rdbSaveLen(fp,comprlen)) == -1) goto writeerr;
125 nwritten += n;
126
127 if ((n = rdbSaveLen(fp,len)) == -1) goto writeerr;
128 nwritten += n;
129
130 if ((n = rdbWriteRaw(fp,out,comprlen)) == -1) goto writeerr;
131 nwritten += n;
132
133 zfree(out);
134 return nwritten;
135
136 writeerr:
137 zfree(out);
138 return -1;
139 }
140
141 /* Save a string objet as [len][data] on disk. If the object is a string
142 * representation of an integer value we try to safe it in a special form */
143 int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
144 int enclen;
145 int n, nwritten = 0;
146
147 /* Try integer encoding */
148 if (len <= 11) {
149 unsigned char buf[5];
150 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
151 if (rdbWriteRaw(fp,buf,enclen) == -1) return -1;
152 return enclen;
153 }
154 }
155
156 /* Try LZF compression - under 20 bytes it's unable to compress even
157 * aaaaaaaaaaaaaaaaaa so skip it */
158 if (server.rdbcompression && len > 20) {
159 n = rdbSaveLzfStringObject(fp,s,len);
160 if (n == -1) return -1;
161 if (n > 0) return n;
162 /* Return value of 0 means data can't be compressed, save the old way */
163 }
164
165 /* Store verbatim */
166 if ((n = rdbSaveLen(fp,len)) == -1) return -1;
167 nwritten += n;
168 if (len > 0) {
169 if (rdbWriteRaw(fp,s,len) == -1) return -1;
170 nwritten += len;
171 }
172 return nwritten;
173 }
174
175 /* Save a long long value as either an encoded string or a string. */
176 int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
177 unsigned char buf[32];
178 int n, nwritten = 0;
179 int enclen = rdbEncodeInteger(value,buf);
180 if (enclen > 0) {
181 return rdbWriteRaw(fp,buf,enclen);
182 } else {
183 /* Encode as string */
184 enclen = ll2string((char*)buf,32,value);
185 redisAssert(enclen < 32);
186 if ((n = rdbSaveLen(fp,enclen)) == -1) return -1;
187 nwritten += n;
188 if ((n = rdbWriteRaw(fp,buf,enclen)) == -1) return -1;
189 nwritten += n;
190 }
191 return nwritten;
192 }
193
194 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
195 int rdbSaveStringObject(FILE *fp, robj *obj) {
196 /* Avoid to decode the object, then encode it again, if the
197 * object is alrady integer encoded. */
198 if (obj->encoding == REDIS_ENCODING_INT) {
199 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
200 } else {
201 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
202 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
203 }
204 }
205
206 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
207 * 8 bit integer specifing the length of the representation.
208 * This 8 bit integer has special values in order to specify the following
209 * conditions:
210 * 253: not a number
211 * 254: + inf
212 * 255: - inf
213 */
214 int rdbSaveDoubleValue(FILE *fp, double val) {
215 unsigned char buf[128];
216 int len;
217
218 if (isnan(val)) {
219 buf[0] = 253;
220 len = 1;
221 } else if (!isfinite(val)) {
222 len = 1;
223 buf[0] = (val < 0) ? 255 : 254;
224 } else {
225 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
226 /* Check if the float is in a safe range to be casted into a
227 * long long. We are assuming that long long is 64 bit here.
228 * Also we are assuming that there are no implementations around where
229 * double has precision < 52 bit.
230 *
231 * Under this assumptions we test if a double is inside an interval
232 * where casting to long long is safe. Then using two castings we
233 * make sure the decimal part is zero. If all this is true we use
234 * integer printing function that is much faster. */
235 double min = -4503599627370495; /* (2^52)-1 */
236 double max = 4503599627370496; /* -(2^52) */
237 if (val > min && val < max && val == ((double)((long long)val)))
238 ll2string((char*)buf+1,sizeof(buf),(long long)val);
239 else
240 #endif
241 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
242 buf[0] = strlen((char*)buf+1);
243 len = buf[0]+1;
244 }
245 return rdbWriteRaw(fp,buf,len);
246 }
247
248 /* Save a Redis object. */
249 int rdbSaveObject(FILE *fp, robj *o) {
250 int n, nwritten = 0;
251
252 if (o->type == REDIS_STRING) {
253 /* Save a string value */
254 if ((n = rdbSaveStringObject(fp,o)) == -1) return -1;
255 nwritten += n;
256 } else if (o->type == REDIS_LIST) {
257 /* Save a list value */
258 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
259 unsigned char *p;
260 unsigned char *vstr;
261 unsigned int vlen;
262 long long vlong;
263
264 if ((n = rdbSaveLen(fp,ziplistLen(o->ptr))) == -1) return -1;
265 nwritten += n;
266
267 p = ziplistIndex(o->ptr,0);
268 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
269 if (vstr) {
270 if ((n = rdbSaveRawString(fp,vstr,vlen)) == -1)
271 return -1;
272 nwritten += n;
273 } else {
274 if ((n = rdbSaveLongLongAsStringObject(fp,vlong)) == -1)
275 return -1;
276 nwritten += n;
277 }
278 p = ziplistNext(o->ptr,p);
279 }
280 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
281 list *list = o->ptr;
282 listIter li;
283 listNode *ln;
284
285 if ((n = rdbSaveLen(fp,listLength(list))) == -1) return -1;
286 nwritten += n;
287
288 listRewind(list,&li);
289 while((ln = listNext(&li))) {
290 robj *eleobj = listNodeValue(ln);
291 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
292 nwritten += n;
293 }
294 } else {
295 redisPanic("Unknown list encoding");
296 }
297 } else if (o->type == REDIS_SET) {
298 /* Save a set value */
299 if (o->encoding == REDIS_ENCODING_HT) {
300 dict *set = o->ptr;
301 dictIterator *di = dictGetIterator(set);
302 dictEntry *de;
303
304 if ((n = rdbSaveLen(fp,dictSize(set))) == -1) return -1;
305 nwritten += n;
306
307 while((de = dictNext(di)) != NULL) {
308 robj *eleobj = dictGetEntryKey(de);
309 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
310 nwritten += n;
311 }
312 dictReleaseIterator(di);
313 } else if (o->encoding == REDIS_ENCODING_INTSET) {
314 intset *is = o->ptr;
315 int64_t llval;
316 int i = 0;
317
318 if ((n = rdbSaveLen(fp,intsetLen(is))) == -1) return -1;
319 nwritten += n;
320
321 while(intsetGet(is,i++,&llval)) {
322 if ((n = rdbSaveLongLongAsStringObject(fp,llval)) == -1) return -1;
323 nwritten += n;
324 }
325 } else {
326 redisPanic("Unknown set encoding");
327 }
328 } else if (o->type == REDIS_ZSET) {
329 /* Save a set value */
330 zset *zs = o->ptr;
331 dictIterator *di = dictGetIterator(zs->dict);
332 dictEntry *de;
333
334 if ((n = rdbSaveLen(fp,dictSize(zs->dict))) == -1) return -1;
335 nwritten += n;
336
337 while((de = dictNext(di)) != NULL) {
338 robj *eleobj = dictGetEntryKey(de);
339 double *score = dictGetEntryVal(de);
340
341 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
342 nwritten += n;
343 if ((n = rdbSaveDoubleValue(fp,*score)) == -1) return -1;
344 nwritten += n;
345 }
346 dictReleaseIterator(di);
347 } else if (o->type == REDIS_HASH) {
348 /* Save a hash value */
349 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
350 unsigned char *p = zipmapRewind(o->ptr);
351 unsigned int count = zipmapLen(o->ptr);
352 unsigned char *key, *val;
353 unsigned int klen, vlen;
354
355 if ((n = rdbSaveLen(fp,count)) == -1) return -1;
356 nwritten += n;
357
358 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
359 if ((n = rdbSaveRawString(fp,key,klen)) == -1) return -1;
360 nwritten += n;
361 if ((n = rdbSaveRawString(fp,val,vlen)) == -1) return -1;
362 nwritten += n;
363 }
364 } else {
365 dictIterator *di = dictGetIterator(o->ptr);
366 dictEntry *de;
367
368 if ((n = rdbSaveLen(fp,dictSize((dict*)o->ptr))) == -1) return -1;
369 nwritten += n;
370
371 while((de = dictNext(di)) != NULL) {
372 robj *key = dictGetEntryKey(de);
373 robj *val = dictGetEntryVal(de);
374
375 if ((n = rdbSaveStringObject(fp,key)) == -1) return -1;
376 nwritten += n;
377 if ((n = rdbSaveStringObject(fp,val)) == -1) return -1;
378 nwritten += n;
379 }
380 dictReleaseIterator(di);
381 }
382 } else {
383 redisPanic("Unknown object type");
384 }
385 return nwritten;
386 }
387
388 /* Return the length the object will have on disk if saved with
389 * the rdbSaveObject() function. Currently we use a trick to get
390 * this length with very little changes to the code. In the future
391 * we could switch to a faster solution. */
392 off_t rdbSavedObjectLen(robj *o) {
393 int len = rdbSaveObject(NULL,o);
394 redisAssert(len != -1);
395 return len;
396 }
397
398 /* Save a key-value pair, with expire time, type, key, value.
399 * On error -1 is returned.
400 * On success if the key was actaully saved 1 is returned, otherwise 0
401 * is returned (the key was already expired). */
402 int rdbSaveKeyValuePair(FILE *fp, robj *key, robj *val,
403 time_t expiretime, time_t now)
404 {
405 /* Save the expire time */
406 if (expiretime != -1) {
407 /* If this key is already expired skip it */
408 if (expiretime < now) return 0;
409 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) return -1;
410 if (rdbSaveTime(fp,expiretime) == -1) return -1;
411 }
412 /* Save type, key, value */
413 if (rdbSaveType(fp,val->type) == -1) return -1;
414 if (rdbSaveStringObject(fp,key) == -1) return -1;
415 if (rdbSaveObject(fp,val) == -1) return -1;
416 return 1;
417 }
418
419 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
420 int rdbSave(char *filename) {
421 dictIterator *di = NULL;
422 dictEntry *de;
423 FILE *fp;
424 char tmpfile[256];
425 int j;
426 time_t now = time(NULL);
427
428 if (server.ds_enabled) {
429 cacheForcePointInTime();
430 return dsRdbSave(filename);
431 }
432
433 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
434 fp = fopen(tmpfile,"w");
435 if (!fp) {
436 redisLog(REDIS_WARNING, "Failed opening .rdb for saving: %s",
437 strerror(errno));
438 return REDIS_ERR;
439 }
440 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
441 for (j = 0; j < server.dbnum; j++) {
442 redisDb *db = server.db+j;
443 dict *d = db->dict;
444 if (dictSize(d) == 0) continue;
445 di = dictGetIterator(d);
446 if (!di) {
447 fclose(fp);
448 return REDIS_ERR;
449 }
450
451 /* Write the SELECT DB opcode */
452 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
453 if (rdbSaveLen(fp,j) == -1) goto werr;
454
455 /* Iterate this DB writing every entry */
456 while((de = dictNext(di)) != NULL) {
457 sds keystr = dictGetEntryKey(de);
458 robj key, *o = dictGetEntryVal(de);
459 time_t expire;
460
461 initStaticStringObject(key,keystr);
462 expire = getExpire(db,&key);
463 if (rdbSaveKeyValuePair(fp,&key,o,expire,now) == -1) goto werr;
464 }
465 dictReleaseIterator(di);
466 }
467 /* EOF opcode */
468 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
469
470 /* Make sure data will not remain on the OS's output buffers */
471 fflush(fp);
472 fsync(fileno(fp));
473 fclose(fp);
474
475 /* Use RENAME to make sure the DB file is changed atomically only
476 * if the generate DB file is ok. */
477 if (rename(tmpfile,filename) == -1) {
478 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
479 unlink(tmpfile);
480 return REDIS_ERR;
481 }
482 redisLog(REDIS_NOTICE,"DB saved on disk");
483 server.dirty = 0;
484 server.lastsave = time(NULL);
485 return REDIS_OK;
486
487 werr:
488 fclose(fp);
489 unlink(tmpfile);
490 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
491 if (di) dictReleaseIterator(di);
492 return REDIS_ERR;
493 }
494
495 int rdbSaveBackground(char *filename) {
496 pid_t childpid;
497
498 if (server.bgsavechildpid != -1 ||
499 server.bgsavethread != (pthread_t) -1) return REDIS_ERR;
500
501 server.dirty_before_bgsave = server.dirty;
502
503 if (server.ds_enabled) {
504 cacheForcePointInTime();
505 return dsRdbSaveBackground(filename);
506 }
507
508 if ((childpid = fork()) == 0) {
509 int retval;
510
511 /* Child */
512 if (server.ipfd > 0) close(server.ipfd);
513 if (server.sofd > 0) close(server.sofd);
514 retval = rdbSave(filename);
515 _exit((retval == REDIS_OK) ? 0 : 1);
516 } else {
517 /* Parent */
518 if (childpid == -1) {
519 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
520 strerror(errno));
521 return REDIS_ERR;
522 }
523 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
524 server.bgsavechildpid = childpid;
525 updateDictResizePolicy();
526 return REDIS_OK;
527 }
528 return REDIS_OK; /* unreached */
529 }
530
531 void rdbRemoveTempFile(pid_t childpid) {
532 char tmpfile[256];
533
534 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
535 unlink(tmpfile);
536 }
537
538 int rdbLoadType(FILE *fp) {
539 unsigned char type;
540 if (fread(&type,1,1,fp) == 0) return -1;
541 return type;
542 }
543
544 time_t rdbLoadTime(FILE *fp) {
545 int32_t t32;
546 if (fread(&t32,4,1,fp) == 0) return -1;
547 return (time_t) t32;
548 }
549
550 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
551 * of this file for a description of how this are stored on disk.
552 *
553 * isencoded is set to 1 if the readed length is not actually a length but
554 * an "encoding type", check the above comments for more info */
555 uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
556 unsigned char buf[2];
557 uint32_t len;
558 int type;
559
560 if (isencoded) *isencoded = 0;
561 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
562 type = (buf[0]&0xC0)>>6;
563 if (type == REDIS_RDB_6BITLEN) {
564 /* Read a 6 bit len */
565 return buf[0]&0x3F;
566 } else if (type == REDIS_RDB_ENCVAL) {
567 /* Read a 6 bit len encoding type */
568 if (isencoded) *isencoded = 1;
569 return buf[0]&0x3F;
570 } else if (type == REDIS_RDB_14BITLEN) {
571 /* Read a 14 bit len */
572 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
573 return ((buf[0]&0x3F)<<8)|buf[1];
574 } else {
575 /* Read a 32 bit len */
576 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
577 return ntohl(len);
578 }
579 }
580
581 /* Load an integer-encoded object from file 'fp', with the specified
582 * encoding type 'enctype'. If encode is true the function may return
583 * an integer-encoded object as reply, otherwise the returned object
584 * will always be encoded as a raw string. */
585 robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
586 unsigned char enc[4];
587 long long val;
588
589 if (enctype == REDIS_RDB_ENC_INT8) {
590 if (fread(enc,1,1,fp) == 0) return NULL;
591 val = (signed char)enc[0];
592 } else if (enctype == REDIS_RDB_ENC_INT16) {
593 uint16_t v;
594 if (fread(enc,2,1,fp) == 0) return NULL;
595 v = enc[0]|(enc[1]<<8);
596 val = (int16_t)v;
597 } else if (enctype == REDIS_RDB_ENC_INT32) {
598 uint32_t v;
599 if (fread(enc,4,1,fp) == 0) return NULL;
600 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
601 val = (int32_t)v;
602 } else {
603 val = 0; /* anti-warning */
604 redisPanic("Unknown RDB integer encoding type");
605 }
606 if (encode)
607 return createStringObjectFromLongLong(val);
608 else
609 return createObject(REDIS_STRING,sdsfromlonglong(val));
610 }
611
612 robj *rdbLoadLzfStringObject(FILE*fp) {
613 unsigned int len, clen;
614 unsigned char *c = NULL;
615 sds val = NULL;
616
617 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
618 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
619 if ((c = zmalloc(clen)) == NULL) goto err;
620 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
621 if (fread(c,clen,1,fp) == 0) goto err;
622 if (lzf_decompress(c,clen,val,len) == 0) goto err;
623 zfree(c);
624 return createObject(REDIS_STRING,val);
625 err:
626 zfree(c);
627 sdsfree(val);
628 return NULL;
629 }
630
631 robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
632 int isencoded;
633 uint32_t len;
634 sds val;
635
636 len = rdbLoadLen(fp,&isencoded);
637 if (isencoded) {
638 switch(len) {
639 case REDIS_RDB_ENC_INT8:
640 case REDIS_RDB_ENC_INT16:
641 case REDIS_RDB_ENC_INT32:
642 return rdbLoadIntegerObject(fp,len,encode);
643 case REDIS_RDB_ENC_LZF:
644 return rdbLoadLzfStringObject(fp);
645 default:
646 redisPanic("Unknown RDB encoding type");
647 }
648 }
649
650 if (len == REDIS_RDB_LENERR) return NULL;
651 val = sdsnewlen(NULL,len);
652 if (len && fread(val,len,1,fp) == 0) {
653 sdsfree(val);
654 return NULL;
655 }
656 return createObject(REDIS_STRING,val);
657 }
658
659 robj *rdbLoadStringObject(FILE *fp) {
660 return rdbGenericLoadStringObject(fp,0);
661 }
662
663 robj *rdbLoadEncodedStringObject(FILE *fp) {
664 return rdbGenericLoadStringObject(fp,1);
665 }
666
667 /* For information about double serialization check rdbSaveDoubleValue() */
668 int rdbLoadDoubleValue(FILE *fp, double *val) {
669 char buf[128];
670 unsigned char len;
671
672 if (fread(&len,1,1,fp) == 0) return -1;
673 switch(len) {
674 case 255: *val = R_NegInf; return 0;
675 case 254: *val = R_PosInf; return 0;
676 case 253: *val = R_Nan; return 0;
677 default:
678 if (fread(buf,len,1,fp) == 0) return -1;
679 buf[len] = '\0';
680 sscanf(buf, "%lg", val);
681 return 0;
682 }
683 }
684
685 /* Load a Redis object of the specified type from the specified file.
686 * On success a newly allocated object is returned, otherwise NULL. */
687 robj *rdbLoadObject(int type, FILE *fp) {
688 robj *o, *ele, *dec;
689 size_t len;
690 unsigned int i;
691
692 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
693 if (type == REDIS_STRING) {
694 /* Read string value */
695 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
696 o = tryObjectEncoding(o);
697 } else if (type == REDIS_LIST) {
698 /* Read list value */
699 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
700
701 /* Use a real list when there are too many entries */
702 if (len > server.list_max_ziplist_entries) {
703 o = createListObject();
704 } else {
705 o = createZiplistObject();
706 }
707
708 /* Load every single element of the list */
709 while(len--) {
710 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
711
712 /* If we are using a ziplist and the value is too big, convert
713 * the object to a real list. */
714 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
715 ele->encoding == REDIS_ENCODING_RAW &&
716 sdslen(ele->ptr) > server.list_max_ziplist_value)
717 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
718
719 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
720 dec = getDecodedObject(ele);
721 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
722 decrRefCount(dec);
723 decrRefCount(ele);
724 } else {
725 ele = tryObjectEncoding(ele);
726 listAddNodeTail(o->ptr,ele);
727 }
728 }
729 } else if (type == REDIS_SET) {
730 /* Read list/set value */
731 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
732
733 /* Use a regular set when there are too many entries. */
734 if (len > server.set_max_intset_entries) {
735 o = createSetObject();
736 /* It's faster to expand the dict to the right size asap in order
737 * to avoid rehashing */
738 if (len > DICT_HT_INITIAL_SIZE)
739 dictExpand(o->ptr,len);
740 } else {
741 o = createIntsetObject();
742 }
743
744 /* Load every single element of the list/set */
745 for (i = 0; i < len; i++) {
746 long long llval;
747 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
748 ele = tryObjectEncoding(ele);
749
750 if (o->encoding == REDIS_ENCODING_INTSET) {
751 /* Fetch integer value from element */
752 if (isObjectRepresentableAsLongLong(ele,&llval) == REDIS_OK) {
753 o->ptr = intsetAdd(o->ptr,llval,NULL);
754 } else {
755 setTypeConvert(o,REDIS_ENCODING_HT);
756 dictExpand(o->ptr,len);
757 }
758 }
759
760 /* This will also be called when the set was just converted
761 * to regular hashtable encoded set */
762 if (o->encoding == REDIS_ENCODING_HT) {
763 dictAdd((dict*)o->ptr,ele,NULL);
764 } else {
765 decrRefCount(ele);
766 }
767 }
768 } else if (type == REDIS_ZSET) {
769 /* Read list/set value */
770 size_t zsetlen;
771 zset *zs;
772
773 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
774 o = createZsetObject();
775 zs = o->ptr;
776 /* Load every single element of the list/set */
777 while(zsetlen--) {
778 robj *ele;
779 double score;
780 zskiplistNode *znode;
781
782 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
783 ele = tryObjectEncoding(ele);
784 if (rdbLoadDoubleValue(fp,&score) == -1) return NULL;
785 znode = zslInsert(zs->zsl,score,ele);
786 dictAdd(zs->dict,ele,&znode->score);
787 incrRefCount(ele); /* added to skiplist */
788 }
789 } else if (type == REDIS_HASH) {
790 size_t hashlen;
791
792 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
793 o = createHashObject();
794 /* Too many entries? Use an hash table. */
795 if (hashlen > server.hash_max_zipmap_entries)
796 convertToRealHash(o);
797 /* Load every key/value, then set it into the zipmap or hash
798 * table, as needed. */
799 while(hashlen--) {
800 robj *key, *val;
801
802 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
803 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
804 /* If we are using a zipmap and there are too big values
805 * the object is converted to real hash table encoding. */
806 if (o->encoding != REDIS_ENCODING_HT &&
807 ((key->encoding == REDIS_ENCODING_RAW &&
808 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
809 (val->encoding == REDIS_ENCODING_RAW &&
810 sdslen(val->ptr) > server.hash_max_zipmap_value)))
811 {
812 convertToRealHash(o);
813 }
814
815 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
816 unsigned char *zm = o->ptr;
817 robj *deckey, *decval;
818
819 /* We need raw string objects to add them to the zipmap */
820 deckey = getDecodedObject(key);
821 decval = getDecodedObject(val);
822 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
823 decval->ptr,sdslen(decval->ptr),NULL);
824 o->ptr = zm;
825 decrRefCount(deckey);
826 decrRefCount(decval);
827 decrRefCount(key);
828 decrRefCount(val);
829 } else {
830 key = tryObjectEncoding(key);
831 val = tryObjectEncoding(val);
832 dictAdd((dict*)o->ptr,key,val);
833 }
834 }
835 } else {
836 redisPanic("Unknown object type");
837 }
838 return o;
839 }
840
841 /* Mark that we are loading in the global state and setup the fields
842 * needed to provide loading stats. */
843 void startLoading(FILE *fp) {
844 struct stat sb;
845
846 /* Load the DB */
847 server.loading = 1;
848 server.loading_start_time = time(NULL);
849 if (fstat(fileno(fp), &sb) == -1) {
850 server.loading_total_bytes = 1; /* just to avoid division by zero */
851 } else {
852 server.loading_total_bytes = sb.st_size;
853 }
854 }
855
856 /* Refresh the loading progress info */
857 void loadingProgress(off_t pos) {
858 server.loading_loaded_bytes = pos;
859 }
860
861 /* Loading finished */
862 void stopLoading(void) {
863 server.loading = 0;
864 }
865
866 int rdbLoad(char *filename) {
867 FILE *fp;
868 uint32_t dbid;
869 int type, retval, rdbver;
870 redisDb *db = server.db+0;
871 char buf[1024];
872 time_t expiretime, now = time(NULL);
873 long loops = 0;
874
875 fp = fopen(filename,"r");
876 if (!fp) return REDIS_ERR;
877 if (fread(buf,9,1,fp) == 0) goto eoferr;
878 buf[9] = '\0';
879 if (memcmp(buf,"REDIS",5) != 0) {
880 fclose(fp);
881 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
882 return REDIS_ERR;
883 }
884 rdbver = atoi(buf+5);
885 if (rdbver != 1) {
886 fclose(fp);
887 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
888 return REDIS_ERR;
889 }
890
891 startLoading(fp);
892 while(1) {
893 robj *key, *val;
894 expiretime = -1;
895
896 /* Serve the clients from time to time */
897 if (!(loops++ % 1000)) {
898 loadingProgress(ftello(fp));
899 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
900 }
901
902 /* Read type. */
903 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
904 if (type == REDIS_EXPIRETIME) {
905 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
906 /* We read the time so we need to read the object type again */
907 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
908 }
909 if (type == REDIS_EOF) break;
910 /* Handle SELECT DB opcode as a special case */
911 if (type == REDIS_SELECTDB) {
912 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
913 goto eoferr;
914 if (dbid >= (unsigned)server.dbnum) {
915 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
916 exit(1);
917 }
918 db = server.db+dbid;
919 continue;
920 }
921 /* Read key */
922 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
923 /* Read value */
924 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
925 /* Check if the key already expired */
926 if (expiretime != -1 && expiretime < now) {
927 decrRefCount(key);
928 decrRefCount(val);
929 continue;
930 }
931 /* Add the new object in the hash table */
932 retval = dbAdd(db,key,val);
933 if (retval == REDIS_ERR) {
934 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
935 exit(1);
936 }
937 /* Set the expire time if needed */
938 if (expiretime != -1) setExpire(db,key,expiretime);
939
940 decrRefCount(key);
941 }
942 fclose(fp);
943 stopLoading();
944 return REDIS_OK;
945
946 eoferr: /* unexpected end of file is handled here with a fatal exit */
947 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
948 exit(1);
949 return REDIS_ERR; /* Just to avoid warning */
950 }
951
952 /* A background saving child (BGSAVE) terminated its work. Handle this. */
953 void backgroundSaveDoneHandler(int exitcode, int bysignal) {
954 if (!bysignal && exitcode == 0) {
955 redisLog(REDIS_NOTICE,
956 "Background saving terminated with success");
957 server.dirty = server.dirty - server.dirty_before_bgsave;
958 server.lastsave = time(NULL);
959 } else if (!bysignal && exitcode != 0) {
960 redisLog(REDIS_WARNING, "Background saving error");
961 } else {
962 redisLog(REDIS_WARNING,
963 "Background saving terminated by signal %d", bysignal);
964 rdbRemoveTempFile(server.bgsavechildpid);
965 }
966 server.bgsavechildpid = -1;
967 server.bgsavethread = (pthread_t) -1;
968 server.bgsavethread_state = REDIS_BGSAVE_THREAD_UNACTIVE;
969 /* Possibly there are slaves waiting for a BGSAVE in order to be served
970 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
971 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
972 }
973
974 void saveCommand(redisClient *c) {
975 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread_t)-1) {
976 addReplyError(c,"Background save already in progress");
977 return;
978 }
979 if (rdbSave(server.dbfilename) == REDIS_OK) {
980 addReply(c,shared.ok);
981 } else {
982 addReply(c,shared.err);
983 }
984 }
985
986 void bgsaveCommand(redisClient *c) {
987 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread_t)-1) {
988 addReplyError(c,"Background save already in progress");
989 return;
990 }
991 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
992 addReplyStatus(c,"Background saving started");
993 } else {
994 addReply(c,shared.err);
995 }
996 }