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 save 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. Returns -1 on error, 0 on success. */
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
) {
259 size_t l
= ziplistBlobLen((unsigned char*)o
->ptr
);
261 if ((n
= rdbSaveRawString(fp
,o
->ptr
,l
)) == -1) return -1;
263 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
268 if ((n
= rdbSaveLen(fp
,listLength(list
))) == -1) return -1;
271 listRewind(list
,&li
);
272 while((ln
= listNext(&li
))) {
273 robj
*eleobj
= listNodeValue(ln
);
274 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
278 redisPanic("Unknown list encoding");
280 } else if (o
->type
== REDIS_SET
) {
281 /* Save a set value */
282 if (o
->encoding
== REDIS_ENCODING_HT
) {
284 dictIterator
*di
= dictGetIterator(set
);
287 if ((n
= rdbSaveLen(fp
,dictSize(set
))) == -1) return -1;
290 while((de
= dictNext(di
)) != NULL
) {
291 robj
*eleobj
= dictGetEntryKey(de
);
292 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
295 dictReleaseIterator(di
);
296 } else if (o
->encoding
== REDIS_ENCODING_INTSET
) {
297 size_t l
= intsetBlobLen((intset
*)o
->ptr
);
299 if ((n
= rdbSaveRawString(fp
,o
->ptr
,l
)) == -1) return -1;
302 redisPanic("Unknown set encoding");
304 } else if (o
->type
== REDIS_ZSET
) {
305 /* Save a sorted set value */
306 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
307 size_t l
= ziplistBlobLen((unsigned char*)o
->ptr
);
309 if ((n
= rdbSaveRawString(fp
,o
->ptr
,l
)) == -1) return -1;
311 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
313 dictIterator
*di
= dictGetIterator(zs
->dict
);
316 if ((n
= rdbSaveLen(fp
,dictSize(zs
->dict
))) == -1) return -1;
319 while((de
= dictNext(di
)) != NULL
) {
320 robj
*eleobj
= dictGetEntryKey(de
);
321 double *score
= dictGetEntryVal(de
);
323 if ((n
= rdbSaveStringObject(fp
,eleobj
)) == -1) return -1;
325 if ((n
= rdbSaveDoubleValue(fp
,*score
)) == -1) return -1;
328 dictReleaseIterator(di
);
330 redisPanic("Unknown sorted set encoding");
332 } else if (o
->type
== REDIS_HASH
) {
333 /* Save a hash value */
334 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
335 size_t l
= zipmapBlobLen((unsigned char*)o
->ptr
);
337 if ((n
= rdbSaveRawString(fp
,o
->ptr
,l
)) == -1) return -1;
340 dictIterator
*di
= dictGetIterator(o
->ptr
);
343 if ((n
= rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
))) == -1) return -1;
346 while((de
= dictNext(di
)) != NULL
) {
347 robj
*key
= dictGetEntryKey(de
);
348 robj
*val
= dictGetEntryVal(de
);
350 if ((n
= rdbSaveStringObject(fp
,key
)) == -1) return -1;
352 if ((n
= rdbSaveStringObject(fp
,val
)) == -1) return -1;
355 dictReleaseIterator(di
);
358 redisPanic("Unknown object type");
363 /* Return the length the object will have on disk if saved with
364 * the rdbSaveObject() function. Currently we use a trick to get
365 * this length with very little changes to the code. In the future
366 * we could switch to a faster solution. */
367 off_t
rdbSavedObjectLen(robj
*o
) {
368 int len
= rdbSaveObject(NULL
,o
);
369 redisAssert(len
!= -1);
373 /* Save a key-value pair, with expire time, type, key, value.
374 * On error -1 is returned.
375 * On success if the key was actaully saved 1 is returned, otherwise 0
376 * is returned (the key was already expired). */
377 int rdbSaveKeyValuePair(FILE *fp
, robj
*key
, robj
*val
,
378 time_t expiretime
, time_t now
)
382 /* Save the expire time */
383 if (expiretime
!= -1) {
384 /* If this key is already expired skip it */
385 if (expiretime
< now
) return 0;
386 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) return -1;
387 if (rdbSaveTime(fp
,expiretime
) == -1) return -1;
389 /* Fix the object type if needed, to support saving zipmaps, ziplists,
390 * and intsets, directly as blobs of bytes: they are already serialized. */
392 if (vtype
== REDIS_HASH
&& val
->encoding
== REDIS_ENCODING_ZIPMAP
)
393 vtype
= REDIS_HASH_ZIPMAP
;
394 else if (vtype
== REDIS_LIST
&& val
->encoding
== REDIS_ENCODING_ZIPLIST
)
395 vtype
= REDIS_LIST_ZIPLIST
;
396 else if (vtype
== REDIS_SET
&& val
->encoding
== REDIS_ENCODING_INTSET
)
397 vtype
= REDIS_SET_INTSET
;
398 else if (vtype
== REDIS_ZSET
&& val
->encoding
== REDIS_ENCODING_ZIPLIST
)
399 vtype
= REDIS_ZSET_ZIPLIST
;
400 /* Save type, key, value */
401 if (rdbSaveType(fp
,vtype
) == -1) return -1;
402 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
403 if (rdbSaveObject(fp
,val
) == -1) return -1;
407 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
408 int rdbSave(char *filename
) {
409 dictIterator
*di
= NULL
;
414 time_t now
= time(NULL
);
416 if (server
.ds_enabled
) {
417 cacheForcePointInTime();
418 return dsRdbSave(filename
);
421 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
422 fp
= fopen(tmpfile
,"w");
424 redisLog(REDIS_WARNING
, "Failed opening .rdb for saving: %s",
428 if (fwrite("REDIS0002",9,1,fp
) == 0) goto werr
;
429 for (j
= 0; j
< server
.dbnum
; j
++) {
430 redisDb
*db
= server
.db
+j
;
432 if (dictSize(d
) == 0) continue;
433 di
= dictGetIterator(d
);
439 /* Write the SELECT DB opcode */
440 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
441 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
443 /* Iterate this DB writing every entry */
444 while((de
= dictNext(di
)) != NULL
) {
445 sds keystr
= dictGetEntryKey(de
);
446 robj key
, *o
= dictGetEntryVal(de
);
449 initStaticStringObject(key
,keystr
);
450 expire
= getExpire(db
,&key
);
451 if (rdbSaveKeyValuePair(fp
,&key
,o
,expire
,now
) == -1) goto werr
;
453 dictReleaseIterator(di
);
456 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
458 /* Make sure data will not remain on the OS's output buffers */
463 /* Use RENAME to make sure the DB file is changed atomically only
464 * if the generate DB file is ok. */
465 if (rename(tmpfile
,filename
) == -1) {
466 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
470 redisLog(REDIS_NOTICE
,"DB saved on disk");
472 server
.lastsave
= time(NULL
);
478 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
479 if (di
) dictReleaseIterator(di
);
483 int rdbSaveBackground(char *filename
) {
487 if (server
.bgsavechildpid
!= -1 ||
488 server
.bgsavethread
!= (pthread_t
) -1) return REDIS_ERR
;
490 server
.dirty_before_bgsave
= server
.dirty
;
492 if (server
.ds_enabled
) {
493 cacheForcePointInTime();
494 return dsRdbSaveBackground(filename
);
498 if ((childpid
= fork()) == 0) {
502 if (server
.ipfd
> 0) close(server
.ipfd
);
503 if (server
.sofd
> 0) close(server
.sofd
);
504 retval
= rdbSave(filename
);
505 _exit((retval
== REDIS_OK
) ? 0 : 1);
508 server
.stat_fork_time
= ustime()-start
;
509 if (childpid
== -1) {
510 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
514 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
515 server
.bgsavechildpid
= childpid
;
516 updateDictResizePolicy();
519 return REDIS_OK
; /* unreached */
522 void rdbRemoveTempFile(pid_t childpid
) {
525 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
529 int rdbLoadType(FILE *fp
) {
531 if (fread(&type
,1,1,fp
) == 0) return -1;
535 time_t rdbLoadTime(FILE *fp
) {
537 if (fread(&t32
,4,1,fp
) == 0) return -1;
541 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
542 * of this file for a description of how this are stored on disk.
544 * isencoded is set to 1 if the readed length is not actually a length but
545 * an "encoding type", check the above comments for more info */
546 uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
547 unsigned char buf
[2];
551 if (isencoded
) *isencoded
= 0;
552 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
553 type
= (buf
[0]&0xC0)>>6;
554 if (type
== REDIS_RDB_6BITLEN
) {
555 /* Read a 6 bit len */
557 } else if (type
== REDIS_RDB_ENCVAL
) {
558 /* Read a 6 bit len encoding type */
559 if (isencoded
) *isencoded
= 1;
561 } else if (type
== REDIS_RDB_14BITLEN
) {
562 /* Read a 14 bit len */
563 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
564 return ((buf
[0]&0x3F)<<8)|buf
[1];
566 /* Read a 32 bit len */
567 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
572 /* Load an integer-encoded object from file 'fp', with the specified
573 * encoding type 'enctype'. If encode is true the function may return
574 * an integer-encoded object as reply, otherwise the returned object
575 * will always be encoded as a raw string. */
576 robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
577 unsigned char enc
[4];
580 if (enctype
== REDIS_RDB_ENC_INT8
) {
581 if (fread(enc
,1,1,fp
) == 0) return NULL
;
582 val
= (signed char)enc
[0];
583 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
585 if (fread(enc
,2,1,fp
) == 0) return NULL
;
586 v
= enc
[0]|(enc
[1]<<8);
588 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
590 if (fread(enc
,4,1,fp
) == 0) return NULL
;
591 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
594 val
= 0; /* anti-warning */
595 redisPanic("Unknown RDB integer encoding type");
598 return createStringObjectFromLongLong(val
);
600 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
603 robj
*rdbLoadLzfStringObject(FILE*fp
) {
604 unsigned int len
, clen
;
605 unsigned char *c
= NULL
;
608 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
609 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
610 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
611 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
612 if (fread(c
,clen
,1,fp
) == 0) goto err
;
613 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
615 return createObject(REDIS_STRING
,val
);
622 robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
627 len
= rdbLoadLen(fp
,&isencoded
);
630 case REDIS_RDB_ENC_INT8
:
631 case REDIS_RDB_ENC_INT16
:
632 case REDIS_RDB_ENC_INT32
:
633 return rdbLoadIntegerObject(fp
,len
,encode
);
634 case REDIS_RDB_ENC_LZF
:
635 return rdbLoadLzfStringObject(fp
);
637 redisPanic("Unknown RDB encoding type");
641 if (len
== REDIS_RDB_LENERR
) return NULL
;
642 val
= sdsnewlen(NULL
,len
);
643 if (len
&& fread(val
,len
,1,fp
) == 0) {
647 return createObject(REDIS_STRING
,val
);
650 robj
*rdbLoadStringObject(FILE *fp
) {
651 return rdbGenericLoadStringObject(fp
,0);
654 robj
*rdbLoadEncodedStringObject(FILE *fp
) {
655 return rdbGenericLoadStringObject(fp
,1);
658 /* For information about double serialization check rdbSaveDoubleValue() */
659 int rdbLoadDoubleValue(FILE *fp
, double *val
) {
663 if (fread(&len
,1,1,fp
) == 0) return -1;
665 case 255: *val
= R_NegInf
; return 0;
666 case 254: *val
= R_PosInf
; return 0;
667 case 253: *val
= R_Nan
; return 0;
669 if (fread(buf
,len
,1,fp
) == 0) return -1;
671 sscanf(buf
, "%lg", val
);
676 /* Load a Redis object of the specified type from the specified file.
677 * On success a newly allocated object is returned, otherwise NULL. */
678 robj
*rdbLoadObject(int type
, FILE *fp
) {
683 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
684 if (type
== REDIS_STRING
) {
685 /* Read string value */
686 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
687 o
= tryObjectEncoding(o
);
688 } else if (type
== REDIS_LIST
) {
689 /* Read list value */
690 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
692 /* Use a real list when there are too many entries */
693 if (len
> server
.list_max_ziplist_entries
) {
694 o
= createListObject();
696 o
= createZiplistObject();
699 /* Load every single element of the list */
701 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
703 /* If we are using a ziplist and the value is too big, convert
704 * the object to a real list. */
705 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
&&
706 ele
->encoding
== REDIS_ENCODING_RAW
&&
707 sdslen(ele
->ptr
) > server
.list_max_ziplist_value
)
708 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
710 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
711 dec
= getDecodedObject(ele
);
712 o
->ptr
= ziplistPush(o
->ptr
,dec
->ptr
,sdslen(dec
->ptr
),REDIS_TAIL
);
716 ele
= tryObjectEncoding(ele
);
717 listAddNodeTail(o
->ptr
,ele
);
720 } else if (type
== REDIS_SET
) {
721 /* Read list/set value */
722 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
724 /* Use a regular set when there are too many entries. */
725 if (len
> server
.set_max_intset_entries
) {
726 o
= createSetObject();
727 /* It's faster to expand the dict to the right size asap in order
728 * to avoid rehashing */
729 if (len
> DICT_HT_INITIAL_SIZE
)
730 dictExpand(o
->ptr
,len
);
732 o
= createIntsetObject();
735 /* Load every single element of the list/set */
736 for (i
= 0; i
< len
; i
++) {
738 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
739 ele
= tryObjectEncoding(ele
);
741 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
742 /* Fetch integer value from element */
743 if (isObjectRepresentableAsLongLong(ele
,&llval
) == REDIS_OK
) {
744 o
->ptr
= intsetAdd(o
->ptr
,llval
,NULL
);
746 setTypeConvert(o
,REDIS_ENCODING_HT
);
747 dictExpand(o
->ptr
,len
);
751 /* This will also be called when the set was just converted
752 * to regular hashtable encoded set */
753 if (o
->encoding
== REDIS_ENCODING_HT
) {
754 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
759 } else if (type
== REDIS_ZSET
) {
760 /* Read list/set value */
762 size_t maxelelen
= 0;
765 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
766 o
= createZsetObject();
769 /* Load every single element of the list/set */
773 zskiplistNode
*znode
;
775 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
776 ele
= tryObjectEncoding(ele
);
777 if (rdbLoadDoubleValue(fp
,&score
) == -1) return NULL
;
779 /* Don't care about integer-encoded strings. */
780 if (ele
->encoding
== REDIS_ENCODING_RAW
&&
781 sdslen(ele
->ptr
) > maxelelen
)
782 maxelelen
= sdslen(ele
->ptr
);
784 znode
= zslInsert(zs
->zsl
,score
,ele
);
785 dictAdd(zs
->dict
,ele
,&znode
->score
);
786 incrRefCount(ele
); /* added to skiplist */
789 /* Convert *after* loading, since sorted sets are not stored ordered. */
790 if (zsetLength(o
) <= server
.zset_max_ziplist_entries
&&
791 maxelelen
<= server
.zset_max_ziplist_value
)
792 zsetConvert(o
,REDIS_ENCODING_ZIPLIST
);
793 } else if (type
== REDIS_HASH
) {
796 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
797 o
= createHashObject();
798 /* Too many entries? Use an hash table. */
799 if (hashlen
> server
.hash_max_zipmap_entries
)
800 convertToRealHash(o
);
801 /* Load every key/value, then set it into the zipmap or hash
802 * table, as needed. */
806 if ((key
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
807 if ((val
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
808 /* If we are using a zipmap and there are too big values
809 * the object is converted to real hash table encoding. */
810 if (o
->encoding
!= REDIS_ENCODING_HT
&&
811 ((key
->encoding
== REDIS_ENCODING_RAW
&&
812 sdslen(key
->ptr
) > server
.hash_max_zipmap_value
) ||
813 (val
->encoding
== REDIS_ENCODING_RAW
&&
814 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
)))
816 convertToRealHash(o
);
819 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
820 unsigned char *zm
= o
->ptr
;
821 robj
*deckey
, *decval
;
823 /* We need raw string objects to add them to the zipmap */
824 deckey
= getDecodedObject(key
);
825 decval
= getDecodedObject(val
);
826 zm
= zipmapSet(zm
,deckey
->ptr
,sdslen(deckey
->ptr
),
827 decval
->ptr
,sdslen(decval
->ptr
),NULL
);
829 decrRefCount(deckey
);
830 decrRefCount(decval
);
834 key
= tryObjectEncoding(key
);
835 val
= tryObjectEncoding(val
);
836 dictAdd((dict
*)o
->ptr
,key
,val
);
839 } else if (type
== REDIS_HASH_ZIPMAP
||
840 type
== REDIS_LIST_ZIPLIST
||
841 type
== REDIS_SET_INTSET
||
842 type
== REDIS_ZSET_ZIPLIST
)
844 robj
*aux
= rdbLoadStringObject(fp
);
846 if (aux
== NULL
) return NULL
;
847 o
= createObject(REDIS_STRING
,NULL
); /* string is just placeholder */
848 o
->ptr
= zmalloc(sdslen(aux
->ptr
));
849 memcpy(o
->ptr
,aux
->ptr
,sdslen(aux
->ptr
));
852 /* Fix the object encoding, and make sure to convert the encoded
853 * data type into the base type if accordingly to the current
854 * configuration there are too many elements in the encoded data
855 * type. Note that we only check the length and not max element
856 * size as this is an O(N) scan. Eventually everything will get
859 case REDIS_HASH_ZIPMAP
:
860 o
->type
= REDIS_HASH
;
861 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
862 if (zipmapLen(o
->ptr
) > server
.hash_max_zipmap_entries
)
863 convertToRealHash(o
);
865 case REDIS_LIST_ZIPLIST
:
866 o
->type
= REDIS_LIST
;
867 o
->encoding
= REDIS_ENCODING_ZIPLIST
;
868 if (ziplistLen(o
->ptr
) > server
.list_max_ziplist_entries
)
869 listTypeConvert(o
,REDIS_ENCODING_LINKEDLIST
);
871 case REDIS_SET_INTSET
:
873 o
->encoding
= REDIS_ENCODING_INTSET
;
874 if (intsetLen(o
->ptr
) > server
.set_max_intset_entries
)
875 setTypeConvert(o
,REDIS_ENCODING_HT
);
877 case REDIS_ZSET_ZIPLIST
:
878 o
->type
= REDIS_ZSET
;
879 o
->encoding
= REDIS_ENCODING_ZIPLIST
;
880 if (zsetLength(o
) > server
.zset_max_ziplist_entries
)
881 zsetConvert(o
,REDIS_ENCODING_SKIPLIST
);
884 redisPanic("Unknown encoding");
888 redisPanic("Unknown object type");
893 /* Mark that we are loading in the global state and setup the fields
894 * needed to provide loading stats. */
895 void startLoading(FILE *fp
) {
900 server
.loading_start_time
= time(NULL
);
901 if (fstat(fileno(fp
), &sb
) == -1) {
902 server
.loading_total_bytes
= 1; /* just to avoid division by zero */
904 server
.loading_total_bytes
= sb
.st_size
;
908 /* Refresh the loading progress info */
909 void loadingProgress(off_t pos
) {
910 server
.loading_loaded_bytes
= pos
;
913 /* Loading finished */
914 void stopLoading(void) {
918 int rdbLoad(char *filename
) {
921 int type
, retval
, rdbver
;
922 redisDb
*db
= server
.db
+0;
924 time_t expiretime
, now
= time(NULL
);
927 fp
= fopen(filename
,"r");
928 if (!fp
) return REDIS_ERR
;
929 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
931 if (memcmp(buf
,"REDIS",5) != 0) {
933 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
936 rdbver
= atoi(buf
+5);
937 if (rdbver
< 1 || rdbver
> 2) {
939 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
948 /* Serve the clients from time to time */
949 if (!(loops
++ % 1000)) {
950 loadingProgress(ftello(fp
));
951 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
955 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
956 if (type
== REDIS_EXPIRETIME
) {
957 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
958 /* We read the time so we need to read the object type again */
959 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
961 if (type
== REDIS_EOF
) break;
962 /* Handle SELECT DB opcode as a special case */
963 if (type
== REDIS_SELECTDB
) {
964 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
966 if (dbid
>= (unsigned)server
.dbnum
) {
967 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
974 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
976 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
977 /* Check if the key already expired */
978 if (expiretime
!= -1 && expiretime
< now
) {
983 /* Add the new object in the hash table */
984 retval
= dbAdd(db
,key
,val
);
985 if (retval
== REDIS_ERR
) {
986 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
989 /* Set the expire time if needed */
990 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
998 eoferr
: /* unexpected end of file is handled here with a fatal exit */
999 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
1001 return REDIS_ERR
; /* Just to avoid warning */
1004 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1005 void backgroundSaveDoneHandler(int exitcode
, int bysignal
) {
1006 if (!bysignal
&& exitcode
== 0) {
1007 redisLog(REDIS_NOTICE
,
1008 "Background saving terminated with success");
1009 server
.dirty
= server
.dirty
- server
.dirty_before_bgsave
;
1010 server
.lastsave
= time(NULL
);
1011 } else if (!bysignal
&& exitcode
!= 0) {
1012 redisLog(REDIS_WARNING
, "Background saving error");
1014 redisLog(REDIS_WARNING
,
1015 "Background saving terminated by signal %d", bysignal
);
1016 rdbRemoveTempFile(server
.bgsavechildpid
);
1018 server
.bgsavechildpid
= -1;
1019 server
.bgsavethread
= (pthread_t
) -1;
1020 server
.bgsavethread_state
= REDIS_BGSAVE_THREAD_UNACTIVE
;
1021 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1022 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1023 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1026 void saveCommand(redisClient
*c
) {
1027 if (server
.bgsavechildpid
!= -1 || server
.bgsavethread
!= (pthread_t
)-1) {
1028 addReplyError(c
,"Background save already in progress");
1031 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
1032 addReply(c
,shared
.ok
);
1034 addReply(c
,shared
.err
);
1038 void bgsaveCommand(redisClient
*c
) {
1039 if (server
.bgsavechildpid
!= -1 || server
.bgsavethread
!= (pthread_t
)-1) {
1040 addReplyError(c
,"Background save already in progress");
1042 } else if (server
.bgrewritechildpid
!= -1) {
1043 addReplyError(c
,"Can't BGSAVE while AOF log rewriting is in progress");
1046 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
1047 addReplyStatus(c
,"Background saving started");
1049 addReply(c
,shared
.err
);