]> git.saurik.com Git - redis.git/blob - src/rdb.c
Fix updating the prevlen field of consecutive entries
[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
11 int rdbSaveType(FILE *fp, unsigned char type) {
12 if (fwrite(&type,1,1,fp) == 0) return -1;
13 return 0;
14 }
15
16 int rdbSaveTime(FILE *fp, time_t t) {
17 int32_t t32 = (int32_t) t;
18 if (fwrite(&t32,4,1,fp) == 0) return -1;
19 return 0;
20 }
21
22 /* check rdbLoadLen() comments for more info */
23 int rdbSaveLen(FILE *fp, uint32_t len) {
24 unsigned char buf[2];
25
26 if (len < (1<<6)) {
27 /* Save a 6 bit len */
28 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
29 if (fwrite(buf,1,1,fp) == 0) return -1;
30 } else if (len < (1<<14)) {
31 /* Save a 14 bit len */
32 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
33 buf[1] = len&0xFF;
34 if (fwrite(buf,2,1,fp) == 0) return -1;
35 } else {
36 /* Save a 32 bit len */
37 buf[0] = (REDIS_RDB_32BITLEN<<6);
38 if (fwrite(buf,1,1,fp) == 0) return -1;
39 len = htonl(len);
40 if (fwrite(&len,4,1,fp) == 0) return -1;
41 }
42 return 0;
43 }
44
45 /* Encode 'value' as an integer if possible (if integer will fit the
46 * supported range). If the function sucessful encoded the integer
47 * then the (up to 5 bytes) encoded representation is written in the
48 * string pointed by 'enc' and the length is returned. Otherwise
49 * 0 is returned. */
50 int rdbEncodeInteger(long long value, unsigned char *enc) {
51 /* Finally check if it fits in our ranges */
52 if (value >= -(1<<7) && value <= (1<<7)-1) {
53 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
54 enc[1] = value&0xFF;
55 return 2;
56 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
57 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
58 enc[1] = value&0xFF;
59 enc[2] = (value>>8)&0xFF;
60 return 3;
61 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
62 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
63 enc[1] = value&0xFF;
64 enc[2] = (value>>8)&0xFF;
65 enc[3] = (value>>16)&0xFF;
66 enc[4] = (value>>24)&0xFF;
67 return 5;
68 } else {
69 return 0;
70 }
71 }
72
73 /* String objects in the form "2391" "-100" without any space and with a
74 * range of values that can fit in an 8, 16 or 32 bit signed value can be
75 * encoded as integers to save space */
76 int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
77 long long value;
78 char *endptr, buf[32];
79
80 /* Check if it's possible to encode this value as a number */
81 value = strtoll(s, &endptr, 10);
82 if (endptr[0] != '\0') return 0;
83 ll2string(buf,32,value);
84
85 /* If the number converted back into a string is not identical
86 * then it's not possible to encode the string as integer */
87 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
88
89 return rdbEncodeInteger(value,enc);
90 }
91
92 int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
93 size_t comprlen, outlen;
94 unsigned char byte;
95 void *out;
96
97 /* We require at least four bytes compression for this to be worth it */
98 if (len <= 4) return 0;
99 outlen = len-4;
100 if ((out = zmalloc(outlen+1)) == NULL) return 0;
101 comprlen = lzf_compress(s, len, out, outlen);
102 if (comprlen == 0) {
103 zfree(out);
104 return 0;
105 }
106 /* Data compressed! Let's save it on disk */
107 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
108 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
109 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
110 if (rdbSaveLen(fp,len) == -1) goto writeerr;
111 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
112 zfree(out);
113 return comprlen;
114
115 writeerr:
116 zfree(out);
117 return -1;
118 }
119
120 /* Save a string objet as [len][data] on disk. If the object is a string
121 * representation of an integer value we try to safe it in a special form */
122 int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
123 int enclen;
124
125 /* Try integer encoding */
126 if (len <= 11) {
127 unsigned char buf[5];
128 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
129 if (fwrite(buf,enclen,1,fp) == 0) return -1;
130 return 0;
131 }
132 }
133
134 /* Try LZF compression - under 20 bytes it's unable to compress even
135 * aaaaaaaaaaaaaaaaaa so skip it */
136 if (server.rdbcompression && len > 20) {
137 int retval;
138
139 retval = rdbSaveLzfStringObject(fp,s,len);
140 if (retval == -1) return -1;
141 if (retval > 0) return 0;
142 /* retval == 0 means data can't be compressed, save the old way */
143 }
144
145 /* Store verbatim */
146 if (rdbSaveLen(fp,len) == -1) return -1;
147 if (len && fwrite(s,len,1,fp) == 0) return -1;
148 return 0;
149 }
150
151 /* Save a long long value as either an encoded string or a string. */
152 int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
153 unsigned char buf[32];
154 int enclen = rdbEncodeInteger(value,buf);
155 if (enclen > 0) {
156 if (fwrite(buf,enclen,1,fp) == 0) return -1;
157 } else {
158 /* Encode as string */
159 enclen = ll2string((char*)buf,32,value);
160 redisAssert(enclen < 32);
161 if (rdbSaveLen(fp,enclen) == -1) return -1;
162 if (fwrite(buf,enclen,1,fp) == 0) return -1;
163 }
164 return 0;
165 }
166
167 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
168 int rdbSaveStringObject(FILE *fp, robj *obj) {
169 /* Avoid to decode the object, then encode it again, if the
170 * object is alrady integer encoded. */
171 if (obj->encoding == REDIS_ENCODING_INT) {
172 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
173 } else {
174 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
175 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
176 }
177 }
178
179 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
180 * 8 bit integer specifing the length of the representation.
181 * This 8 bit integer has special values in order to specify the following
182 * conditions:
183 * 253: not a number
184 * 254: + inf
185 * 255: - inf
186 */
187 int rdbSaveDoubleValue(FILE *fp, double val) {
188 unsigned char buf[128];
189 int len;
190
191 if (isnan(val)) {
192 buf[0] = 253;
193 len = 1;
194 } else if (!isfinite(val)) {
195 len = 1;
196 buf[0] = (val < 0) ? 255 : 254;
197 } else {
198 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
199 /* Check if the float is in a safe range to be casted into a
200 * long long. We are assuming that long long is 64 bit here.
201 * Also we are assuming that there are no implementations around where
202 * double has precision < 52 bit.
203 *
204 * Under this assumptions we test if a double is inside an interval
205 * where casting to long long is safe. Then using two castings we
206 * make sure the decimal part is zero. If all this is true we use
207 * integer printing function that is much faster. */
208 double min = -4503599627370495; /* (2^52)-1 */
209 double max = 4503599627370496; /* -(2^52) */
210 if (val > min && val < max && val == ((double)((long long)val)))
211 ll2string((char*)buf+1,sizeof(buf),(long long)val);
212 else
213 #endif
214 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
215 buf[0] = strlen((char*)buf+1);
216 len = buf[0]+1;
217 }
218 if (fwrite(buf,len,1,fp) == 0) return -1;
219 return 0;
220 }
221
222 /* Save a Redis object. */
223 int rdbSaveObject(FILE *fp, robj *o) {
224 if (o->type == REDIS_STRING) {
225 /* Save a string value */
226 if (rdbSaveStringObject(fp,o) == -1) return -1;
227 } else if (o->type == REDIS_LIST) {
228 /* Save a list value */
229 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
230 unsigned char *p;
231 unsigned char *vstr;
232 unsigned int vlen;
233 long long vlong;
234
235 if (rdbSaveLen(fp,ziplistLen(o->ptr)) == -1) return -1;
236 p = ziplistIndex(o->ptr,0);
237 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
238 if (vstr) {
239 if (rdbSaveRawString(fp,vstr,vlen) == -1)
240 return -1;
241 } else {
242 if (rdbSaveLongLongAsStringObject(fp,vlong) == -1)
243 return -1;
244 }
245 p = ziplistNext(o->ptr,p);
246 }
247 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
248 list *list = o->ptr;
249 listIter li;
250 listNode *ln;
251
252 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
253 listRewind(list,&li);
254 while((ln = listNext(&li))) {
255 robj *eleobj = listNodeValue(ln);
256 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
257 }
258 } else {
259 redisPanic("Unknown list encoding");
260 }
261 } else if (o->type == REDIS_SET) {
262 /* Save a set value */
263 dict *set = o->ptr;
264 dictIterator *di = dictGetIterator(set);
265 dictEntry *de;
266
267 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
268 while((de = dictNext(di)) != NULL) {
269 robj *eleobj = dictGetEntryKey(de);
270
271 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
272 }
273 dictReleaseIterator(di);
274 } else if (o->type == REDIS_ZSET) {
275 /* Save a set value */
276 zset *zs = o->ptr;
277 dictIterator *di = dictGetIterator(zs->dict);
278 dictEntry *de;
279
280 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
281 while((de = dictNext(di)) != NULL) {
282 robj *eleobj = dictGetEntryKey(de);
283 double *score = dictGetEntryVal(de);
284
285 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
286 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
287 }
288 dictReleaseIterator(di);
289 } else if (o->type == REDIS_HASH) {
290 /* Save a hash value */
291 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
292 unsigned char *p = zipmapRewind(o->ptr);
293 unsigned int count = zipmapLen(o->ptr);
294 unsigned char *key, *val;
295 unsigned int klen, vlen;
296
297 if (rdbSaveLen(fp,count) == -1) return -1;
298 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
299 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
300 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
301 }
302 } else {
303 dictIterator *di = dictGetIterator(o->ptr);
304 dictEntry *de;
305
306 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
307 while((de = dictNext(di)) != NULL) {
308 robj *key = dictGetEntryKey(de);
309 robj *val = dictGetEntryVal(de);
310
311 if (rdbSaveStringObject(fp,key) == -1) return -1;
312 if (rdbSaveStringObject(fp,val) == -1) return -1;
313 }
314 dictReleaseIterator(di);
315 }
316 } else {
317 redisPanic("Unknown object type");
318 }
319 return 0;
320 }
321
322 /* Return the length the object will have on disk if saved with
323 * the rdbSaveObject() function. Currently we use a trick to get
324 * this length with very little changes to the code. In the future
325 * we could switch to a faster solution. */
326 off_t rdbSavedObjectLen(robj *o, FILE *fp) {
327 if (fp == NULL) fp = server.devnull;
328 rewind(fp);
329 redisAssert(rdbSaveObject(fp,o) != 1);
330 return ftello(fp);
331 }
332
333 /* Return the number of pages required to save this object in the swap file */
334 off_t rdbSavedObjectPages(robj *o, FILE *fp) {
335 off_t bytes = rdbSavedObjectLen(o,fp);
336
337 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
338 }
339
340 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
341 int rdbSave(char *filename) {
342 dictIterator *di = NULL;
343 dictEntry *de;
344 FILE *fp;
345 char tmpfile[256];
346 int j;
347 time_t now = time(NULL);
348
349 /* Wait for I/O therads to terminate, just in case this is a
350 * foreground-saving, to avoid seeking the swap file descriptor at the
351 * same time. */
352 if (server.vm_enabled)
353 waitEmptyIOJobsQueue();
354
355 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
356 fp = fopen(tmpfile,"w");
357 if (!fp) {
358 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
359 return REDIS_ERR;
360 }
361 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
362 for (j = 0; j < server.dbnum; j++) {
363 redisDb *db = server.db+j;
364 dict *d = db->dict;
365 if (dictSize(d) == 0) continue;
366 di = dictGetIterator(d);
367 if (!di) {
368 fclose(fp);
369 return REDIS_ERR;
370 }
371
372 /* Write the SELECT DB opcode */
373 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
374 if (rdbSaveLen(fp,j) == -1) goto werr;
375
376 /* Iterate this DB writing every entry */
377 while((de = dictNext(di)) != NULL) {
378 sds keystr = dictGetEntryKey(de);
379 robj key, *o = dictGetEntryVal(de);
380 time_t expiretime;
381
382 initStaticStringObject(key,keystr);
383 expiretime = getExpire(db,&key);
384
385 /* Save the expire time */
386 if (expiretime != -1) {
387 /* If this key is already expired skip it */
388 if (expiretime < now) continue;
389 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
390 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
391 }
392 /* Save the key and associated value. This requires special
393 * handling if the value is swapped out. */
394 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
395 o->storage == REDIS_VM_SWAPPING) {
396 /* Save type, key, value */
397 if (rdbSaveType(fp,o->type) == -1) goto werr;
398 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
399 if (rdbSaveObject(fp,o) == -1) goto werr;
400 } else {
401 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
402 robj *po;
403 /* Get a preview of the object in memory */
404 po = vmPreviewObject(o);
405 /* Save type, key, value */
406 if (rdbSaveType(fp,po->type) == -1) goto werr;
407 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
408 if (rdbSaveObject(fp,po) == -1) goto werr;
409 /* Remove the loaded object from memory */
410 decrRefCount(po);
411 }
412 }
413 dictReleaseIterator(di);
414 }
415 /* EOF opcode */
416 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
417
418 /* Make sure data will not remain on the OS's output buffers */
419 fflush(fp);
420 fsync(fileno(fp));
421 fclose(fp);
422
423 /* Use RENAME to make sure the DB file is changed atomically only
424 * if the generate DB file is ok. */
425 if (rename(tmpfile,filename) == -1) {
426 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
427 unlink(tmpfile);
428 return REDIS_ERR;
429 }
430 redisLog(REDIS_NOTICE,"DB saved on disk");
431 server.dirty = 0;
432 server.lastsave = time(NULL);
433 return REDIS_OK;
434
435 werr:
436 fclose(fp);
437 unlink(tmpfile);
438 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
439 if (di) dictReleaseIterator(di);
440 return REDIS_ERR;
441 }
442
443 int rdbSaveBackground(char *filename) {
444 pid_t childpid;
445
446 if (server.bgsavechildpid != -1) return REDIS_ERR;
447 if (server.vm_enabled) waitEmptyIOJobsQueue();
448 if ((childpid = fork()) == 0) {
449 /* Child */
450 if (server.vm_enabled) vmReopenSwapFile();
451 close(server.fd);
452 if (rdbSave(filename) == REDIS_OK) {
453 _exit(0);
454 } else {
455 _exit(1);
456 }
457 } else {
458 /* Parent */
459 if (childpid == -1) {
460 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
461 strerror(errno));
462 return REDIS_ERR;
463 }
464 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
465 server.bgsavechildpid = childpid;
466 updateDictResizePolicy();
467 return REDIS_OK;
468 }
469 return REDIS_OK; /* unreached */
470 }
471
472 void rdbRemoveTempFile(pid_t childpid) {
473 char tmpfile[256];
474
475 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
476 unlink(tmpfile);
477 }
478
479 int rdbLoadType(FILE *fp) {
480 unsigned char type;
481 if (fread(&type,1,1,fp) == 0) return -1;
482 return type;
483 }
484
485 time_t rdbLoadTime(FILE *fp) {
486 int32_t t32;
487 if (fread(&t32,4,1,fp) == 0) return -1;
488 return (time_t) t32;
489 }
490
491 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
492 * of this file for a description of how this are stored on disk.
493 *
494 * isencoded is set to 1 if the readed length is not actually a length but
495 * an "encoding type", check the above comments for more info */
496 uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
497 unsigned char buf[2];
498 uint32_t len;
499 int type;
500
501 if (isencoded) *isencoded = 0;
502 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
503 type = (buf[0]&0xC0)>>6;
504 if (type == REDIS_RDB_6BITLEN) {
505 /* Read a 6 bit len */
506 return buf[0]&0x3F;
507 } else if (type == REDIS_RDB_ENCVAL) {
508 /* Read a 6 bit len encoding type */
509 if (isencoded) *isencoded = 1;
510 return buf[0]&0x3F;
511 } else if (type == REDIS_RDB_14BITLEN) {
512 /* Read a 14 bit len */
513 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
514 return ((buf[0]&0x3F)<<8)|buf[1];
515 } else {
516 /* Read a 32 bit len */
517 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
518 return ntohl(len);
519 }
520 }
521
522 /* Load an integer-encoded object from file 'fp', with the specified
523 * encoding type 'enctype'. If encode is true the function may return
524 * an integer-encoded object as reply, otherwise the returned object
525 * will always be encoded as a raw string. */
526 robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
527 unsigned char enc[4];
528 long long val;
529
530 if (enctype == REDIS_RDB_ENC_INT8) {
531 if (fread(enc,1,1,fp) == 0) return NULL;
532 val = (signed char)enc[0];
533 } else if (enctype == REDIS_RDB_ENC_INT16) {
534 uint16_t v;
535 if (fread(enc,2,1,fp) == 0) return NULL;
536 v = enc[0]|(enc[1]<<8);
537 val = (int16_t)v;
538 } else if (enctype == REDIS_RDB_ENC_INT32) {
539 uint32_t v;
540 if (fread(enc,4,1,fp) == 0) return NULL;
541 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
542 val = (int32_t)v;
543 } else {
544 val = 0; /* anti-warning */
545 redisPanic("Unknown RDB integer encoding type");
546 }
547 if (encode)
548 return createStringObjectFromLongLong(val);
549 else
550 return createObject(REDIS_STRING,sdsfromlonglong(val));
551 }
552
553 robj *rdbLoadLzfStringObject(FILE*fp) {
554 unsigned int len, clen;
555 unsigned char *c = NULL;
556 sds val = NULL;
557
558 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
559 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
560 if ((c = zmalloc(clen)) == NULL) goto err;
561 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
562 if (fread(c,clen,1,fp) == 0) goto err;
563 if (lzf_decompress(c,clen,val,len) == 0) goto err;
564 zfree(c);
565 return createObject(REDIS_STRING,val);
566 err:
567 zfree(c);
568 sdsfree(val);
569 return NULL;
570 }
571
572 robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
573 int isencoded;
574 uint32_t len;
575 sds val;
576
577 len = rdbLoadLen(fp,&isencoded);
578 if (isencoded) {
579 switch(len) {
580 case REDIS_RDB_ENC_INT8:
581 case REDIS_RDB_ENC_INT16:
582 case REDIS_RDB_ENC_INT32:
583 return rdbLoadIntegerObject(fp,len,encode);
584 case REDIS_RDB_ENC_LZF:
585 return rdbLoadLzfStringObject(fp);
586 default:
587 redisPanic("Unknown RDB encoding type");
588 }
589 }
590
591 if (len == REDIS_RDB_LENERR) return NULL;
592 val = sdsnewlen(NULL,len);
593 if (len && fread(val,len,1,fp) == 0) {
594 sdsfree(val);
595 return NULL;
596 }
597 return createObject(REDIS_STRING,val);
598 }
599
600 robj *rdbLoadStringObject(FILE *fp) {
601 return rdbGenericLoadStringObject(fp,0);
602 }
603
604 robj *rdbLoadEncodedStringObject(FILE *fp) {
605 return rdbGenericLoadStringObject(fp,1);
606 }
607
608 /* For information about double serialization check rdbSaveDoubleValue() */
609 int rdbLoadDoubleValue(FILE *fp, double *val) {
610 char buf[128];
611 unsigned char len;
612
613 if (fread(&len,1,1,fp) == 0) return -1;
614 switch(len) {
615 case 255: *val = R_NegInf; return 0;
616 case 254: *val = R_PosInf; return 0;
617 case 253: *val = R_Nan; return 0;
618 default:
619 if (fread(buf,len,1,fp) == 0) return -1;
620 buf[len] = '\0';
621 sscanf(buf, "%lg", val);
622 return 0;
623 }
624 }
625
626 /* Load a Redis object of the specified type from the specified file.
627 * On success a newly allocated object is returned, otherwise NULL. */
628 robj *rdbLoadObject(int type, FILE *fp) {
629 robj *o, *ele, *dec;
630 size_t len;
631
632 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
633 if (type == REDIS_STRING) {
634 /* Read string value */
635 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
636 o = tryObjectEncoding(o);
637 } else if (type == REDIS_LIST) {
638 /* Read list value */
639 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
640
641 /* Use a real list when there are too many entries */
642 if (len > server.list_max_ziplist_entries) {
643 o = createListObject();
644 } else {
645 o = createZiplistObject();
646 }
647
648 /* Load every single element of the list */
649 while(len--) {
650 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
651
652 /* If we are using a ziplist and the value is too big, convert
653 * the object to a real list. */
654 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
655 ele->encoding == REDIS_ENCODING_RAW &&
656 sdslen(ele->ptr) > server.list_max_ziplist_value)
657 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
658
659 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
660 dec = getDecodedObject(ele);
661 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
662 decrRefCount(dec);
663 decrRefCount(ele);
664 } else {
665 ele = tryObjectEncoding(ele);
666 listAddNodeTail(o->ptr,ele);
667 }
668 }
669 } else if (type == REDIS_SET) {
670 /* Read list/set value */
671 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
672 o = createSetObject();
673 /* It's faster to expand the dict to the right size asap in order
674 * to avoid rehashing */
675 if (len > DICT_HT_INITIAL_SIZE)
676 dictExpand(o->ptr,len);
677 /* Load every single element of the list/set */
678 while(len--) {
679 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
680 ele = tryObjectEncoding(ele);
681 dictAdd((dict*)o->ptr,ele,NULL);
682 }
683 } else if (type == REDIS_ZSET) {
684 /* Read list/set value */
685 size_t zsetlen;
686 zset *zs;
687
688 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
689 o = createZsetObject();
690 zs = o->ptr;
691 /* Load every single element of the list/set */
692 while(zsetlen--) {
693 robj *ele;
694 double *score = zmalloc(sizeof(double));
695
696 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
697 ele = tryObjectEncoding(ele);
698 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
699 dictAdd(zs->dict,ele,score);
700 zslInsert(zs->zsl,*score,ele);
701 incrRefCount(ele); /* added to skiplist */
702 }
703 } else if (type == REDIS_HASH) {
704 size_t hashlen;
705
706 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
707 o = createHashObject();
708 /* Too many entries? Use an hash table. */
709 if (hashlen > server.hash_max_zipmap_entries)
710 convertToRealHash(o);
711 /* Load every key/value, then set it into the zipmap or hash
712 * table, as needed. */
713 while(hashlen--) {
714 robj *key, *val;
715
716 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
717 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
718 /* If we are using a zipmap and there are too big values
719 * the object is converted to real hash table encoding. */
720 if (o->encoding != REDIS_ENCODING_HT &&
721 ((key->encoding == REDIS_ENCODING_RAW &&
722 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
723 (val->encoding == REDIS_ENCODING_RAW &&
724 sdslen(val->ptr) > server.hash_max_zipmap_value)))
725 {
726 convertToRealHash(o);
727 }
728
729 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
730 unsigned char *zm = o->ptr;
731 robj *deckey, *decval;
732
733 /* We need raw string objects to add them to the zipmap */
734 deckey = getDecodedObject(key);
735 decval = getDecodedObject(val);
736 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
737 decval->ptr,sdslen(decval->ptr),NULL);
738 o->ptr = zm;
739 decrRefCount(deckey);
740 decrRefCount(decval);
741 decrRefCount(key);
742 decrRefCount(val);
743 } else {
744 key = tryObjectEncoding(key);
745 val = tryObjectEncoding(val);
746 dictAdd((dict*)o->ptr,key,val);
747 }
748 }
749 } else {
750 redisPanic("Unknown object type");
751 }
752 return o;
753 }
754
755 int rdbLoad(char *filename) {
756 FILE *fp;
757 uint32_t dbid;
758 int type, retval, rdbver;
759 int swap_all_values = 0;
760 redisDb *db = server.db+0;
761 char buf[1024];
762 time_t expiretime, now = time(NULL);
763
764 fp = fopen(filename,"r");
765 if (!fp) return REDIS_ERR;
766 if (fread(buf,9,1,fp) == 0) goto eoferr;
767 buf[9] = '\0';
768 if (memcmp(buf,"REDIS",5) != 0) {
769 fclose(fp);
770 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
771 return REDIS_ERR;
772 }
773 rdbver = atoi(buf+5);
774 if (rdbver != 1) {
775 fclose(fp);
776 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
777 return REDIS_ERR;
778 }
779 while(1) {
780 robj *key, *val;
781 int force_swapout;
782
783 expiretime = -1;
784 /* Read type. */
785 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
786 if (type == REDIS_EXPIRETIME) {
787 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
788 /* We read the time so we need to read the object type again */
789 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
790 }
791 if (type == REDIS_EOF) break;
792 /* Handle SELECT DB opcode as a special case */
793 if (type == REDIS_SELECTDB) {
794 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
795 goto eoferr;
796 if (dbid >= (unsigned)server.dbnum) {
797 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
798 exit(1);
799 }
800 db = server.db+dbid;
801 continue;
802 }
803 /* Read key */
804 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
805 /* Read value */
806 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
807 /* Check if the key already expired */
808 if (expiretime != -1 && expiretime < now) {
809 decrRefCount(key);
810 decrRefCount(val);
811 continue;
812 }
813 /* Add the new object in the hash table */
814 retval = dbAdd(db,key,val);
815 if (retval == REDIS_ERR) {
816 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
817 exit(1);
818 }
819 /* Set the expire time if needed */
820 if (expiretime != -1) setExpire(db,key,expiretime);
821
822 /* Handle swapping while loading big datasets when VM is on */
823
824 /* If we detecter we are hopeless about fitting something in memory
825 * we just swap every new key on disk. Directly...
826 * Note that's important to check for this condition before resorting
827 * to random sampling, otherwise we may try to swap already
828 * swapped keys. */
829 if (swap_all_values) {
830 dictEntry *de = dictFind(db->dict,key->ptr);
831
832 /* de may be NULL since the key already expired */
833 if (de) {
834 vmpointer *vp;
835 val = dictGetEntryVal(de);
836
837 if (val->refcount == 1 &&
838 (vp = vmSwapObjectBlocking(val)) != NULL)
839 dictGetEntryVal(de) = vp;
840 }
841 decrRefCount(key);
842 continue;
843 }
844 decrRefCount(key);
845
846 /* Flush data on disk once 32 MB of additional RAM are used... */
847 force_swapout = 0;
848 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
849 force_swapout = 1;
850
851 /* If we have still some hope of having some value fitting memory
852 * then we try random sampling. */
853 if (!swap_all_values && server.vm_enabled && force_swapout) {
854 while (zmalloc_used_memory() > server.vm_max_memory) {
855 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
856 }
857 if (zmalloc_used_memory() > server.vm_max_memory)
858 swap_all_values = 1; /* We are already using too much mem */
859 }
860 }
861 fclose(fp);
862 return REDIS_OK;
863
864 eoferr: /* unexpected end of file is handled here with a fatal exit */
865 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
866 exit(1);
867 return REDIS_ERR; /* Just to avoid warning */
868 }
869
870 /* A background saving child (BGSAVE) terminated its work. Handle this. */
871 void backgroundSaveDoneHandler(int statloc) {
872 int exitcode = WEXITSTATUS(statloc);
873 int bysignal = WIFSIGNALED(statloc);
874
875 if (!bysignal && exitcode == 0) {
876 redisLog(REDIS_NOTICE,
877 "Background saving terminated with success");
878 server.dirty = 0;
879 server.lastsave = time(NULL);
880 } else if (!bysignal && exitcode != 0) {
881 redisLog(REDIS_WARNING, "Background saving error");
882 } else {
883 redisLog(REDIS_WARNING,
884 "Background saving terminated by signal %d", WTERMSIG(statloc));
885 rdbRemoveTempFile(server.bgsavechildpid);
886 }
887 server.bgsavechildpid = -1;
888 /* Possibly there are slaves waiting for a BGSAVE in order to be served
889 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
890 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
891 }