2 #include "lzf.h" /* LZF compression library */
7 #include <sys/resource.h>
12 int rdbSaveType(FILE *fp
, unsigned char type
) {
13 if (fwrite(&type
,1,1,fp
) == 0) return -1;
17 int rdbSaveTime(FILE *fp
, time_t t
) {
18 int32_t t32
= (int32_t) t
;
19 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
23 /* check rdbLoadLen() comments for more info */
24 int rdbSaveLen(FILE *fp
, uint32_t len
) {
28 /* Save a 6 bit len */
29 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
30 if (fwrite(buf
,1,1,fp
) == 0) return -1;
31 } else if (len
< (1<<14)) {
32 /* Save a 14 bit len */
33 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
35 if (fwrite(buf
,2,1,fp
) == 0) return -1;
37 /* Save a 32 bit len */
38 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
39 if (fwrite(buf
,1,1,fp
) == 0) return -1;
41 if (fwrite(&len
,4,1,fp
) == 0) return -1;
46 /* Encode 'value' as an integer if possible (if integer will fit the
47 * supported range). If the function sucessful encoded the integer
48 * then the (up to 5 bytes) encoded representation is written in the
49 * string pointed by 'enc' and the length is returned. Otherwise
51 int rdbEncodeInteger(long long value
, unsigned char *enc
) {
52 /* Finally check if it fits in our ranges */
53 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
54 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
57 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
58 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
60 enc
[2] = (value
>>8)&0xFF;
62 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
63 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
65 enc
[2] = (value
>>8)&0xFF;
66 enc
[3] = (value
>>16)&0xFF;
67 enc
[4] = (value
>>24)&0xFF;
74 /* String objects in the form "2391" "-100" without any space and with a
75 * range of values that can fit in an 8, 16 or 32 bit signed value can be
76 * encoded as integers to save space */
77 int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
79 char *endptr
, buf
[32];
81 /* Check if it's possible to encode this value as a number */
82 value
= strtoll(s
, &endptr
, 10);
83 if (endptr
[0] != '\0') return 0;
84 ll2string(buf
,32,value
);
86 /* If the number converted back into a string is not identical
87 * then it's not possible to encode the string as integer */
88 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
90 return rdbEncodeInteger(value
,enc
);
93 int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
94 size_t comprlen
, outlen
;
98 /* We require at least four bytes compression for this to be worth it */
99 if (len
<= 4) return 0;
101 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
102 comprlen
= lzf_compress(s
, len
, out
, outlen
);
107 /* Data compressed! Let's save it on disk */
108 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
109 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
110 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
111 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
112 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
121 /* Save a string objet as [len][data] on disk. If the object is a string
122 * representation of an integer value we try to safe it in a special form */
123 int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
126 /* Try integer encoding */
128 unsigned char buf
[5];
129 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
130 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
135 /* Try LZF compression - under 20 bytes it's unable to compress even
136 * aaaaaaaaaaaaaaaaaa so skip it */
137 if (server
.rdbcompression
&& len
> 20) {
140 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
141 if (retval
== -1) return -1;
142 if (retval
> 0) return 0;
143 /* retval == 0 means data can't be compressed, save the old way */
147 if (rdbSaveLen(fp
,len
) == -1) return -1;
148 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
152 /* Save a long long value as either an encoded string or a string. */
153 int rdbSaveLongLongAsStringObject(FILE *fp
, long long value
) {
154 unsigned char buf
[32];
155 int enclen
= rdbEncodeInteger(value
,buf
);
157 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
159 /* Encode as string */
160 enclen
= ll2string((char*)buf
,32,value
);
161 redisAssert(enclen
< 32);
162 if (rdbSaveLen(fp
,enclen
) == -1) return -1;
163 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
168 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
169 int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
170 /* Avoid to decode the object, then encode it again, if the
171 * object is alrady integer encoded. */
172 if (obj
->encoding
== REDIS_ENCODING_INT
) {
173 return rdbSaveLongLongAsStringObject(fp
,(long)obj
->ptr
);
175 redisAssert(obj
->encoding
== REDIS_ENCODING_RAW
);
176 return rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
180 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
181 * 8 bit integer specifing the length of the representation.
182 * This 8 bit integer has special values in order to specify the following
188 int rdbSaveDoubleValue(FILE *fp
, double val
) {
189 unsigned char buf
[128];
195 } else if (!isfinite(val
)) {
197 buf
[0] = (val
< 0) ? 255 : 254;
199 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
200 /* Check if the float is in a safe range to be casted into a
201 * long long. We are assuming that long long is 64 bit here.
202 * Also we are assuming that there are no implementations around where
203 * double has precision < 52 bit.
205 * Under this assumptions we test if a double is inside an interval
206 * where casting to long long is safe. Then using two castings we
207 * make sure the decimal part is zero. If all this is true we use
208 * integer printing function that is much faster. */
209 double min
= -4503599627370495; /* (2^52)-1 */
210 double max
= 4503599627370496; /* -(2^52) */
211 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
212 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
215 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
216 buf
[0] = strlen((char*)buf
+1);
219 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
223 /* Save a Redis object. */
224 int rdbSaveObject(FILE *fp
, robj
*o
) {
225 if (o
->type
== REDIS_STRING
) {
226 /* Save a string value */
227 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
228 } else if (o
->type
== REDIS_LIST
) {
229 /* Save a list value */
230 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
236 if (rdbSaveLen(fp
,ziplistLen(o
->ptr
)) == -1) return -1;
237 p
= ziplistIndex(o
->ptr
,0);
238 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
240 if (rdbSaveRawString(fp
,vstr
,vlen
) == -1)
243 if (rdbSaveLongLongAsStringObject(fp
,vlong
) == -1)
246 p
= ziplistNext(o
->ptr
,p
);
248 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
253 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
254 listRewind(list
,&li
);
255 while((ln
= listNext(&li
))) {
256 robj
*eleobj
= listNodeValue(ln
);
257 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
260 redisPanic("Unknown list encoding");
262 } else if (o
->type
== REDIS_SET
) {
263 /* Save a set value */
264 if (o
->encoding
== REDIS_ENCODING_HT
) {
266 dictIterator
*di
= dictGetIterator(set
);
269 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
270 while((de
= dictNext(di
)) != NULL
) {
271 robj
*eleobj
= dictGetEntryKey(de
);
272 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
274 dictReleaseIterator(di
);
275 } else if (o
->encoding
== REDIS_ENCODING_INTSET
) {
280 if (rdbSaveLen(fp
,intsetLen(is
)) == -1) return -1;
281 while(intsetGet(is
,i
++,&llval
)) {
282 if (rdbSaveLongLongAsStringObject(fp
,llval
) == -1) return -1;
285 redisPanic("Unknown set encoding");
287 } else if (o
->type
== REDIS_ZSET
) {
288 /* Save a set value */
290 dictIterator
*di
= dictGetIterator(zs
->dict
);
293 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
294 while((de
= dictNext(di
)) != NULL
) {
295 robj
*eleobj
= dictGetEntryKey(de
);
296 double *score
= dictGetEntryVal(de
);
298 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
299 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
301 dictReleaseIterator(di
);
302 } else if (o
->type
== REDIS_HASH
) {
303 /* Save a hash value */
304 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
305 unsigned char *p
= zipmapRewind(o
->ptr
);
306 unsigned int count
= zipmapLen(o
->ptr
);
307 unsigned char *key
, *val
;
308 unsigned int klen
, vlen
;
310 if (rdbSaveLen(fp
,count
) == -1) return -1;
311 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
312 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
313 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
316 dictIterator
*di
= dictGetIterator(o
->ptr
);
319 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
320 while((de
= dictNext(di
)) != NULL
) {
321 robj
*key
= dictGetEntryKey(de
);
322 robj
*val
= dictGetEntryVal(de
);
324 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
325 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
327 dictReleaseIterator(di
);
330 redisPanic("Unknown object type");
335 /* Return the length the object will have on disk if saved with
336 * the rdbSaveObject() function. Currently we use a trick to get
337 * this length with very little changes to the code. In the future
338 * we could switch to a faster solution. */
339 off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
340 if (fp
== NULL
) fp
= server
.devnull
;
342 redisAssert(rdbSaveObject(fp
,o
) != 1);
346 /* Return the number of pages required to save this object in the swap file */
347 off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
348 off_t bytes
= rdbSavedObjectLen(o
,fp
);
350 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
353 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
354 int rdbSave(char *filename
) {
355 dictIterator
*di
= NULL
;
360 time_t now
= time(NULL
);
362 /* Wait for I/O therads to terminate, just in case this is a
363 * foreground-saving, to avoid seeking the swap file descriptor at the
365 if (server
.vm_enabled
)
366 waitEmptyIOJobsQueue();
368 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
369 fp
= fopen(tmpfile
,"w");
371 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
374 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
375 for (j
= 0; j
< server
.dbnum
; j
++) {
376 redisDb
*db
= server
.db
+j
;
378 if (dictSize(d
) == 0) continue;
379 di
= dictGetIterator(d
);
385 /* Write the SELECT DB opcode */
386 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
387 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
389 /* Iterate this DB writing every entry */
390 while((de
= dictNext(di
)) != NULL
) {
391 sds keystr
= dictGetEntryKey(de
);
392 robj key
, *o
= dictGetEntryVal(de
);
395 initStaticStringObject(key
,keystr
);
396 expiretime
= getExpire(db
,&key
);
398 /* Save the expire time */
399 if (expiretime
!= -1) {
400 /* If this key is already expired skip it */
401 if (expiretime
< now
) continue;
402 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
403 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
405 /* Save the key and associated value. This requires special
406 * handling if the value is swapped out. */
407 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
408 o
->storage
== REDIS_VM_SWAPPING
) {
409 /* Save type, key, value */
410 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
411 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
412 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
414 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
416 /* Get a preview of the object in memory */
417 po
= vmPreviewObject(o
);
418 /* Save type, key, value */
419 if (rdbSaveType(fp
,po
->type
) == -1) goto werr
;
420 if (rdbSaveStringObject(fp
,&key
) == -1) goto werr
;
421 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
422 /* Remove the loaded object from memory */
426 dictReleaseIterator(di
);
429 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
431 /* Make sure data will not remain on the OS's output buffers */
436 /* Use RENAME to make sure the DB file is changed atomically only
437 * if the generate DB file is ok. */
438 if (rename(tmpfile
,filename
) == -1) {
439 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
443 redisLog(REDIS_NOTICE
,"DB saved on disk");
445 server
.lastsave
= time(NULL
);
451 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
452 if (di
) dictReleaseIterator(di
);
456 int rdbSaveBackground(char *filename
) {
459 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
460 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
461 server
.dirty_before_bgsave
= server
.dirty
;
462 if ((childpid
= fork()) == 0) {
464 if (server
.vm_enabled
) vmReopenSwapFile();
465 if (server
.ipfd
> 0) close(server
.ipfd
);
466 if (server
.sofd
> 0) close(server
.sofd
);
467 if (rdbSave(filename
) == REDIS_OK
) {
474 if (childpid
== -1) {
475 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
479 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
480 server
.bgsavechildpid
= childpid
;
481 updateDictResizePolicy();
484 return REDIS_OK
; /* unreached */
487 void rdbRemoveTempFile(pid_t childpid
) {
490 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
494 int rdbLoadType(FILE *fp
) {
496 if (fread(&type
,1,1,fp
) == 0) return -1;
500 time_t rdbLoadTime(FILE *fp
) {
502 if (fread(&t32
,4,1,fp
) == 0) return -1;
506 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
507 * of this file for a description of how this are stored on disk.
509 * isencoded is set to 1 if the readed length is not actually a length but
510 * an "encoding type", check the above comments for more info */
511 uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
512 unsigned char buf
[2];
516 if (isencoded
) *isencoded
= 0;
517 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
518 type
= (buf
[0]&0xC0)>>6;
519 if (type
== REDIS_RDB_6BITLEN
) {
520 /* Read a 6 bit len */
522 } else if (type
== REDIS_RDB_ENCVAL
) {
523 /* Read a 6 bit len encoding type */
524 if (isencoded
) *isencoded
= 1;
526 } else if (type
== REDIS_RDB_14BITLEN
) {
527 /* Read a 14 bit len */
528 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
529 return ((buf
[0]&0x3F)<<8)|buf
[1];
531 /* Read a 32 bit len */
532 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
537 /* Load an integer-encoded object from file 'fp', with the specified
538 * encoding type 'enctype'. If encode is true the function may return
539 * an integer-encoded object as reply, otherwise the returned object
540 * will always be encoded as a raw string. */
541 robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
542 unsigned char enc
[4];
545 if (enctype
== REDIS_RDB_ENC_INT8
) {
546 if (fread(enc
,1,1,fp
) == 0) return NULL
;
547 val
= (signed char)enc
[0];
548 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
550 if (fread(enc
,2,1,fp
) == 0) return NULL
;
551 v
= enc
[0]|(enc
[1]<<8);
553 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
555 if (fread(enc
,4,1,fp
) == 0) return NULL
;
556 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
559 val
= 0; /* anti-warning */
560 redisPanic("Unknown RDB integer encoding type");
563 return createStringObjectFromLongLong(val
);
565 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
568 robj
*rdbLoadLzfStringObject(FILE*fp
) {
569 unsigned int len
, clen
;
570 unsigned char *c
= NULL
;
573 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
574 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
575 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
576 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
577 if (fread(c
,clen
,1,fp
) == 0) goto err
;
578 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
580 return createObject(REDIS_STRING
,val
);
587 robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
592 len
= rdbLoadLen(fp
,&isencoded
);
595 case REDIS_RDB_ENC_INT8
:
596 case REDIS_RDB_ENC_INT16
:
597 case REDIS_RDB_ENC_INT32
:
598 return rdbLoadIntegerObject(fp
,len
,encode
);
599 case REDIS_RDB_ENC_LZF
:
600 return rdbLoadLzfStringObject(fp
);
602 redisPanic("Unknown RDB encoding type");
606 if (len
== REDIS_RDB_LENERR
) return NULL
;
607 val
= sdsnewlen(NULL
,len
);
608 if (len
&& fread(val
,len
,1,fp
) == 0) {
612 return createObject(REDIS_STRING
,val
);
615 robj
*rdbLoadStringObject(FILE *fp
) {
616 return rdbGenericLoadStringObject(fp
,0);
619 robj
*rdbLoadEncodedStringObject(FILE *fp
) {
620 return rdbGenericLoadStringObject(fp
,1);
623 /* For information about double serialization check rdbSaveDoubleValue() */
624 int rdbLoadDoubleValue(FILE *fp
, double *val
) {
628 if (fread(&len
,1,1,fp
) == 0) return -1;
630 case 255: *val
= R_NegInf
; return 0;
631 case 254: *val
= R_PosInf
; return 0;
632 case 253: *val
= R_Nan
; return 0;
634 if (fread(buf
,len
,1,fp
) == 0) return -1;
636 sscanf(buf
, "%lg", val
);
641 /* Load a Redis object of the specified type from the specified file.
642 * On success a newly allocated object is returned, otherwise NULL. */
643 robj
*rdbLoadObject(int type
, FILE *fp
) {
648 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
649 if (type
== REDIS_STRING
) {
650 /* Read string value */
651 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
652 o
= tryObjectEncoding(o
);
653 } else if (type
== REDIS_LIST
) {
654 /* Read list value */
655 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
657 /* Use a real list when there are too many entries */
658 if (len
> server
.list_max_ziplist_entries
) {
659 o
= createListObject();
661 o
= createZiplistObject();
664 /* Load every single element of the list */
666 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
668 /* If we are using a ziplist and the value is too big, convert
669 * the object to a real list. */
670 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
&&
671 ele
->encoding
== REDIS_ENCODING_RAW
&&
672 sdslen(ele
->ptr
) > server
.list_max_ziplist_value
)
673 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
675 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
676 dec
= getDecodedObject(ele
);
677 o
->ptr
= ziplistPush(o
->ptr
,dec
->ptr
,sdslen(dec
->ptr
),REDIS_TAIL
);
681 ele
= tryObjectEncoding(ele
);
682 listAddNodeTail(o
->ptr
,ele
);
685 } else if (type
== REDIS_SET
) {
686 /* Read list/set value */
687 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
689 /* Use a regular set when there are too many entries. */
690 if (len
> server
.set_max_intset_entries
) {
691 o
= createSetObject();
692 /* It's faster to expand the dict to the right size asap in order
693 * to avoid rehashing */
694 if (len
> DICT_HT_INITIAL_SIZE
)
695 dictExpand(o
->ptr
,len
);
697 o
= createIntsetObject();
700 /* Load every single element of the list/set */
701 for (i
= 0; i
< len
; i
++) {
703 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
704 ele
= tryObjectEncoding(ele
);
706 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
707 /* Fetch integer value from element */
708 if (isObjectRepresentableAsLongLong(ele
,&llval
) == REDIS_OK
) {
709 o
->ptr
= intsetAdd(o
->ptr
,llval
,NULL
);
711 setTypeConvert(o
,REDIS_ENCODING_HT
);
712 dictExpand(o
->ptr
,len
);
716 /* This will also be called when the set was just converted
717 * to regular hashtable encoded set */
718 if (o
->encoding
== REDIS_ENCODING_HT
) {
719 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
724 } else if (type
== REDIS_ZSET
) {
725 /* Read list/set value */
729 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
730 o
= createZsetObject();
732 /* Load every single element of the list/set */
736 zskiplistNode
*znode
;
738 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
739 ele
= tryObjectEncoding(ele
);
740 if (rdbLoadDoubleValue(fp
,&score
) == -1) return NULL
;
741 znode
= zslInsert(zs
->zsl
,score
,ele
);
742 dictAdd(zs
->dict
,ele
,&znode
->score
);
743 incrRefCount(ele
); /* added to skiplist */
745 } else if (type
== REDIS_HASH
) {
748 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
749 o
= createHashObject();
750 /* Too many entries? Use an hash table. */
751 if (hashlen
> server
.hash_max_zipmap_entries
)
752 convertToRealHash(o
);
753 /* Load every key/value, then set it into the zipmap or hash
754 * table, as needed. */
758 if ((key
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
759 if ((val
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
760 /* If we are using a zipmap and there are too big values
761 * the object is converted to real hash table encoding. */
762 if (o
->encoding
!= REDIS_ENCODING_HT
&&
763 ((key
->encoding
== REDIS_ENCODING_RAW
&&
764 sdslen(key
->ptr
) > server
.hash_max_zipmap_value
) ||
765 (val
->encoding
== REDIS_ENCODING_RAW
&&
766 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)))
768 convertToRealHash(o
);
771 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
772 unsigned char *zm
= o
->ptr
;
773 robj
*deckey
, *decval
;
775 /* We need raw string objects to add them to the zipmap */
776 deckey
= getDecodedObject(key
);
777 decval
= getDecodedObject(val
);
778 zm
= zipmapSet(zm
,deckey
->ptr
,sdslen(deckey
->ptr
),
779 decval
->ptr
,sdslen(decval
->ptr
),NULL
);
781 decrRefCount(deckey
);
782 decrRefCount(decval
);
786 key
= tryObjectEncoding(key
);
787 val
= tryObjectEncoding(val
);
788 dictAdd((dict
*)o
->ptr
,key
,val
);
792 redisPanic("Unknown object type");
797 /* Mark that we are loading in the global state and setup the fields
798 * needed to provide loading stats. */
799 void startLoading(FILE *fp
) {
804 server
.loading_start_time
= time(NULL
);
805 if (fstat(fileno(fp
), &sb
) == -1) {
806 server
.loading_total_bytes
= 1; /* just to avoid division by zero */
808 server
.loading_total_bytes
= sb
.st_size
;
812 /* Refresh the loading progress info */
813 void loadingProgress(off_t pos
) {
814 server
.loading_loaded_bytes
= pos
;
817 /* Loading finished */
818 void stopLoading(void) {
822 int rdbLoad(char *filename
) {
825 int type
, retval
, rdbver
;
826 int swap_all_values
= 0;
827 redisDb
*db
= server
.db
+0;
829 time_t expiretime
, now
= time(NULL
);
832 fp
= fopen(filename
,"r");
833 if (!fp
) return REDIS_ERR
;
834 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
836 if (memcmp(buf
,"REDIS",5) != 0) {
838 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
841 rdbver
= atoi(buf
+5);
844 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
855 /* Serve the clients from time to time */
856 if (!(loops
++ % 1000)) {
857 loadingProgress(ftello(fp
));
858 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
862 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
863 if (type
== REDIS_EXPIRETIME
) {
864 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
865 /* We read the time so we need to read the object type again */
866 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
868 if (type
== REDIS_EOF
) break;
869 /* Handle SELECT DB opcode as a special case */
870 if (type
== REDIS_SELECTDB
) {
871 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
873 if (dbid
>= (unsigned)server
.dbnum
) {
874 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
881 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
883 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
884 /* Check if the key already expired */
885 if (expiretime
!= -1 && expiretime
< now
) {
890 /* Add the new object in the hash table */
891 retval
= dbAdd(db
,key
,val
);
892 if (retval
== REDIS_ERR
) {
893 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
896 /* Set the expire time if needed */
897 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
899 /* Handle swapping while loading big datasets when VM is on */
901 /* If we detecter we are hopeless about fitting something in memory
902 * we just swap every new key on disk. Directly...
903 * Note that's important to check for this condition before resorting
904 * to random sampling, otherwise we may try to swap already
906 if (swap_all_values
) {
907 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
909 /* de may be NULL since the key already expired */
912 val
= dictGetEntryVal(de
);
914 if (val
->refcount
== 1 &&
915 (vp
= vmSwapObjectBlocking(val
)) != NULL
)
916 dictGetEntryVal(de
) = vp
;
923 /* Flush data on disk once 32 MB of additional RAM are used... */
925 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
928 /* If we have still some hope of having some value fitting memory
929 * then we try random sampling. */
930 if (!swap_all_values
&& server
.vm_enabled
&& force_swapout
) {
931 while (zmalloc_used_memory() > server
.vm_max_memory
) {
932 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
934 if (zmalloc_used_memory() > server
.vm_max_memory
)
935 swap_all_values
= 1; /* We are already using too much mem */
942 eoferr
: /* unexpected end of file is handled here with a fatal exit */
943 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
945 return REDIS_ERR
; /* Just to avoid warning */
948 /* A background saving child (BGSAVE) terminated its work. Handle this. */
949 void backgroundSaveDoneHandler(int statloc
) {
950 int exitcode
= WEXITSTATUS(statloc
);
951 int bysignal
= WIFSIGNALED(statloc
);
953 if (!bysignal
&& exitcode
== 0) {
954 redisLog(REDIS_NOTICE
,
955 "Background saving terminated with success");
956 server
.dirty
= server
.dirty
- server
.dirty_before_bgsave
;
957 server
.lastsave
= time(NULL
);
958 } else if (!bysignal
&& exitcode
!= 0) {
959 redisLog(REDIS_WARNING
, "Background saving error");
961 redisLog(REDIS_WARNING
,
962 "Background saving terminated by signal %d", WTERMSIG(statloc
));
963 rdbRemoveTempFile(server
.bgsavechildpid
);
965 server
.bgsavechildpid
= -1;
966 /* Possibly there are slaves waiting for a BGSAVE in order to be served
967 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
968 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);