2 #include "lzf.h" /* LZF compression library */
7 #include <sys/resource.h>
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;
21 int rdbSaveType(FILE *fp
, unsigned char type
) {
22 return rdbWriteRaw(fp
,&type
,1);
25 int rdbSaveTime(FILE *fp
, time_t t
) {
26 int32_t t32
= (int32_t) t
;
27 return rdbWriteRaw(fp
,&t32
,4);
30 /* check rdbLoadLen() comments for more info */
31 int rdbSaveLen(FILE *fp
, uint32_t len
) {
36 /* Save a 6 bit len */
37 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
38 if (rdbWriteRaw(fp
,buf
,1) == -1) return -1;
40 } else if (len
< (1<<14)) {
41 /* Save a 14 bit len */
42 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
44 if (rdbWriteRaw(fp
,buf
,2) == -1) return -1;
47 /* Save a 32 bit len */
48 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
49 if (rdbWriteRaw(fp
,buf
,1) == -1) return -1;
51 if (rdbWriteRaw(fp
,&len
,4) == -1) return -1;
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
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
;
68 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
69 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
71 enc
[2] = (value
>>8)&0xFF;
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
;
76 enc
[2] = (value
>>8)&0xFF;
77 enc
[3] = (value
>>16)&0xFF;
78 enc
[4] = (value
>>24)&0xFF;
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
) {
90 char *endptr
, buf
[32];
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
);
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;
101 return rdbEncodeInteger(value
,enc
);
104 int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
105 size_t comprlen
, outlen
;
110 /* We require at least four bytes compression for this to be worth it */
111 if (len
<= 4) return 0;
113 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
114 comprlen
= lzf_compress(s
, len
, out
, outlen
);
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
;
124 if ((n
= rdbSaveLen(fp
,comprlen
)) == -1) goto writeerr
;
127 if ((n
= rdbSaveLen(fp
,len
)) == -1) goto writeerr
;
130 if ((n
= rdbWriteRaw(fp
,out
,comprlen
)) == -1) goto writeerr
;
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
) {
147 /* Try integer encoding */
149 unsigned char buf
[5];
150 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
151 if (rdbWriteRaw(fp
,buf
,enclen
) == -1) return -1;
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;
162 /* Return value of 0 means data can't be compressed, save the old way */
166 if ((n
= rdbSaveLen(fp
,len
)) == -1) return -1;
169 if (rdbWriteRaw(fp
,s
,len
) == -1) return -1;
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];
179 int enclen
= rdbEncodeInteger(value
,buf
);
181 return rdbWriteRaw(fp
,buf
,enclen
);
183 /* Encode as string */
184 enclen
= ll2string((char*)buf
,32,value
);
185 redisAssert(enclen
< 32);
186 if ((n
= rdbSaveLen(fp
,enclen
)) == -1) return -1;
188 if ((n
= rdbWriteRaw(fp
,buf
,enclen
)) == -1) return -1;
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
);
201 redisAssert(obj
->encoding
== REDIS_ENCODING_RAW
);
202 return rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
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
214 int rdbSaveDoubleValue(FILE *fp
, double val
) {
215 unsigned char buf
[128];
221 } else if (!isfinite(val
)) {
223 buf
[0] = (val
< 0) ? 255 : 254;
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.
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
);
241 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
242 buf
[0] = strlen((char*)buf
+1);
245 return rdbWriteRaw(fp
,buf
,len
);
248 /* Save a Redis object. */
249 int rdbSaveObject(FILE *fp
, robj
*o
) {
252 if (o
->type
== REDIS_STRING
) {
253 /* Save a string value */
254 if ((n
= rdbSaveStringObject(fp
,o
)) == -1) return -1;
256 } else if (o
->type
== REDIS_LIST
) {
257 /* Save a list value */
258 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
264 if ((n
= rdbSaveLen(fp
,ziplistLen(o
->ptr
))) == -1) return -1;
267 p
= ziplistIndex(o
->ptr
,0);
268 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
270 if ((n
= rdbSaveRawString(fp
,vstr
,vlen
)) == -1)
274 if ((n
= rdbSaveLongLongAsStringObject(fp
,vlong
)) == -1)
278 p
= ziplistNext(o
->ptr
,p
);
280 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
285 if ((n
= rdbSaveLen(fp
,listLength(list
))) == -1) return -1;
288 listRewind(list
,&li
);
289 while((ln
= listNext(&li
))) {
290 robj
*eleobj
= listNodeValue(ln
);
291 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
295 redisPanic("Unknown list encoding");
297 } else if (o
->type
== REDIS_SET
) {
298 /* Save a set value */
299 if (o
->encoding
== REDIS_ENCODING_HT
) {
301 dictIterator
*di
= dictGetIterator(set
);
304 if ((n
= rdbSaveLen(fp
,dictSize(set
))) == -1) return -1;
307 while((de
= dictNext(di
)) != NULL
) {
308 robj
*eleobj
= dictGetEntryKey(de
);
309 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
312 dictReleaseIterator(di
);
313 } else if (o
->encoding
== REDIS_ENCODING_INTSET
) {
318 if ((n
= rdbSaveLen(fp
,intsetLen(is
))) == -1) return -1;
321 while(intsetGet(is
,i
++,&llval
)) {
322 if ((n
= rdbSaveLongLongAsStringObject(fp
,llval
)) == -1) return -1;
326 redisPanic("Unknown set encoding");
328 } else if (o
->type
== REDIS_ZSET
) {
329 /* Save a set value */
331 dictIterator
*di
= dictGetIterator(zs
->dict
);
334 if ((n
= rdbSaveLen(fp
,dictSize(zs
->dict
))) == -1) return -1;
337 while((de
= dictNext(di
)) != NULL
) {
338 robj
*eleobj
= dictGetEntryKey(de
);
339 double *score
= dictGetEntryVal(de
);
341 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
343 if ((n
= rdbSaveDoubleValue(fp
,*score
)) == -1) return -1;
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
;
355 if ((n
= rdbSaveLen(fp
,count
)) == -1) return -1;
358 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
359 if ((n
= rdbSaveRawString(fp
,key
,klen
)) == -1) return -1;
361 if ((n
= rdbSaveRawString(fp
,val
,vlen
)) == -1) return -1;
365 dictIterator
*di
= dictGetIterator(o
->ptr
);
368 if ((n
= rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
))) == -1) return -1;
371 while((de
= dictNext(di
)) != NULL
) {
372 robj
*key
= dictGetEntryKey(de
);
373 robj
*val
= dictGetEntryVal(de
);
375 if ((n
= rdbSaveStringObject(fp
,key
)) == -1) return -1;
377 if ((n
= rdbSaveStringObject(fp
,val
)) == -1) return -1;
380 dictReleaseIterator(di
);
383 redisPanic("Unknown object type");
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);
398 /* Return the number of pages required to save this object in the swap file */
399 off_t
rdbSavedObjectPages(robj
*o
) {
400 off_t bytes
= rdbSavedObjectLen(o
);
401 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
404 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
405 int rdbSave(char *filename
) {
406 dictIterator
*di
= NULL
;
411 time_t now
= time(NULL
);
413 /* Wait for I/O therads to terminate, just in case this is a
414 * foreground-saving, to avoid seeking the swap file descriptor at the
416 if (server
.vm_enabled
)
417 waitEmptyIOJobsQueue();
419 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
420 fp
= fopen(tmpfile
,"w");
422 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
425 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
426 for (j
= 0; j
< server
.dbnum
; j
++) {
427 redisDb
*db
= server
.db
+j
;
429 if (dictSize(d
) == 0) continue;
430 di
= dictGetIterator(d
);
436 /* Write the SELECT DB opcode */
437 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
438 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
440 /* Iterate this DB writing every entry */
441 while((de
= dictNext(di
)) != NULL
) {
442 sds keystr
= dictGetEntryKey(de
);
443 robj key
, *o
= dictGetEntryVal(de
);
446 initStaticStringObject(key
,keystr
);
447 expiretime
= getExpire(db
,&key
);
449 /* Save the expire time */
450 if (expiretime
!= -1) {
451 /* If this key is already expired skip it */
452 if (expiretime
< now
) continue;
453 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
454 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
456 /* Save the key and associated value. This requires special
457 * handling if the value is swapped out. */
458 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
459 o
->storage
== REDIS_VM_SWAPPING
) {
460 /* Save type, key, value */
461 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
462 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
463 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
465 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
467 /* Get a preview of the object in memory */
468 po
= vmPreviewObject(o
);
469 /* Save type, key, value */
470 if (rdbSaveType(fp
,po
->type
) == -1) goto werr
;
471 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
472 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
473 /* Remove the loaded object from memory */
477 dictReleaseIterator(di
);
480 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
482 /* Make sure data will not remain on the OS's output buffers */
487 /* Use RENAME to make sure the DB file is changed atomically only
488 * if the generate DB file is ok. */
489 if (rename(tmpfile
,filename
) == -1) {
490 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
494 redisLog(REDIS_NOTICE
,"DB saved on disk");
496 server
.lastsave
= time(NULL
);
502 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
503 if (di
) dictReleaseIterator(di
);
507 int rdbSaveBackground(char *filename
) {
510 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
511 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
512 server
.dirty_before_bgsave
= server
.dirty
;
513 if ((childpid
= fork()) == 0) {
515 if (server
.vm_enabled
) vmReopenSwapFile();
516 if (server
.ipfd
> 0) close(server
.ipfd
);
517 if (server
.sofd
> 0) close(server
.sofd
);
518 if (rdbSave(filename
) == REDIS_OK
) {
525 if (childpid
== -1) {
526 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
530 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
531 server
.bgsavechildpid
= childpid
;
532 updateDictResizePolicy();
535 return REDIS_OK
; /* unreached */
538 void rdbRemoveTempFile(pid_t childpid
) {
541 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
545 int rdbLoadType(FILE *fp
) {
547 if (fread(&type
,1,1,fp
) == 0) return -1;
551 time_t rdbLoadTime(FILE *fp
) {
553 if (fread(&t32
,4,1,fp
) == 0) return -1;
557 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
558 * of this file for a description of how this are stored on disk.
560 * isencoded is set to 1 if the readed length is not actually a length but
561 * an "encoding type", check the above comments for more info */
562 uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
563 unsigned char buf
[2];
567 if (isencoded
) *isencoded
= 0;
568 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
569 type
= (buf
[0]&0xC0)>>6;
570 if (type
== REDIS_RDB_6BITLEN
) {
571 /* Read a 6 bit len */
573 } else if (type
== REDIS_RDB_ENCVAL
) {
574 /* Read a 6 bit len encoding type */
575 if (isencoded
) *isencoded
= 1;
577 } else if (type
== REDIS_RDB_14BITLEN
) {
578 /* Read a 14 bit len */
579 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
580 return ((buf
[0]&0x3F)<<8)|buf
[1];
582 /* Read a 32 bit len */
583 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
588 /* Load an integer-encoded object from file 'fp', with the specified
589 * encoding type 'enctype'. If encode is true the function may return
590 * an integer-encoded object as reply, otherwise the returned object
591 * will always be encoded as a raw string. */
592 robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
593 unsigned char enc
[4];
596 if (enctype
== REDIS_RDB_ENC_INT8
) {
597 if (fread(enc
,1,1,fp
) == 0) return NULL
;
598 val
= (signed char)enc
[0];
599 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
601 if (fread(enc
,2,1,fp
) == 0) return NULL
;
602 v
= enc
[0]|(enc
[1]<<8);
604 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
606 if (fread(enc
,4,1,fp
) == 0) return NULL
;
607 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
610 val
= 0; /* anti-warning */
611 redisPanic("Unknown RDB integer encoding type");
614 return createStringObjectFromLongLong(val
);
616 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
619 robj
*rdbLoadLzfStringObject(FILE*fp
) {
620 unsigned int len
, clen
;
621 unsigned char *c
= NULL
;
624 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
625 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
626 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
627 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
628 if (fread(c
,clen
,1,fp
) == 0) goto err
;
629 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
631 return createObject(REDIS_STRING
,val
);
638 robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
643 len
= rdbLoadLen(fp
,&isencoded
);
646 case REDIS_RDB_ENC_INT8
:
647 case REDIS_RDB_ENC_INT16
:
648 case REDIS_RDB_ENC_INT32
:
649 return rdbLoadIntegerObject(fp
,len
,encode
);
650 case REDIS_RDB_ENC_LZF
:
651 return rdbLoadLzfStringObject(fp
);
653 redisPanic("Unknown RDB encoding type");
657 if (len
== REDIS_RDB_LENERR
) return NULL
;
658 val
= sdsnewlen(NULL
,len
);
659 if (len
&& fread(val
,len
,1,fp
) == 0) {
663 return createObject(REDIS_STRING
,val
);
666 robj
*rdbLoadStringObject(FILE *fp
) {
667 return rdbGenericLoadStringObject(fp
,0);
670 robj
*rdbLoadEncodedStringObject(FILE *fp
) {
671 return rdbGenericLoadStringObject(fp
,1);
674 /* For information about double serialization check rdbSaveDoubleValue() */
675 int rdbLoadDoubleValue(FILE *fp
, double *val
) {
679 if (fread(&len
,1,1,fp
) == 0) return -1;
681 case 255: *val
= R_NegInf
; return 0;
682 case 254: *val
= R_PosInf
; return 0;
683 case 253: *val
= R_Nan
; return 0;
685 if (fread(buf
,len
,1,fp
) == 0) return -1;
687 sscanf(buf
, "%lg", val
);
692 /* Load a Redis object of the specified type from the specified file.
693 * On success a newly allocated object is returned, otherwise NULL. */
694 robj
*rdbLoadObject(int type
, FILE *fp
) {
699 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
700 if (type
== REDIS_STRING
) {
701 /* Read string value */
702 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
703 o
= tryObjectEncoding(o
);
704 } else if (type
== REDIS_LIST
) {
705 /* Read list value */
706 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
708 /* Use a real list when there are too many entries */
709 if (len
> server
.list_max_ziplist_entries
) {
710 o
= createListObject();
712 o
= createZiplistObject();
715 /* Load every single element of the list */
717 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
719 /* If we are using a ziplist and the value is too big, convert
720 * the object to a real list. */
721 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
&&
722 ele
->encoding
== REDIS_ENCODING_RAW
&&
723 sdslen(ele
->ptr
) > server
.list_max_ziplist_value
)
724 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
726 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
727 dec
= getDecodedObject(ele
);
728 o
->ptr
= ziplistPush(o
->ptr
,dec
->ptr
,sdslen(dec
->ptr
),REDIS_TAIL
);
732 ele
= tryObjectEncoding(ele
);
733 listAddNodeTail(o
->ptr
,ele
);
736 } else if (type
== REDIS_SET
) {
737 /* Read list/set value */
738 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
740 /* Use a regular set when there are too many entries. */
741 if (len
> server
.set_max_intset_entries
) {
742 o
= createSetObject();
743 /* It's faster to expand the dict to the right size asap in order
744 * to avoid rehashing */
745 if (len
> DICT_HT_INITIAL_SIZE
)
746 dictExpand(o
->ptr
,len
);
748 o
= createIntsetObject();
751 /* Load every single element of the list/set */
752 for (i
= 0; i
< len
; i
++) {
754 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
755 ele
= tryObjectEncoding(ele
);
757 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
758 /* Fetch integer value from element */
759 if (isObjectRepresentableAsLongLong(ele
,&llval
) == REDIS_OK
) {
760 o
->ptr
= intsetAdd(o
->ptr
,llval
,NULL
);
762 setTypeConvert(o
,REDIS_ENCODING_HT
);
763 dictExpand(o
->ptr
,len
);
767 /* This will also be called when the set was just converted
768 * to regular hashtable encoded set */
769 if (o
->encoding
== REDIS_ENCODING_HT
) {
770 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
775 } else if (type
== REDIS_ZSET
) {
776 /* Read list/set value */
780 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
781 o
= createZsetObject();
783 /* Load every single element of the list/set */
787 zskiplistNode
*znode
;
789 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
790 ele
= tryObjectEncoding(ele
);
791 if (rdbLoadDoubleValue(fp
,&score
) == -1) return NULL
;
792 znode
= zslInsert(zs
->zsl
,score
,ele
);
793 dictAdd(zs
->dict
,ele
,&znode
->score
);
794 incrRefCount(ele
); /* added to skiplist */
796 } else if (type
== REDIS_HASH
) {
799 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
800 o
= createHashObject();
801 /* Too many entries? Use an hash table. */
802 if (hashlen
> server
.hash_max_zipmap_entries
)
803 convertToRealHash(o
);
804 /* Load every key/value, then set it into the zipmap or hash
805 * table, as needed. */
809 if ((key
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
810 if ((val
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
811 /* If we are using a zipmap and there are too big values
812 * the object is converted to real hash table encoding. */
813 if (o
->encoding
!= REDIS_ENCODING_HT
&&
814 ((key
->encoding
== REDIS_ENCODING_RAW
&&
815 sdslen(key
->ptr
) > server
.hash_max_zipmap_value
) ||
816 (val
->encoding
== REDIS_ENCODING_RAW
&&
817 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)))
819 convertToRealHash(o
);
822 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
823 unsigned char *zm
= o
->ptr
;
824 robj
*deckey
, *decval
;
826 /* We need raw string objects to add them to the zipmap */
827 deckey
= getDecodedObject(key
);
828 decval
= getDecodedObject(val
);
829 zm
= zipmapSet(zm
,deckey
->ptr
,sdslen(deckey
->ptr
),
830 decval
->ptr
,sdslen(decval
->ptr
),NULL
);
832 decrRefCount(deckey
);
833 decrRefCount(decval
);
837 key
= tryObjectEncoding(key
);
838 val
= tryObjectEncoding(val
);
839 dictAdd((dict
*)o
->ptr
,key
,val
);
843 redisPanic("Unknown object type");
848 /* Mark that we are loading in the global state and setup the fields
849 * needed to provide loading stats. */
850 void startLoading(FILE *fp
) {
855 server
.loading_start_time
= time(NULL
);
856 if (fstat(fileno(fp
), &sb
) == -1) {
857 server
.loading_total_bytes
= 1; /* just to avoid division by zero */
859 server
.loading_total_bytes
= sb
.st_size
;
863 /* Refresh the loading progress info */
864 void loadingProgress(off_t pos
) {
865 server
.loading_loaded_bytes
= pos
;
868 /* Loading finished */
869 void stopLoading(void) {
873 int rdbLoad(char *filename
) {
876 int type
, retval
, rdbver
;
877 int swap_all_values
= 0;
878 redisDb
*db
= server
.db
+0;
880 time_t expiretime
, now
= time(NULL
);
883 fp
= fopen(filename
,"r");
884 if (!fp
) return REDIS_ERR
;
885 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
887 if (memcmp(buf
,"REDIS",5) != 0) {
889 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
892 rdbver
= atoi(buf
+5);
895 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
906 /* Serve the clients from time to time */
907 if (!(loops
++ % 1000)) {
908 loadingProgress(ftello(fp
));
909 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
913 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
914 if (type
== REDIS_EXPIRETIME
) {
915 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
916 /* We read the time so we need to read the object type again */
917 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
919 if (type
== REDIS_EOF
) break;
920 /* Handle SELECT DB opcode as a special case */
921 if (type
== REDIS_SELECTDB
) {
922 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
924 if (dbid
>= (unsigned)server
.dbnum
) {
925 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
932 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
934 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
935 /* Check if the key already expired */
936 if (expiretime
!= -1 && expiretime
< now
) {
941 /* Add the new object in the hash table */
942 retval
= dbAdd(db
,key
,val
);
943 if (retval
== REDIS_ERR
) {
944 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
947 /* Set the expire time if needed */
948 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
950 /* Handle swapping while loading big datasets when VM is on */
952 /* If we detecter we are hopeless about fitting something in memory
953 * we just swap every new key on disk. Directly...
954 * Note that's important to check for this condition before resorting
955 * to random sampling, otherwise we may try to swap already
957 if (swap_all_values
) {
958 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
960 /* de may be NULL since the key already expired */
963 val
= dictGetEntryVal(de
);
965 if (val
->refcount
== 1 &&
966 (vp
= vmSwapObjectBlocking(val
)) != NULL
)
967 dictGetEntryVal(de
) = vp
;
974 /* Flush data on disk once 32 MB of additional RAM are used... */
976 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
979 /* If we have still some hope of having some value fitting memory
980 * then we try random sampling. */
981 if (!swap_all_values
&& server
.vm_enabled
&& force_swapout
) {
982 while (zmalloc_used_memory() > server
.vm_max_memory
) {
983 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
985 if (zmalloc_used_memory() > server
.vm_max_memory
)
986 swap_all_values
= 1; /* We are already using too much mem */
993 eoferr
: /* unexpected end of file is handled here with a fatal exit */
994 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
996 return REDIS_ERR
; /* Just to avoid warning */
999 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1000 void backgroundSaveDoneHandler(int statloc
) {
1001 int exitcode
= WEXITSTATUS(statloc
);
1002 int bysignal
= WIFSIGNALED(statloc
);
1004 if (!bysignal
&& exitcode
== 0) {
1005 redisLog(REDIS_NOTICE
,
1006 "Background saving terminated with success");
1007 server
.dirty
= server
.dirty
- server
.dirty_before_bgsave
;
1008 server
.lastsave
= time(NULL
);
1009 } else if (!bysignal
&& exitcode
!= 0) {
1010 redisLog(REDIS_WARNING
, "Background saving error");
1012 redisLog(REDIS_WARNING
,
1013 "Background saving terminated by signal %d", WTERMSIG(statloc
));
1014 rdbRemoveTempFile(server
.bgsavechildpid
);
1016 server
.bgsavechildpid
= -1;
1017 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1018 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1019 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);