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 */
264 dictIterator
*di
= dictGetIterator(set
);
267 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
268 while((de
= dictNext(di
)) != NULL
) {
269 robj
*eleobj
= dictGetEntryKey(de
);
271 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
273 dictReleaseIterator(di
);
274 } else if (o
->type
== REDIS_ZSET
) {
275 /* Save a set value */
277 dictIterator
*di
= dictGetIterator(zs
->dict
);
280 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
281 while((de
= dictNext(di
)) != NULL
) {
282 robj
*eleobj
= dictGetEntryKey(de
);
283 double *score
= dictGetEntryVal(de
);
285 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
286 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
288 dictReleaseIterator(di
);
289 } else if (o
->type
== REDIS_HASH
) {
290 /* Save a hash value */
291 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
292 unsigned char *p
= zipmapRewind(o
->ptr
);
293 unsigned int count
= zipmapLen(o
->ptr
);
294 unsigned char *key
, *val
;
295 unsigned int klen
, vlen
;
297 if (rdbSaveLen(fp
,count
) == -1) return -1;
298 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
299 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
300 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
303 dictIterator
*di
= dictGetIterator(o
->ptr
);
306 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
307 while((de
= dictNext(di
)) != NULL
) {
308 robj
*key
= dictGetEntryKey(de
);
309 robj
*val
= dictGetEntryVal(de
);
311 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
312 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
314 dictReleaseIterator(di
);
317 redisPanic("Unknown object type");
322 /* Return the length the object will have on disk if saved with
323 * the rdbSaveObject() function. Currently we use a trick to get
324 * this length with very little changes to the code. In the future
325 * we could switch to a faster solution. */
326 off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
327 if (fp
== NULL
) fp
= server
.devnull
;
329 redisAssert(rdbSaveObject(fp
,o
) != 1);
333 /* Return the number of pages required to save this object in the swap file */
334 off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
335 off_t bytes
= rdbSavedObjectLen(o
,fp
);
337 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
340 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
341 int rdbSave(char *filename
) {
342 dictIterator
*di
= NULL
;
347 time_t now
= time(NULL
);
349 /* Wait for I/O therads to terminate, just in case this is a
350 * foreground-saving, to avoid seeking the swap file descriptor at the
352 if (server
.vm_enabled
)
353 waitEmptyIOJobsQueue();
355 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
356 fp
= fopen(tmpfile
,"w");
358 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
361 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
362 for (j
= 0; j
< server
.dbnum
; j
++) {
363 redisDb
*db
= server
.db
+j
;
365 if (dictSize(d
) == 0) continue;
366 di
= dictGetIterator(d
);
372 /* Write the SELECT DB opcode */
373 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
374 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
376 /* Iterate this DB writing every entry */
377 while((de
= dictNext(di
)) != NULL
) {
378 sds keystr
= dictGetEntryKey(de
);
379 robj key
, *o
= dictGetEntryVal(de
);
382 initStaticStringObject(key
,keystr
);
383 expiretime
= getExpire(db
,&key
);
385 /* Save the expire time */
386 if (expiretime
!= -1) {
387 /* If this key is already expired skip it */
388 if (expiretime
< now
) continue;
389 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
390 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
392 /* Save the key and associated value. This requires special
393 * handling if the value is swapped out. */
394 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
395 o
->storage
== REDIS_VM_SWAPPING
) {
396 /* Save type, key, value */
397 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
398 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
399 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
401 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
403 /* Get a preview of the object in memory */
404 po
= vmPreviewObject(o
);
405 /* Save type, key, value */
406 if (rdbSaveType(fp
,po
->type
) == -1) goto werr
;
407 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
408 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
409 /* Remove the loaded object from memory */
413 dictReleaseIterator(di
);
416 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
418 /* Make sure data will not remain on the OS's output buffers */
423 /* Use RENAME to make sure the DB file is changed atomically only
424 * if the generate DB file is ok. */
425 if (rename(tmpfile
,filename
) == -1) {
426 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
430 redisLog(REDIS_NOTICE
,"DB saved on disk");
432 server
.lastsave
= time(NULL
);
438 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
439 if (di
) dictReleaseIterator(di
);
443 int rdbSaveBackground(char *filename
) {
446 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
447 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
448 if ((childpid
= fork()) == 0) {
450 if (server
.vm_enabled
) vmReopenSwapFile();
452 if (rdbSave(filename
) == REDIS_OK
) {
459 if (childpid
== -1) {
460 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
464 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
465 server
.bgsavechildpid
= childpid
;
466 updateDictResizePolicy();
469 return REDIS_OK
; /* unreached */
472 void rdbRemoveTempFile(pid_t childpid
) {
475 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
479 int rdbLoadType(FILE *fp
) {
481 if (fread(&type
,1,1,fp
) == 0) return -1;
485 time_t rdbLoadTime(FILE *fp
) {
487 if (fread(&t32
,4,1,fp
) == 0) return -1;
491 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
492 * of this file for a description of how this are stored on disk.
494 * isencoded is set to 1 if the readed length is not actually a length but
495 * an "encoding type", check the above comments for more info */
496 uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
497 unsigned char buf
[2];
501 if (isencoded
) *isencoded
= 0;
502 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
503 type
= (buf
[0]&0xC0)>>6;
504 if (type
== REDIS_RDB_6BITLEN
) {
505 /* Read a 6 bit len */
507 } else if (type
== REDIS_RDB_ENCVAL
) {
508 /* Read a 6 bit len encoding type */
509 if (isencoded
) *isencoded
= 1;
511 } else if (type
== REDIS_RDB_14BITLEN
) {
512 /* Read a 14 bit len */
513 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
514 return ((buf
[0]&0x3F)<<8)|buf
[1];
516 /* Read a 32 bit len */
517 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
522 /* Load an integer-encoded object from file 'fp', with the specified
523 * encoding type 'enctype'. If encode is true the function may return
524 * an integer-encoded object as reply, otherwise the returned object
525 * will always be encoded as a raw string. */
526 robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
527 unsigned char enc
[4];
530 if (enctype
== REDIS_RDB_ENC_INT8
) {
531 if (fread(enc
,1,1,fp
) == 0) return NULL
;
532 val
= (signed char)enc
[0];
533 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
535 if (fread(enc
,2,1,fp
) == 0) return NULL
;
536 v
= enc
[0]|(enc
[1]<<8);
538 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
540 if (fread(enc
,4,1,fp
) == 0) return NULL
;
541 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
544 val
= 0; /* anti-warning */
545 redisPanic("Unknown RDB integer encoding type");
548 return createStringObjectFromLongLong(val
);
550 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
553 robj
*rdbLoadLzfStringObject(FILE*fp
) {
554 unsigned int len
, clen
;
555 unsigned char *c
= NULL
;
558 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
559 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
560 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
561 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
562 if (fread(c
,clen
,1,fp
) == 0) goto err
;
563 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
565 return createObject(REDIS_STRING
,val
);
572 robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
577 len
= rdbLoadLen(fp
,&isencoded
);
580 case REDIS_RDB_ENC_INT8
:
581 case REDIS_RDB_ENC_INT16
:
582 case REDIS_RDB_ENC_INT32
:
583 return rdbLoadIntegerObject(fp
,len
,encode
);
584 case REDIS_RDB_ENC_LZF
:
585 return rdbLoadLzfStringObject(fp
);
587 redisPanic("Unknown RDB encoding type");
591 if (len
== REDIS_RDB_LENERR
) return NULL
;
592 val
= sdsnewlen(NULL
,len
);
593 if (len
&& fread(val
,len
,1,fp
) == 0) {
597 return createObject(REDIS_STRING
,val
);
600 robj
*rdbLoadStringObject(FILE *fp
) {
601 return rdbGenericLoadStringObject(fp
,0);
604 robj
*rdbLoadEncodedStringObject(FILE *fp
) {
605 return rdbGenericLoadStringObject(fp
,1);
608 /* For information about double serialization check rdbSaveDoubleValue() */
609 int rdbLoadDoubleValue(FILE *fp
, double *val
) {
613 if (fread(&len
,1,1,fp
) == 0) return -1;
615 case 255: *val
= R_NegInf
; return 0;
616 case 254: *val
= R_PosInf
; return 0;
617 case 253: *val
= R_Nan
; return 0;
619 if (fread(buf
,len
,1,fp
) == 0) return -1;
621 sscanf(buf
, "%lg", val
);
626 /* Load a Redis object of the specified type from the specified file.
627 * On success a newly allocated object is returned, otherwise NULL. */
628 robj
*rdbLoadObject(int type
, FILE *fp
) {
632 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
633 if (type
== REDIS_STRING
) {
634 /* Read string value */
635 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
636 o
= tryObjectEncoding(o
);
637 } else if (type
== REDIS_LIST
) {
638 /* Read list value */
639 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
641 /* Use a real list when there are too many entries */
642 if (len
> server
.list_max_ziplist_entries
) {
643 o
= createListObject();
645 o
= createZiplistObject();
648 /* Load every single element of the list */
650 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
652 /* If we are using a ziplist and the value is too big, convert
653 * the object to a real list. */
654 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
&&
655 ele
->encoding
== REDIS_ENCODING_RAW
&&
656 sdslen(ele
->ptr
) > server
.list_max_ziplist_value
)
657 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
659 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
660 dec
= getDecodedObject(ele
);
661 o
->ptr
= ziplistPush(o
->ptr
,dec
->ptr
,sdslen(dec
->ptr
),REDIS_TAIL
);
665 ele
= tryObjectEncoding(ele
);
666 listAddNodeTail(o
->ptr
,ele
);
669 } else if (type
== REDIS_SET
) {
670 /* Read list/set value */
671 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
672 o
= createSetObject();
673 /* It's faster to expand the dict to the right size asap in order
674 * to avoid rehashing */
675 if (len
> DICT_HT_INITIAL_SIZE
)
676 dictExpand(o
->ptr
,len
);
677 /* Load every single element of the list/set */
679 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
680 ele
= tryObjectEncoding(ele
);
681 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
683 } else if (type
== REDIS_ZSET
) {
684 /* Read list/set value */
688 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
689 o
= createZsetObject();
691 /* Load every single element of the list/set */
694 double *score
= zmalloc(sizeof(double));
696 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
697 ele
= tryObjectEncoding(ele
);
698 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
699 dictAdd(zs
->dict
,ele
,score
);
700 zslInsert(zs
->zsl
,*score
,ele
);
701 incrRefCount(ele
); /* added to skiplist */
703 } else if (type
== REDIS_HASH
) {
706 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
707 o
= createHashObject();
708 /* Too many entries? Use an hash table. */
709 if (hashlen
> server
.hash_max_zipmap_entries
)
710 convertToRealHash(o
);
711 /* Load every key/value, then set it into the zipmap or hash
712 * table, as needed. */
716 if ((key
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
717 if ((val
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
718 /* If we are using a zipmap and there are too big values
719 * the object is converted to real hash table encoding. */
720 if (o
->encoding
!= REDIS_ENCODING_HT
&&
721 ((key
->encoding
== REDIS_ENCODING_RAW
&&
722 sdslen(key
->ptr
) > server
.hash_max_zipmap_value
) ||
723 (val
->encoding
== REDIS_ENCODING_RAW
&&
724 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)))
726 convertToRealHash(o
);
729 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
730 unsigned char *zm
= o
->ptr
;
731 robj
*deckey
, *decval
;
733 /* We need raw string objects to add them to the zipmap */
734 deckey
= getDecodedObject(key
);
735 decval
= getDecodedObject(val
);
736 zm
= zipmapSet(zm
,deckey
->ptr
,sdslen(deckey
->ptr
),
737 decval
->ptr
,sdslen(decval
->ptr
),NULL
);
739 decrRefCount(deckey
);
740 decrRefCount(decval
);
744 key
= tryObjectEncoding(key
);
745 val
= tryObjectEncoding(val
);
746 dictAdd((dict
*)o
->ptr
,key
,val
);
750 redisPanic("Unknown object type");
755 int rdbLoad(char *filename
) {
758 int type
, retval
, rdbver
;
759 int swap_all_values
= 0;
760 redisDb
*db
= server
.db
+0;
762 time_t expiretime
, now
= time(NULL
);
764 fp
= fopen(filename
,"r");
765 if (!fp
) return REDIS_ERR
;
766 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
768 if (memcmp(buf
,"REDIS",5) != 0) {
770 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
773 rdbver
= atoi(buf
+5);
776 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
785 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
786 if (type
== REDIS_EXPIRETIME
) {
787 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
788 /* We read the time so we need to read the object type again */
789 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
791 if (type
== REDIS_EOF
) break;
792 /* Handle SELECT DB opcode as a special case */
793 if (type
== REDIS_SELECTDB
) {
794 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
796 if (dbid
>= (unsigned)server
.dbnum
) {
797 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
804 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
806 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
807 /* Check if the key already expired */
808 if (expiretime
!= -1 && expiretime
< now
) {
813 /* Add the new object in the hash table */
814 retval
= dbAdd(db
,key
,val
);
815 if (retval
== REDIS_ERR
) {
816 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
819 /* Set the expire time if needed */
820 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
822 /* Handle swapping while loading big datasets when VM is on */
824 /* If we detecter we are hopeless about fitting something in memory
825 * we just swap every new key on disk. Directly...
826 * Note that's important to check for this condition before resorting
827 * to random sampling, otherwise we may try to swap already
829 if (swap_all_values
) {
830 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
832 /* de may be NULL since the key already expired */
835 val
= dictGetEntryVal(de
);
837 if (val
->refcount
== 1 &&
838 (vp
= vmSwapObjectBlocking(val
)) != NULL
)
839 dictGetEntryVal(de
) = vp
;
846 /* Flush data on disk once 32 MB of additional RAM are used... */
848 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
851 /* If we have still some hope of having some value fitting memory
852 * then we try random sampling. */
853 if (!swap_all_values
&& server
.vm_enabled
&& force_swapout
) {
854 while (zmalloc_used_memory() > server
.vm_max_memory
) {
855 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
857 if (zmalloc_used_memory() > server
.vm_max_memory
)
858 swap_all_values
= 1; /* We are already using too much mem */
864 eoferr
: /* unexpected end of file is handled here with a fatal exit */
865 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
867 return REDIS_ERR
; /* Just to avoid warning */
870 /* A background saving child (BGSAVE) terminated its work. Handle this. */
871 void backgroundSaveDoneHandler(int statloc
) {
872 int exitcode
= WEXITSTATUS(statloc
);
873 int bysignal
= WIFSIGNALED(statloc
);
875 if (!bysignal
&& exitcode
== 0) {
876 redisLog(REDIS_NOTICE
,
877 "Background saving terminated with success");
879 server
.lastsave
= time(NULL
);
880 } else if (!bysignal
&& exitcode
!= 0) {
881 redisLog(REDIS_WARNING
, "Background saving error");
883 redisLog(REDIS_WARNING
,
884 "Background saving terminated by signal %d", WTERMSIG(statloc
));
885 rdbRemoveTempFile(server
.bgsavechildpid
);
887 server
.bgsavechildpid
= -1;
888 /* Possibly there are slaves waiting for a BGSAVE in order to be served
889 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
890 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);