2 #include "lzf.h" /* LZF compression library */
7 #include <sys/resource.h>
11 int rdbSaveType(FILE *fp
, unsigned char type
) {
12 if (fwrite(&type
,1,1,fp
) == 0) return -1;
16 int rdbSaveTime(FILE *fp
, time_t t
) {
17 int32_t t32
= (int32_t) t
;
18 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
22 /* check rdbLoadLen() comments for more info */
23 int rdbSaveLen(FILE *fp
, uint32_t len
) {
27 /* Save a 6 bit len */
28 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
29 if (fwrite(buf
,1,1,fp
) == 0) return -1;
30 } else if (len
< (1<<14)) {
31 /* Save a 14 bit len */
32 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
34 if (fwrite(buf
,2,1,fp
) == 0) return -1;
36 /* Save a 32 bit len */
37 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
38 if (fwrite(buf
,1,1,fp
) == 0) return -1;
40 if (fwrite(&len
,4,1,fp
) == 0) return -1;
45 /* Encode 'value' as an integer if possible (if integer will fit the
46 * supported range). If the function sucessful encoded the integer
47 * then the (up to 5 bytes) encoded representation is written in the
48 * string pointed by 'enc' and the length is returned. Otherwise
50 int rdbEncodeInteger(long long value
, unsigned char *enc
) {
51 /* Finally check if it fits in our ranges */
52 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
53 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
56 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
57 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
59 enc
[2] = (value
>>8)&0xFF;
61 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
62 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
64 enc
[2] = (value
>>8)&0xFF;
65 enc
[3] = (value
>>16)&0xFF;
66 enc
[4] = (value
>>24)&0xFF;
73 /* String objects in the form "2391" "-100" without any space and with a
74 * range of values that can fit in an 8, 16 or 32 bit signed value can be
75 * encoded as integers to save space */
76 int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
78 char *endptr
, buf
[32];
80 /* Check if it's possible to encode this value as a number */
81 value
= strtoll(s
, &endptr
, 10);
82 if (endptr
[0] != '\0') return 0;
83 ll2string(buf
,32,value
);
85 /* If the number converted back into a string is not identical
86 * then it's not possible to encode the string as integer */
87 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
89 return rdbEncodeInteger(value
,enc
);
92 int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
93 size_t comprlen
, outlen
;
97 /* We require at least four bytes compression for this to be worth it */
98 if (len
<= 4) return 0;
100 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
101 comprlen
= lzf_compress(s
, len
, out
, outlen
);
106 /* Data compressed! Let's save it on disk */
107 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
108 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
109 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
110 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
111 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
120 /* Save a string objet as [len][data] on disk. If the object is a string
121 * representation of an integer value we try to safe it in a special form */
122 int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
125 /* Try integer encoding */
127 unsigned char buf
[5];
128 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
129 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
134 /* Try LZF compression - under 20 bytes it's unable to compress even
135 * aaaaaaaaaaaaaaaaaa so skip it */
136 if (server
.rdbcompression
&& len
> 20) {
139 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
140 if (retval
== -1) return -1;
141 if (retval
> 0) return 0;
142 /* retval == 0 means data can't be compressed, save the old way */
146 if (rdbSaveLen(fp
,len
) == -1) return -1;
147 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
151 /* Save a long long value as either an encoded string or a string. */
152 int rdbSaveLongLongAsStringObject(FILE *fp
, long long value
) {
153 unsigned char buf
[32];
154 int enclen
= rdbEncodeInteger(value
,buf
);
156 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
158 /* Encode as string */
159 enclen
= ll2string((char*)buf
,32,value
);
160 redisAssert(enclen
< 32);
161 if (rdbSaveLen(fp
,enclen
) == -1) return -1;
162 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
167 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
168 int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
169 /* Avoid to decode the object, then encode it again, if the
170 * object is alrady integer encoded. */
171 if (obj
->encoding
== REDIS_ENCODING_INT
) {
172 return rdbSaveLongLongAsStringObject(fp
,(long)obj
->ptr
);
174 redisAssert(obj
->encoding
== REDIS_ENCODING_RAW
);
175 return rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
179 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
180 * 8 bit integer specifing the length of the representation.
181 * This 8 bit integer has special values in order to specify the following
187 int rdbSaveDoubleValue(FILE *fp
, double val
) {
188 unsigned char buf
[128];
194 } else if (!isfinite(val
)) {
196 buf
[0] = (val
< 0) ? 255 : 254;
198 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
199 /* Check if the float is in a safe range to be casted into a
200 * long long. We are assuming that long long is 64 bit here.
201 * Also we are assuming that there are no implementations around where
202 * double has precision < 52 bit.
204 * Under this assumptions we test if a double is inside an interval
205 * where casting to long long is safe. Then using two castings we
206 * make sure the decimal part is zero. If all this is true we use
207 * integer printing function that is much faster. */
208 double min
= -4503599627370495; /* (2^52)-1 */
209 double max
= 4503599627370496; /* -(2^52) */
210 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
211 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
214 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
215 buf
[0] = strlen((char*)buf
+1);
218 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
222 /* Save a Redis object. */
223 int rdbSaveObject(FILE *fp
, robj
*o
) {
224 if (o
->type
== REDIS_STRING
) {
225 /* Save a string value */
226 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
227 } else if (o
->type
== REDIS_LIST
) {
228 /* Save a list value */
229 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
235 if (rdbSaveLen(fp
,ziplistLen(o
->ptr
)) == -1) return -1;
236 p
= ziplistIndex(o
->ptr
,0);
237 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
239 if (rdbSaveRawString(fp
,vstr
,vlen
) == -1)
242 if (rdbSaveLongLongAsStringObject(fp
,vlong
) == -1)
245 p
= ziplistNext(o
->ptr
,p
);
247 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
252 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
253 listRewind(list
,&li
);
254 while((ln
= listNext(&li
))) {
255 robj
*eleobj
= listNodeValue(ln
);
256 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
259 redisPanic("Unknown list encoding");
261 } else if (o
->type
== REDIS_SET
) {
262 /* Save a set value */
263 if (o
->encoding
== REDIS_ENCODING_HT
) {
265 dictIterator
*di
= dictGetIterator(set
);
268 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
269 while((de
= dictNext(di
)) != NULL
) {
270 robj
*eleobj
= dictGetEntryKey(de
);
271 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
273 dictReleaseIterator(di
);
274 } else if (o
->encoding
== REDIS_ENCODING_INTSET
) {
279 if (rdbSaveLen(fp
,intsetLen(is
)) == -1) return -1;
280 while(intsetGet(is
,i
++,&llval
)) {
281 if (rdbSaveLongLongAsStringObject(fp
,llval
) == -1) return -1;
284 redisPanic("Unknown set encoding");
286 } else if (o
->type
== REDIS_ZSET
) {
287 /* Save a set value */
289 dictIterator
*di
= dictGetIterator(zs
->dict
);
292 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
293 while((de
= dictNext(di
)) != NULL
) {
294 robj
*eleobj
= dictGetEntryKey(de
);
295 double *score
= dictGetEntryVal(de
);
297 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
298 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
300 dictReleaseIterator(di
);
301 } else if (o
->type
== REDIS_HASH
) {
302 /* Save a hash value */
303 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
304 unsigned char *p
= zipmapRewind(o
->ptr
);
305 unsigned int count
= zipmapLen(o
->ptr
);
306 unsigned char *key
, *val
;
307 unsigned int klen
, vlen
;
309 if (rdbSaveLen(fp
,count
) == -1) return -1;
310 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
311 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
312 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
315 dictIterator
*di
= dictGetIterator(o
->ptr
);
318 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
319 while((de
= dictNext(di
)) != NULL
) {
320 robj
*key
= dictGetEntryKey(de
);
321 robj
*val
= dictGetEntryVal(de
);
323 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
324 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
326 dictReleaseIterator(di
);
329 redisPanic("Unknown object type");
334 /* Return the length the object will have on disk if saved with
335 * the rdbSaveObject() function. Currently we use a trick to get
336 * this length with very little changes to the code. In the future
337 * we could switch to a faster solution. */
338 off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
339 if (fp
== NULL
) fp
= server
.devnull
;
341 redisAssert(rdbSaveObject(fp
,o
) != 1);
345 /* Return the number of pages required to save this object in the swap file */
346 off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
347 off_t bytes
= rdbSavedObjectLen(o
,fp
);
349 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
352 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
353 int rdbSave(char *filename
) {
354 dictIterator
*di
= NULL
;
359 time_t now
= time(NULL
);
361 /* Wait for I/O therads to terminate, just in case this is a
362 * foreground-saving, to avoid seeking the swap file descriptor at the
364 if (server
.vm_enabled
)
365 waitEmptyIOJobsQueue();
367 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
368 fp
= fopen(tmpfile
,"w");
370 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
373 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
374 for (j
= 0; j
< server
.dbnum
; j
++) {
375 redisDb
*db
= server
.db
+j
;
377 if (dictSize(d
) == 0) continue;
378 di
= dictGetIterator(d
);
384 /* Write the SELECT DB opcode */
385 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
386 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
388 /* Iterate this DB writing every entry */
389 while((de
= dictNext(di
)) != NULL
) {
390 sds keystr
= dictGetEntryKey(de
);
391 robj key
, *o
= dictGetEntryVal(de
);
394 initStaticStringObject(key
,keystr
);
395 expiretime
= getExpire(db
,&key
);
397 /* Save the expire time */
398 if (expiretime
!= -1) {
399 /* If this key is already expired skip it */
400 if (expiretime
< now
) continue;
401 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
402 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
404 /* Save the key and associated value. This requires special
405 * handling if the value is swapped out. */
406 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
407 o
->storage
== REDIS_VM_SWAPPING
) {
408 /* Save type, key, value */
409 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
410 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
411 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
413 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
415 /* Get a preview of the object in memory */
416 po
= vmPreviewObject(o
);
417 /* Save type, key, value */
418 if (rdbSaveType(fp
,po
->type
) == -1) goto werr
;
419 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
420 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
421 /* Remove the loaded object from memory */
425 dictReleaseIterator(di
);
428 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
430 /* Make sure data will not remain on the OS's output buffers */
435 /* Use RENAME to make sure the DB file is changed atomically only
436 * if the generate DB file is ok. */
437 if (rename(tmpfile
,filename
) == -1) {
438 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
442 redisLog(REDIS_NOTICE
,"DB saved on disk");
444 server
.lastsave
= time(NULL
);
450 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
451 if (di
) dictReleaseIterator(di
);
455 int rdbSaveBackground(char *filename
) {
458 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
459 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
460 server
.dirty_before_bgsave
= server
.dirty
;
461 if ((childpid
= fork()) == 0) {
463 if (server
.vm_enabled
) vmReopenSwapFile();
464 if (server
.ipfd
> 0) close(server
.ipfd
);
465 if (server
.sofd
> 0) close(server
.sofd
);
466 if (rdbSave(filename
) == REDIS_OK
) {
473 if (childpid
== -1) {
474 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
478 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
479 server
.bgsavechildpid
= childpid
;
480 updateDictResizePolicy();
483 return REDIS_OK
; /* unreached */
486 void rdbRemoveTempFile(pid_t childpid
) {
489 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
493 int rdbLoadType(FILE *fp
) {
495 if (fread(&type
,1,1,fp
) == 0) return -1;
499 time_t rdbLoadTime(FILE *fp
) {
501 if (fread(&t32
,4,1,fp
) == 0) return -1;
505 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
506 * of this file for a description of how this are stored on disk.
508 * isencoded is set to 1 if the readed length is not actually a length but
509 * an "encoding type", check the above comments for more info */
510 uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
511 unsigned char buf
[2];
515 if (isencoded
) *isencoded
= 0;
516 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
517 type
= (buf
[0]&0xC0)>>6;
518 if (type
== REDIS_RDB_6BITLEN
) {
519 /* Read a 6 bit len */
521 } else if (type
== REDIS_RDB_ENCVAL
) {
522 /* Read a 6 bit len encoding type */
523 if (isencoded
) *isencoded
= 1;
525 } else if (type
== REDIS_RDB_14BITLEN
) {
526 /* Read a 14 bit len */
527 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
528 return ((buf
[0]&0x3F)<<8)|buf
[1];
530 /* Read a 32 bit len */
531 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
536 /* Load an integer-encoded object from file 'fp', with the specified
537 * encoding type 'enctype'. If encode is true the function may return
538 * an integer-encoded object as reply, otherwise the returned object
539 * will always be encoded as a raw string. */
540 robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
541 unsigned char enc
[4];
544 if (enctype
== REDIS_RDB_ENC_INT8
) {
545 if (fread(enc
,1,1,fp
) == 0) return NULL
;
546 val
= (signed char)enc
[0];
547 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
549 if (fread(enc
,2,1,fp
) == 0) return NULL
;
550 v
= enc
[0]|(enc
[1]<<8);
552 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
554 if (fread(enc
,4,1,fp
) == 0) return NULL
;
555 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
558 val
= 0; /* anti-warning */
559 redisPanic("Unknown RDB integer encoding type");
562 return createStringObjectFromLongLong(val
);
564 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
567 robj
*rdbLoadLzfStringObject(FILE*fp
) {
568 unsigned int len
, clen
;
569 unsigned char *c
= NULL
;
572 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
573 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
574 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
575 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
576 if (fread(c
,clen
,1,fp
) == 0) goto err
;
577 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
579 return createObject(REDIS_STRING
,val
);
586 robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
591 len
= rdbLoadLen(fp
,&isencoded
);
594 case REDIS_RDB_ENC_INT8
:
595 case REDIS_RDB_ENC_INT16
:
596 case REDIS_RDB_ENC_INT32
:
597 return rdbLoadIntegerObject(fp
,len
,encode
);
598 case REDIS_RDB_ENC_LZF
:
599 return rdbLoadLzfStringObject(fp
);
601 redisPanic("Unknown RDB encoding type");
605 if (len
== REDIS_RDB_LENERR
) return NULL
;
606 val
= sdsnewlen(NULL
,len
);
607 if (len
&& fread(val
,len
,1,fp
) == 0) {
611 return createObject(REDIS_STRING
,val
);
614 robj
*rdbLoadStringObject(FILE *fp
) {
615 return rdbGenericLoadStringObject(fp
,0);
618 robj
*rdbLoadEncodedStringObject(FILE *fp
) {
619 return rdbGenericLoadStringObject(fp
,1);
622 /* For information about double serialization check rdbSaveDoubleValue() */
623 int rdbLoadDoubleValue(FILE *fp
, double *val
) {
627 if (fread(&len
,1,1,fp
) == 0) return -1;
629 case 255: *val
= R_NegInf
; return 0;
630 case 254: *val
= R_PosInf
; return 0;
631 case 253: *val
= R_Nan
; return 0;
633 if (fread(buf
,len
,1,fp
) == 0) return -1;
635 sscanf(buf
, "%lg", val
);
640 /* Load a Redis object of the specified type from the specified file.
641 * On success a newly allocated object is returned, otherwise NULL. */
642 robj
*rdbLoadObject(int type
, FILE *fp
) {
647 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
648 if (type
== REDIS_STRING
) {
649 /* Read string value */
650 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
651 o
= tryObjectEncoding(o
);
652 } else if (type
== REDIS_LIST
) {
653 /* Read list value */
654 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
656 /* Use a real list when there are too many entries */
657 if (len
> server
.list_max_ziplist_entries
) {
658 o
= createListObject();
660 o
= createZiplistObject();
663 /* Load every single element of the list */
665 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
667 /* If we are using a ziplist and the value is too big, convert
668 * the object to a real list. */
669 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
&&
670 ele
->encoding
== REDIS_ENCODING_RAW
&&
671 sdslen(ele
->ptr
) > server
.list_max_ziplist_value
)
672 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
674 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
675 dec
= getDecodedObject(ele
);
676 o
->ptr
= ziplistPush(o
->ptr
,dec
->ptr
,sdslen(dec
->ptr
),REDIS_TAIL
);
680 ele
= tryObjectEncoding(ele
);
681 listAddNodeTail(o
->ptr
,ele
);
684 } else if (type
== REDIS_SET
) {
685 /* Read list/set value */
686 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
688 /* Use a regular set when there are too many entries. */
689 if (len
> server
.set_max_intset_entries
) {
690 o
= createSetObject();
691 /* It's faster to expand the dict to the right size asap in order
692 * to avoid rehashing */
693 if (len
> DICT_HT_INITIAL_SIZE
)
694 dictExpand(o
->ptr
,len
);
696 o
= createIntsetObject();
699 /* Load every single element of the list/set */
700 for (i
= 0; i
< len
; i
++) {
702 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
703 ele
= tryObjectEncoding(ele
);
705 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
706 /* Fetch integer value from element */
707 if (isObjectRepresentableAsLongLong(ele
,&llval
) == REDIS_OK
) {
708 o
->ptr
= intsetAdd(o
->ptr
,llval
,NULL
);
710 setTypeConvert(o
,REDIS_ENCODING_HT
);
711 dictExpand(o
->ptr
,len
);
715 /* This will also be called when the set was just converted
716 * to regular hashtable encoded set */
717 if (o
->encoding
== REDIS_ENCODING_HT
) {
718 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
723 } else if (type
== REDIS_ZSET
) {
724 /* Read list/set value */
728 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
729 o
= createZsetObject();
731 /* Load every single element of the list/set */
735 zskiplistNode
*znode
;
737 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
738 ele
= tryObjectEncoding(ele
);
739 if (rdbLoadDoubleValue(fp
,&score
) == -1) return NULL
;
740 znode
= zslInsert(zs
->zsl
,score
,ele
);
741 dictAdd(zs
->dict
,ele
,&znode
->score
);
742 incrRefCount(ele
); /* added to skiplist */
744 } else if (type
== REDIS_HASH
) {
747 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
748 o
= createHashObject();
749 /* Too many entries? Use an hash table. */
750 if (hashlen
> server
.hash_max_zipmap_entries
)
751 convertToRealHash(o
);
752 /* Load every key/value, then set it into the zipmap or hash
753 * table, as needed. */
757 if ((key
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
758 if ((val
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
759 /* If we are using a zipmap and there are too big values
760 * the object is converted to real hash table encoding. */
761 if (o
->encoding
!= REDIS_ENCODING_HT
&&
762 ((key
->encoding
== REDIS_ENCODING_RAW
&&
763 sdslen(key
->ptr
) > server
.hash_max_zipmap_value
) ||
764 (val
->encoding
== REDIS_ENCODING_RAW
&&
765 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)))
767 convertToRealHash(o
);
770 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
771 unsigned char *zm
= o
->ptr
;
772 robj
*deckey
, *decval
;
774 /* We need raw string objects to add them to the zipmap */
775 deckey
= getDecodedObject(key
);
776 decval
= getDecodedObject(val
);
777 zm
= zipmapSet(zm
,deckey
->ptr
,sdslen(deckey
->ptr
),
778 decval
->ptr
,sdslen(decval
->ptr
),NULL
);
780 decrRefCount(deckey
);
781 decrRefCount(decval
);
785 key
= tryObjectEncoding(key
);
786 val
= tryObjectEncoding(val
);
787 dictAdd((dict
*)o
->ptr
,key
,val
);
791 redisPanic("Unknown object type");
796 int rdbLoad(char *filename
) {
799 int type
, retval
, rdbver
;
800 int swap_all_values
= 0;
801 redisDb
*db
= server
.db
+0;
803 time_t expiretime
, now
= time(NULL
);
805 fp
= fopen(filename
,"r");
806 if (!fp
) return REDIS_ERR
;
807 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
809 if (memcmp(buf
,"REDIS",5) != 0) {
811 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
814 rdbver
= atoi(buf
+5);
817 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
826 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
827 if (type
== REDIS_EXPIRETIME
) {
828 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
829 /* We read the time so we need to read the object type again */
830 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
832 if (type
== REDIS_EOF
) break;
833 /* Handle SELECT DB opcode as a special case */
834 if (type
== REDIS_SELECTDB
) {
835 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
837 if (dbid
>= (unsigned)server
.dbnum
) {
838 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
845 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
847 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
848 /* Check if the key already expired */
849 if (expiretime
!= -1 && expiretime
< now
) {
854 /* Add the new object in the hash table */
855 retval
= dbAdd(db
,key
,val
);
856 if (retval
== REDIS_ERR
) {
857 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
860 /* Set the expire time if needed */
861 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
863 /* Handle swapping while loading big datasets when VM is on */
865 /* If we detecter we are hopeless about fitting something in memory
866 * we just swap every new key on disk. Directly...
867 * Note that's important to check for this condition before resorting
868 * to random sampling, otherwise we may try to swap already
870 if (swap_all_values
) {
871 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
873 /* de may be NULL since the key already expired */
876 val
= dictGetEntryVal(de
);
878 if (val
->refcount
== 1 &&
879 (vp
= vmSwapObjectBlocking(val
)) != NULL
)
880 dictGetEntryVal(de
) = vp
;
887 /* Flush data on disk once 32 MB of additional RAM are used... */
889 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
892 /* If we have still some hope of having some value fitting memory
893 * then we try random sampling. */
894 if (!swap_all_values
&& server
.vm_enabled
&& force_swapout
) {
895 while (zmalloc_used_memory() > server
.vm_max_memory
) {
896 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
898 if (zmalloc_used_memory() > server
.vm_max_memory
)
899 swap_all_values
= 1; /* We are already using too much mem */
905 eoferr
: /* unexpected end of file is handled here with a fatal exit */
906 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
908 return REDIS_ERR
; /* Just to avoid warning */
911 /* A background saving child (BGSAVE) terminated its work. Handle this. */
912 void backgroundSaveDoneHandler(int statloc
) {
913 int exitcode
= WEXITSTATUS(statloc
);
914 int bysignal
= WIFSIGNALED(statloc
);
916 if (!bysignal
&& exitcode
== 0) {
917 redisLog(REDIS_NOTICE
,
918 "Background saving terminated with success");
919 server
.dirty
= server
.dirty
- server
.dirty_before_bgsave
;
920 server
.lastsave
= time(NULL
);
921 } else if (!bysignal
&& exitcode
!= 0) {
922 redisLog(REDIS_WARNING
, "Background saving error");
924 redisLog(REDIS_WARNING
,
925 "Background saving terminated by signal %d", WTERMSIG(statloc
));
926 rdbRemoveTempFile(server
.bgsavechildpid
);
928 server
.bgsavechildpid
= -1;
929 /* Possibly there are slaves waiting for a BGSAVE in order to be served
930 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
931 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);