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