]> git.saurik.com Git - redis.git/blob - src/rdb.c
fcf97d335a580d69e20a8c983e4c516392c6a9d2
[redis.git] / src / rdb.c
1 #include "redis.h"
2 #include "lzf.h" /* LZF compression library */
3
4 #include <math.h>
5 #include <sys/types.h>
6 #include <sys/time.h>
7 #include <sys/resource.h>
8 #include <sys/wait.h>
9 #include <arpa/inet.h>
10 #include <sys/stat.h>
11
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;
18 return len;
19 }
20
21 int rdbSaveType(FILE *fp, unsigned char type) {
22 return rdbWriteRaw(fp,&type,1);
23 }
24
25 int rdbSaveTime(FILE *fp, time_t t) {
26 int32_t t32 = (int32_t) t;
27 return rdbWriteRaw(fp,&t32,4);
28 }
29
30 /* check rdbLoadLen() comments for more info */
31 int rdbSaveLen(FILE *fp, uint32_t len) {
32 unsigned char buf[2];
33 int nwritten;
34
35 if (len < (1<<6)) {
36 /* Save a 6 bit len */
37 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
38 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
39 nwritten = 1;
40 } else if (len < (1<<14)) {
41 /* Save a 14 bit len */
42 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
43 buf[1] = len&0xFF;
44 if (rdbWriteRaw(fp,buf,2) == -1) return -1;
45 nwritten = 2;
46 } else {
47 /* Save a 32 bit len */
48 buf[0] = (REDIS_RDB_32BITLEN<<6);
49 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
50 len = htonl(len);
51 if (rdbWriteRaw(fp,&len,4) == -1) return -1;
52 nwritten = 1+4;
53 }
54 return nwritten;
55 }
56
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
61 * 0 is returned. */
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;
66 enc[1] = value&0xFF;
67 return 2;
68 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
69 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
70 enc[1] = value&0xFF;
71 enc[2] = (value>>8)&0xFF;
72 return 3;
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;
75 enc[1] = value&0xFF;
76 enc[2] = (value>>8)&0xFF;
77 enc[3] = (value>>16)&0xFF;
78 enc[4] = (value>>24)&0xFF;
79 return 5;
80 } else {
81 return 0;
82 }
83 }
84
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) {
89 long long value;
90 char *endptr, buf[32];
91
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);
96
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;
100
101 return rdbEncodeInteger(value,enc);
102 }
103
104 int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
105 size_t comprlen, outlen;
106 unsigned char byte;
107 int n, nwritten = 0;
108 void *out;
109
110 /* We require at least four bytes compression for this to be worth it */
111 if (len <= 4) return 0;
112 outlen = len-4;
113 if ((out = zmalloc(outlen+1)) == NULL) return 0;
114 comprlen = lzf_compress(s, len, out, outlen);
115 if (comprlen == 0) {
116 zfree(out);
117 return 0;
118 }
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;
122 nwritten += n;
123
124 if ((n = rdbSaveLen(fp,comprlen)) == -1) goto writeerr;
125 nwritten += n;
126
127 if ((n = rdbSaveLen(fp,len)) == -1) goto writeerr;
128 nwritten += n;
129
130 if ((n = rdbWriteRaw(fp,out,comprlen)) == -1) goto writeerr;
131 nwritten += n;
132
133 zfree(out);
134 return nwritten;
135
136 writeerr:
137 zfree(out);
138 return -1;
139 }
140
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) {
144 int enclen;
145 int n, nwritten = 0;
146
147 /* Try integer encoding */
148 if (len <= 11) {
149 unsigned char buf[5];
150 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
151 if (rdbWriteRaw(fp,buf,enclen) == -1) return -1;
152 return enclen;
153 }
154 }
155
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;
161 if (n > 0) return n;
162 /* Return value of 0 means data can't be compressed, save the old way */
163 }
164
165 /* Store verbatim */
166 if ((n = rdbSaveLen(fp,len)) == -1) return -1;
167 nwritten += n;
168 if (len > 0) {
169 if (rdbWriteRaw(fp,s,len) == -1) return -1;
170 nwritten += len;
171 }
172 return nwritten;
173 }
174
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];
178 int n, nwritten = 0;
179 int enclen = rdbEncodeInteger(value,buf);
180 if (enclen > 0) {
181 return rdbWriteRaw(fp,buf,enclen);
182 } else {
183 /* Encode as string */
184 enclen = ll2string((char*)buf,32,value);
185 redisAssert(enclen < 32);
186 if ((n = rdbSaveLen(fp,enclen)) == -1) return -1;
187 nwritten += n;
188 if ((n = rdbWriteRaw(fp,buf,enclen)) == -1) return -1;
189 nwritten += n;
190 }
191 return nwritten;
192 }
193
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);
200 } else {
201 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
202 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
203 }
204 }
205
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
209 * conditions:
210 * 253: not a number
211 * 254: + inf
212 * 255: - inf
213 */
214 int rdbSaveDoubleValue(FILE *fp, double val) {
215 unsigned char buf[128];
216 int len;
217
218 if (isnan(val)) {
219 buf[0] = 253;
220 len = 1;
221 } else if (!isfinite(val)) {
222 len = 1;
223 buf[0] = (val < 0) ? 255 : 254;
224 } else {
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.
230 *
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);
239 else
240 #endif
241 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
242 buf[0] = strlen((char*)buf+1);
243 len = buf[0]+1;
244 }
245 return rdbWriteRaw(fp,buf,len);
246 }
247
248 /* Save a Redis object. */
249 int rdbSaveObject(FILE *fp, robj *o) {
250 int n, nwritten = 0;
251
252 if (o->type == REDIS_STRING) {
253 /* Save a string value */
254 if ((n = rdbSaveStringObject(fp,o)) == -1) return -1;
255 nwritten += n;
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);
260
261 if ((n = rdbSaveRawString(fp,o->ptr,l)) == -1) return -1;
262 nwritten += n;
263 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
264 list *list = o->ptr;
265 listIter li;
266 listNode *ln;
267
268 if ((n = rdbSaveLen(fp,listLength(list))) == -1) return -1;
269 nwritten += n;
270
271 listRewind(list,&li);
272 while((ln = listNext(&li))) {
273 robj *eleobj = listNodeValue(ln);
274 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
275 nwritten += n;
276 }
277 } else {
278 redisPanic("Unknown list encoding");
279 }
280 } else if (o->type == REDIS_SET) {
281 /* Save a set value */
282 if (o->encoding == REDIS_ENCODING_HT) {
283 dict *set = o->ptr;
284 dictIterator *di = dictGetIterator(set);
285 dictEntry *de;
286
287 if ((n = rdbSaveLen(fp,dictSize(set))) == -1) return -1;
288 nwritten += n;
289
290 while((de = dictNext(di)) != NULL) {
291 robj *eleobj = dictGetEntryKey(de);
292 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
293 nwritten += n;
294 }
295 dictReleaseIterator(di);
296 } else if (o->encoding == REDIS_ENCODING_INTSET) {
297 size_t l = intsetBlobLen((intset*)o->ptr);
298
299 if ((n = rdbSaveRawString(fp,o->ptr,l)) == -1) return -1;
300 nwritten += n;
301 } else {
302 redisPanic("Unknown set encoding");
303 }
304 } else if (o->type == REDIS_ZSET) {
305 /* Save a set value */
306 zset *zs = o->ptr;
307 dictIterator *di = dictGetIterator(zs->dict);
308 dictEntry *de;
309
310 if ((n = rdbSaveLen(fp,dictSize(zs->dict))) == -1) return -1;
311 nwritten += n;
312
313 while((de = dictNext(di)) != NULL) {
314 robj *eleobj = dictGetEntryKey(de);
315 double *score = dictGetEntryVal(de);
316
317 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
318 nwritten += n;
319 if ((n = rdbSaveDoubleValue(fp,*score)) == -1) return -1;
320 nwritten += n;
321 }
322 dictReleaseIterator(di);
323 } else if (o->type == REDIS_HASH) {
324 /* Save a hash value */
325 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
326 size_t l = zipmapBlobLen((unsigned char*)o->ptr);
327
328 if ((n = rdbSaveRawString(fp,o->ptr,l)) == -1) return -1;
329 nwritten += n;
330 } else {
331 dictIterator *di = dictGetIterator(o->ptr);
332 dictEntry *de;
333
334 if ((n = rdbSaveLen(fp,dictSize((dict*)o->ptr))) == -1) return -1;
335 nwritten += n;
336
337 while((de = dictNext(di)) != NULL) {
338 robj *key = dictGetEntryKey(de);
339 robj *val = dictGetEntryVal(de);
340
341 if ((n = rdbSaveStringObject(fp,key)) == -1) return -1;
342 nwritten += n;
343 if ((n = rdbSaveStringObject(fp,val)) == -1) return -1;
344 nwritten += n;
345 }
346 dictReleaseIterator(di);
347 }
348 } else {
349 redisPanic("Unknown object type");
350 }
351 return nwritten;
352 }
353
354 /* Return the length the object will have on disk if saved with
355 * the rdbSaveObject() function. Currently we use a trick to get
356 * this length with very little changes to the code. In the future
357 * we could switch to a faster solution. */
358 off_t rdbSavedObjectLen(robj *o) {
359 int len = rdbSaveObject(NULL,o);
360 redisAssert(len != -1);
361 return len;
362 }
363
364 /* Save a key-value pair, with expire time, type, key, value.
365 * On error -1 is returned.
366 * On success if the key was actaully saved 1 is returned, otherwise 0
367 * is returned (the key was already expired). */
368 int rdbSaveKeyValuePair(FILE *fp, robj *key, robj *val,
369 time_t expiretime, time_t now)
370 {
371 int vtype;
372
373 /* Save the expire time */
374 if (expiretime != -1) {
375 /* If this key is already expired skip it */
376 if (expiretime < now) return 0;
377 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) return -1;
378 if (rdbSaveTime(fp,expiretime) == -1) return -1;
379 }
380 /* Fix the object type if needed, to support saving zipmaps, ziplists,
381 * and intsets, directly as blobs of bytes: they are already serialized. */
382 vtype = val->type;
383 if (vtype == REDIS_HASH && val->encoding == REDIS_ENCODING_ZIPMAP)
384 vtype = REDIS_HASH_ZIPMAP;
385 else if (vtype == REDIS_LIST && val->encoding == REDIS_ENCODING_ZIPLIST)
386 vtype = REDIS_LIST_ZIPLIST;
387 /* Save type, key, value */
388 if (rdbSaveType(fp,vtype) == -1) return -1;
389 if (rdbSaveStringObject(fp,key) == -1) return -1;
390 if (rdbSaveObject(fp,val) == -1) return -1;
391 return 1;
392 }
393
394 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
395 int rdbSave(char *filename) {
396 dictIterator *di = NULL;
397 dictEntry *de;
398 FILE *fp;
399 char tmpfile[256];
400 int j;
401 time_t now = time(NULL);
402
403 if (server.ds_enabled) {
404 cacheForcePointInTime();
405 return dsRdbSave(filename);
406 }
407
408 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
409 fp = fopen(tmpfile,"w");
410 if (!fp) {
411 redisLog(REDIS_WARNING, "Failed opening .rdb for saving: %s",
412 strerror(errno));
413 return REDIS_ERR;
414 }
415 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
416 for (j = 0; j < server.dbnum; j++) {
417 redisDb *db = server.db+j;
418 dict *d = db->dict;
419 if (dictSize(d) == 0) continue;
420 di = dictGetIterator(d);
421 if (!di) {
422 fclose(fp);
423 return REDIS_ERR;
424 }
425
426 /* Write the SELECT DB opcode */
427 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
428 if (rdbSaveLen(fp,j) == -1) goto werr;
429
430 /* Iterate this DB writing every entry */
431 while((de = dictNext(di)) != NULL) {
432 sds keystr = dictGetEntryKey(de);
433 robj key, *o = dictGetEntryVal(de);
434 time_t expire;
435
436 initStaticStringObject(key,keystr);
437 expire = getExpire(db,&key);
438 if (rdbSaveKeyValuePair(fp,&key,o,expire,now) == -1) goto werr;
439 }
440 dictReleaseIterator(di);
441 }
442 /* EOF opcode */
443 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
444
445 /* Make sure data will not remain on the OS's output buffers */
446 fflush(fp);
447 fsync(fileno(fp));
448 fclose(fp);
449
450 /* Use RENAME to make sure the DB file is changed atomically only
451 * if the generate DB file is ok. */
452 if (rename(tmpfile,filename) == -1) {
453 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
454 unlink(tmpfile);
455 return REDIS_ERR;
456 }
457 redisLog(REDIS_NOTICE,"DB saved on disk");
458 server.dirty = 0;
459 server.lastsave = time(NULL);
460 return REDIS_OK;
461
462 werr:
463 fclose(fp);
464 unlink(tmpfile);
465 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
466 if (di) dictReleaseIterator(di);
467 return REDIS_ERR;
468 }
469
470 int rdbSaveBackground(char *filename) {
471 pid_t childpid;
472
473 if (server.bgsavechildpid != -1 ||
474 server.bgsavethread != (pthread_t) -1) return REDIS_ERR;
475
476 server.dirty_before_bgsave = server.dirty;
477
478 if (server.ds_enabled) {
479 cacheForcePointInTime();
480 return dsRdbSaveBackground(filename);
481 }
482
483 if ((childpid = fork()) == 0) {
484 int retval;
485
486 /* Child */
487 if (server.ipfd > 0) close(server.ipfd);
488 if (server.sofd > 0) close(server.sofd);
489 retval = rdbSave(filename);
490 _exit((retval == REDIS_OK) ? 0 : 1);
491 } else {
492 /* Parent */
493 if (childpid == -1) {
494 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
495 strerror(errno));
496 return REDIS_ERR;
497 }
498 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
499 server.bgsavechildpid = childpid;
500 updateDictResizePolicy();
501 return REDIS_OK;
502 }
503 return REDIS_OK; /* unreached */
504 }
505
506 void rdbRemoveTempFile(pid_t childpid) {
507 char tmpfile[256];
508
509 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
510 unlink(tmpfile);
511 }
512
513 int rdbLoadType(FILE *fp) {
514 unsigned char type;
515 if (fread(&type,1,1,fp) == 0) return -1;
516 return type;
517 }
518
519 time_t rdbLoadTime(FILE *fp) {
520 int32_t t32;
521 if (fread(&t32,4,1,fp) == 0) return -1;
522 return (time_t) t32;
523 }
524
525 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
526 * of this file for a description of how this are stored on disk.
527 *
528 * isencoded is set to 1 if the readed length is not actually a length but
529 * an "encoding type", check the above comments for more info */
530 uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
531 unsigned char buf[2];
532 uint32_t len;
533 int type;
534
535 if (isencoded) *isencoded = 0;
536 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
537 type = (buf[0]&0xC0)>>6;
538 if (type == REDIS_RDB_6BITLEN) {
539 /* Read a 6 bit len */
540 return buf[0]&0x3F;
541 } else if (type == REDIS_RDB_ENCVAL) {
542 /* Read a 6 bit len encoding type */
543 if (isencoded) *isencoded = 1;
544 return buf[0]&0x3F;
545 } else if (type == REDIS_RDB_14BITLEN) {
546 /* Read a 14 bit len */
547 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
548 return ((buf[0]&0x3F)<<8)|buf[1];
549 } else {
550 /* Read a 32 bit len */
551 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
552 return ntohl(len);
553 }
554 }
555
556 /* Load an integer-encoded object from file 'fp', with the specified
557 * encoding type 'enctype'. If encode is true the function may return
558 * an integer-encoded object as reply, otherwise the returned object
559 * will always be encoded as a raw string. */
560 robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
561 unsigned char enc[4];
562 long long val;
563
564 if (enctype == REDIS_RDB_ENC_INT8) {
565 if (fread(enc,1,1,fp) == 0) return NULL;
566 val = (signed char)enc[0];
567 } else if (enctype == REDIS_RDB_ENC_INT16) {
568 uint16_t v;
569 if (fread(enc,2,1,fp) == 0) return NULL;
570 v = enc[0]|(enc[1]<<8);
571 val = (int16_t)v;
572 } else if (enctype == REDIS_RDB_ENC_INT32) {
573 uint32_t v;
574 if (fread(enc,4,1,fp) == 0) return NULL;
575 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
576 val = (int32_t)v;
577 } else {
578 val = 0; /* anti-warning */
579 redisPanic("Unknown RDB integer encoding type");
580 }
581 if (encode)
582 return createStringObjectFromLongLong(val);
583 else
584 return createObject(REDIS_STRING,sdsfromlonglong(val));
585 }
586
587 robj *rdbLoadLzfStringObject(FILE*fp) {
588 unsigned int len, clen;
589 unsigned char *c = NULL;
590 sds val = NULL;
591
592 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
593 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
594 if ((c = zmalloc(clen)) == NULL) goto err;
595 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
596 if (fread(c,clen,1,fp) == 0) goto err;
597 if (lzf_decompress(c,clen,val,len) == 0) goto err;
598 zfree(c);
599 return createObject(REDIS_STRING,val);
600 err:
601 zfree(c);
602 sdsfree(val);
603 return NULL;
604 }
605
606 robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
607 int isencoded;
608 uint32_t len;
609 sds val;
610
611 len = rdbLoadLen(fp,&isencoded);
612 if (isencoded) {
613 switch(len) {
614 case REDIS_RDB_ENC_INT8:
615 case REDIS_RDB_ENC_INT16:
616 case REDIS_RDB_ENC_INT32:
617 return rdbLoadIntegerObject(fp,len,encode);
618 case REDIS_RDB_ENC_LZF:
619 return rdbLoadLzfStringObject(fp);
620 default:
621 redisPanic("Unknown RDB encoding type");
622 }
623 }
624
625 if (len == REDIS_RDB_LENERR) return NULL;
626 val = sdsnewlen(NULL,len);
627 if (len && fread(val,len,1,fp) == 0) {
628 sdsfree(val);
629 return NULL;
630 }
631 return createObject(REDIS_STRING,val);
632 }
633
634 robj *rdbLoadStringObject(FILE *fp) {
635 return rdbGenericLoadStringObject(fp,0);
636 }
637
638 robj *rdbLoadEncodedStringObject(FILE *fp) {
639 return rdbGenericLoadStringObject(fp,1);
640 }
641
642 /* For information about double serialization check rdbSaveDoubleValue() */
643 int rdbLoadDoubleValue(FILE *fp, double *val) {
644 char buf[128];
645 unsigned char len;
646
647 if (fread(&len,1,1,fp) == 0) return -1;
648 switch(len) {
649 case 255: *val = R_NegInf; return 0;
650 case 254: *val = R_PosInf; return 0;
651 case 253: *val = R_Nan; return 0;
652 default:
653 if (fread(buf,len,1,fp) == 0) return -1;
654 buf[len] = '\0';
655 sscanf(buf, "%lg", val);
656 return 0;
657 }
658 }
659
660 /* Load a Redis object of the specified type from the specified file.
661 * On success a newly allocated object is returned, otherwise NULL. */
662 robj *rdbLoadObject(int type, FILE *fp) {
663 robj *o, *ele, *dec;
664 size_t len;
665 unsigned int i;
666
667 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
668 if (type == REDIS_STRING) {
669 /* Read string value */
670 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
671 o = tryObjectEncoding(o);
672 } else if (type == REDIS_LIST) {
673 /* Read list value */
674 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
675
676 /* Use a real list when there are too many entries */
677 if (len > server.list_max_ziplist_entries) {
678 o = createListObject();
679 } else {
680 o = createZiplistObject();
681 }
682
683 /* Load every single element of the list */
684 while(len--) {
685 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
686
687 /* If we are using a ziplist and the value is too big, convert
688 * the object to a real list. */
689 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
690 ele->encoding == REDIS_ENCODING_RAW &&
691 sdslen(ele->ptr) > server.list_max_ziplist_value)
692 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
693
694 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
695 dec = getDecodedObject(ele);
696 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
697 decrRefCount(dec);
698 decrRefCount(ele);
699 } else {
700 ele = tryObjectEncoding(ele);
701 listAddNodeTail(o->ptr,ele);
702 }
703 }
704 } else if (type == REDIS_SET) {
705 /* Read list/set value */
706 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
707
708 /* Use a regular set when there are too many entries. */
709 if (len > server.set_max_intset_entries) {
710 o = createSetObject();
711 /* It's faster to expand the dict to the right size asap in order
712 * to avoid rehashing */
713 if (len > DICT_HT_INITIAL_SIZE)
714 dictExpand(o->ptr,len);
715 } else {
716 o = createIntsetObject();
717 }
718
719 /* Load every single element of the list/set */
720 for (i = 0; i < len; i++) {
721 long long llval;
722 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
723 ele = tryObjectEncoding(ele);
724
725 if (o->encoding == REDIS_ENCODING_INTSET) {
726 /* Fetch integer value from element */
727 if (isObjectRepresentableAsLongLong(ele,&llval) == REDIS_OK) {
728 o->ptr = intsetAdd(o->ptr,llval,NULL);
729 } else {
730 setTypeConvert(o,REDIS_ENCODING_HT);
731 dictExpand(o->ptr,len);
732 }
733 }
734
735 /* This will also be called when the set was just converted
736 * to regular hashtable encoded set */
737 if (o->encoding == REDIS_ENCODING_HT) {
738 dictAdd((dict*)o->ptr,ele,NULL);
739 } else {
740 decrRefCount(ele);
741 }
742 }
743 } else if (type == REDIS_ZSET) {
744 /* Read list/set value */
745 size_t zsetlen;
746 zset *zs;
747
748 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
749 o = createZsetObject();
750 zs = o->ptr;
751 /* Load every single element of the list/set */
752 while(zsetlen--) {
753 robj *ele;
754 double score;
755 zskiplistNode *znode;
756
757 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
758 ele = tryObjectEncoding(ele);
759 if (rdbLoadDoubleValue(fp,&score) == -1) return NULL;
760 znode = zslInsert(zs->zsl,score,ele);
761 dictAdd(zs->dict,ele,&znode->score);
762 incrRefCount(ele); /* added to skiplist */
763 }
764 } else if (type == REDIS_HASH) {
765 size_t hashlen;
766
767 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
768 o = createHashObject();
769 /* Too many entries? Use an hash table. */
770 if (hashlen > server.hash_max_zipmap_entries)
771 convertToRealHash(o);
772 /* Load every key/value, then set it into the zipmap or hash
773 * table, as needed. */
774 while(hashlen--) {
775 robj *key, *val;
776
777 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
778 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
779 /* If we are using a zipmap and there are too big values
780 * the object is converted to real hash table encoding. */
781 if (o->encoding != REDIS_ENCODING_HT &&
782 ((key->encoding == REDIS_ENCODING_RAW &&
783 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
784 (val->encoding == REDIS_ENCODING_RAW &&
785 sdslen(val->ptr) > server.hash_max_zipmap_value)))
786 {
787 convertToRealHash(o);
788 }
789
790 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
791 unsigned char *zm = o->ptr;
792 robj *deckey, *decval;
793
794 /* We need raw string objects to add them to the zipmap */
795 deckey = getDecodedObject(key);
796 decval = getDecodedObject(val);
797 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
798 decval->ptr,sdslen(decval->ptr),NULL);
799 o->ptr = zm;
800 decrRefCount(deckey);
801 decrRefCount(decval);
802 decrRefCount(key);
803 decrRefCount(val);
804 } else {
805 key = tryObjectEncoding(key);
806 val = tryObjectEncoding(val);
807 dictAdd((dict*)o->ptr,key,val);
808 }
809 }
810 } else if (type == REDIS_HASH_ZIPMAP ||
811 type == REDIS_LIST_ZIPLIST ||
812 type == REDIS_SET_INTSET)
813 {
814 robj *aux = rdbLoadStringObject(fp);
815
816 if (aux == NULL) return NULL;
817 o = createObject(REDIS_STRING,NULL); /* string is just placeholder */
818 o->ptr = zmalloc(sdslen(aux->ptr));
819 memcpy(o->ptr,aux->ptr,sdslen(aux->ptr));
820 decrRefCount(aux);
821
822 /* Fix the object encoding, and make sure to convert the encoded
823 * data type into the base type if accordingly to the current
824 * configuration there are too many elements in the encoded data
825 * type. Note that we only check the length and not max element
826 * size as this is an O(N) scan. Eventually everything will get
827 * converted. */
828 switch(type) {
829 case REDIS_HASH_ZIPMAP:
830 o->type = REDIS_HASH;
831 o->encoding = REDIS_ENCODING_ZIPMAP;
832 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
833 convertToRealHash(o);
834 break;
835 case REDIS_LIST_ZIPLIST:
836 o->type = REDIS_LIST;
837 o->encoding = REDIS_ENCODING_ZIPLIST;
838 if (ziplistLen(o->ptr) > server.list_max_ziplist_entries)
839 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
840 break;
841 case REDIS_SET_INTSET:
842 o->type = REDIS_SET;
843 o->encoding = REDIS_ENCODING_INTSET;
844 if (intsetLen(o->ptr) > server.set_max_intset_entries)
845 setTypeConvert(o,REDIS_ENCODING_HT);
846 break;
847 default:
848 redisPanic("Unknown enoding");
849 break;
850 }
851 } else {
852 redisPanic("Unknown object type");
853 }
854 return o;
855 }
856
857 /* Mark that we are loading in the global state and setup the fields
858 * needed to provide loading stats. */
859 void startLoading(FILE *fp) {
860 struct stat sb;
861
862 /* Load the DB */
863 server.loading = 1;
864 server.loading_start_time = time(NULL);
865 if (fstat(fileno(fp), &sb) == -1) {
866 server.loading_total_bytes = 1; /* just to avoid division by zero */
867 } else {
868 server.loading_total_bytes = sb.st_size;
869 }
870 }
871
872 /* Refresh the loading progress info */
873 void loadingProgress(off_t pos) {
874 server.loading_loaded_bytes = pos;
875 }
876
877 /* Loading finished */
878 void stopLoading(void) {
879 server.loading = 0;
880 }
881
882 int rdbLoad(char *filename) {
883 FILE *fp;
884 uint32_t dbid;
885 int type, retval, rdbver;
886 redisDb *db = server.db+0;
887 char buf[1024];
888 time_t expiretime, now = time(NULL);
889 long loops = 0;
890
891 fp = fopen(filename,"r");
892 if (!fp) return REDIS_ERR;
893 if (fread(buf,9,1,fp) == 0) goto eoferr;
894 buf[9] = '\0';
895 if (memcmp(buf,"REDIS",5) != 0) {
896 fclose(fp);
897 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
898 return REDIS_ERR;
899 }
900 rdbver = atoi(buf+5);
901 if (rdbver != 1) {
902 fclose(fp);
903 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
904 return REDIS_ERR;
905 }
906
907 startLoading(fp);
908 while(1) {
909 robj *key, *val;
910 expiretime = -1;
911
912 /* Serve the clients from time to time */
913 if (!(loops++ % 1000)) {
914 loadingProgress(ftello(fp));
915 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
916 }
917
918 /* Read type. */
919 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
920 if (type == REDIS_EXPIRETIME) {
921 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
922 /* We read the time so we need to read the object type again */
923 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
924 }
925 if (type == REDIS_EOF) break;
926 /* Handle SELECT DB opcode as a special case */
927 if (type == REDIS_SELECTDB) {
928 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
929 goto eoferr;
930 if (dbid >= (unsigned)server.dbnum) {
931 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
932 exit(1);
933 }
934 db = server.db+dbid;
935 continue;
936 }
937 /* Read key */
938 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
939 /* Read value */
940 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
941 /* Check if the key already expired */
942 if (expiretime != -1 && expiretime < now) {
943 decrRefCount(key);
944 decrRefCount(val);
945 continue;
946 }
947 /* Add the new object in the hash table */
948 retval = dbAdd(db,key,val);
949 if (retval == REDIS_ERR) {
950 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
951 exit(1);
952 }
953 /* Set the expire time if needed */
954 if (expiretime != -1) setExpire(db,key,expiretime);
955
956 decrRefCount(key);
957 }
958 fclose(fp);
959 stopLoading();
960 return REDIS_OK;
961
962 eoferr: /* unexpected end of file is handled here with a fatal exit */
963 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
964 exit(1);
965 return REDIS_ERR; /* Just to avoid warning */
966 }
967
968 /* A background saving child (BGSAVE) terminated its work. Handle this. */
969 void backgroundSaveDoneHandler(int exitcode, int bysignal) {
970 if (!bysignal && exitcode == 0) {
971 redisLog(REDIS_NOTICE,
972 "Background saving terminated with success");
973 server.dirty = server.dirty - server.dirty_before_bgsave;
974 server.lastsave = time(NULL);
975 } else if (!bysignal && exitcode != 0) {
976 redisLog(REDIS_WARNING, "Background saving error");
977 } else {
978 redisLog(REDIS_WARNING,
979 "Background saving terminated by signal %d", bysignal);
980 rdbRemoveTempFile(server.bgsavechildpid);
981 }
982 server.bgsavechildpid = -1;
983 server.bgsavethread = (pthread_t) -1;
984 server.bgsavethread_state = REDIS_BGSAVE_THREAD_UNACTIVE;
985 /* Possibly there are slaves waiting for a BGSAVE in order to be served
986 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
987 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
988 }
989
990 void saveCommand(redisClient *c) {
991 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread_t)-1) {
992 addReplyError(c,"Background save already in progress");
993 return;
994 }
995 if (rdbSave(server.dbfilename) == REDIS_OK) {
996 addReply(c,shared.ok);
997 } else {
998 addReply(c,shared.err);
999 }
1000 }
1001
1002 void bgsaveCommand(redisClient *c) {
1003 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread_t)-1) {
1004 addReplyError(c,"Background save already in progress");
1005 return;
1006 }
1007 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
1008 addReplyStatus(c,"Background saving started");
1009 } else {
1010 addReply(c,shared.err);
1011 }
1012 }