]> git.saurik.com Git - redis.git/blob - src/rdb.c
Wrapper around fwrite to make API consistent
[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 safe 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 unsigned char *p;
260 unsigned char *vstr;
261 unsigned int vlen;
262 long long vlong;
263
264 if ((n = rdbSaveLen(fp,ziplistLen(o->ptr))) == -1) return -1;
265 nwritten += n;
266
267 p = ziplistIndex(o->ptr,0);
268 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
269 if (vstr) {
270 if ((n = rdbSaveRawString(fp,vstr,vlen)) == -1)
271 return -1;
272 nwritten += n;
273 } else {
274 if ((n = rdbSaveLongLongAsStringObject(fp,vlong)) == -1)
275 return -1;
276 nwritten += n;
277 }
278 p = ziplistNext(o->ptr,p);
279 }
280 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
281 list *list = o->ptr;
282 listIter li;
283 listNode *ln;
284
285 if ((n = rdbSaveLen(fp,listLength(list))) == -1) return -1;
286 nwritten += n;
287
288 listRewind(list,&li);
289 while((ln = listNext(&li))) {
290 robj *eleobj = listNodeValue(ln);
291 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
292 nwritten += n;
293 }
294 } else {
295 redisPanic("Unknown list encoding");
296 }
297 } else if (o->type == REDIS_SET) {
298 /* Save a set value */
299 if (o->encoding == REDIS_ENCODING_HT) {
300 dict *set = o->ptr;
301 dictIterator *di = dictGetIterator(set);
302 dictEntry *de;
303
304 if ((n = rdbSaveLen(fp,dictSize(set))) == -1) return -1;
305 nwritten += n;
306
307 while((de = dictNext(di)) != NULL) {
308 robj *eleobj = dictGetEntryKey(de);
309 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
310 nwritten += n;
311 }
312 dictReleaseIterator(di);
313 } else if (o->encoding == REDIS_ENCODING_INTSET) {
314 intset *is = o->ptr;
315 int64_t llval;
316 int i = 0;
317
318 if ((n = rdbSaveLen(fp,intsetLen(is))) == -1) return -1;
319 nwritten += n;
320
321 while(intsetGet(is,i++,&llval)) {
322 if ((n = rdbSaveLongLongAsStringObject(fp,llval)) == -1) return -1;
323 nwritten += n;
324 }
325 } else {
326 redisPanic("Unknown set encoding");
327 }
328 } else if (o->type == REDIS_ZSET) {
329 /* Save a set value */
330 zset *zs = o->ptr;
331 dictIterator *di = dictGetIterator(zs->dict);
332 dictEntry *de;
333
334 if ((n = rdbSaveLen(fp,dictSize(zs->dict))) == -1) return -1;
335 nwritten += n;
336
337 while((de = dictNext(di)) != NULL) {
338 robj *eleobj = dictGetEntryKey(de);
339 double *score = dictGetEntryVal(de);
340
341 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
342 nwritten += n;
343 if ((n = rdbSaveDoubleValue(fp,*score)) == -1) return -1;
344 nwritten += n;
345 }
346 dictReleaseIterator(di);
347 } else if (o->type == REDIS_HASH) {
348 /* Save a hash value */
349 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
350 unsigned char *p = zipmapRewind(o->ptr);
351 unsigned int count = zipmapLen(o->ptr);
352 unsigned char *key, *val;
353 unsigned int klen, vlen;
354
355 if ((n = rdbSaveLen(fp,count)) == -1) return -1;
356 nwritten += n;
357
358 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
359 if ((n = rdbSaveRawString(fp,key,klen)) == -1) return -1;
360 nwritten += n;
361 if ((n = rdbSaveRawString(fp,val,vlen)) == -1) return -1;
362 nwritten += n;
363 }
364 } else {
365 dictIterator *di = dictGetIterator(o->ptr);
366 dictEntry *de;
367
368 if ((n = rdbSaveLen(fp,dictSize((dict*)o->ptr))) == -1) return -1;
369 nwritten += n;
370
371 while((de = dictNext(di)) != NULL) {
372 robj *key = dictGetEntryKey(de);
373 robj *val = dictGetEntryVal(de);
374
375 if ((n = rdbSaveStringObject(fp,key)) == -1) return -1;
376 nwritten += n;
377 if ((n = rdbSaveStringObject(fp,val)) == -1) return -1;
378 nwritten += n;
379 }
380 dictReleaseIterator(di);
381 }
382 } else {
383 redisPanic("Unknown object type");
384 }
385 return nwritten;
386 }
387
388 /* Return the length the object will have on disk if saved with
389 * the rdbSaveObject() function. Currently we use a trick to get
390 * this length with very little changes to the code. In the future
391 * we could switch to a faster solution. */
392 off_t rdbSavedObjectLen(robj *o, FILE *fp) {
393 int nwritten;
394 if (fp == NULL) fp = server.devnull;
395 rewind(fp);
396
397 /* Determining the saved length of an object should never return -1 */
398 redisAssert((nwritten = rdbSaveObject(fp,o)) != -1);
399 return nwritten;
400 }
401
402 /* Return the number of pages required to save this object in the swap file */
403 off_t rdbSavedObjectPages(robj *o, FILE *fp) {
404 off_t bytes = rdbSavedObjectLen(o,fp);
405
406 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
407 }
408
409 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
410 int rdbSave(char *filename) {
411 dictIterator *di = NULL;
412 dictEntry *de;
413 FILE *fp;
414 char tmpfile[256];
415 int j;
416 time_t now = time(NULL);
417
418 /* Wait for I/O therads to terminate, just in case this is a
419 * foreground-saving, to avoid seeking the swap file descriptor at the
420 * same time. */
421 if (server.vm_enabled)
422 waitEmptyIOJobsQueue();
423
424 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
425 fp = fopen(tmpfile,"w");
426 if (!fp) {
427 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
428 return REDIS_ERR;
429 }
430 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
431 for (j = 0; j < server.dbnum; j++) {
432 redisDb *db = server.db+j;
433 dict *d = db->dict;
434 if (dictSize(d) == 0) continue;
435 di = dictGetIterator(d);
436 if (!di) {
437 fclose(fp);
438 return REDIS_ERR;
439 }
440
441 /* Write the SELECT DB opcode */
442 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
443 if (rdbSaveLen(fp,j) == -1) goto werr;
444
445 /* Iterate this DB writing every entry */
446 while((de = dictNext(di)) != NULL) {
447 sds keystr = dictGetEntryKey(de);
448 robj key, *o = dictGetEntryVal(de);
449 time_t expiretime;
450
451 initStaticStringObject(key,keystr);
452 expiretime = getExpire(db,&key);
453
454 /* Save the expire time */
455 if (expiretime != -1) {
456 /* If this key is already expired skip it */
457 if (expiretime < now) continue;
458 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
459 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
460 }
461 /* Save the key and associated value. This requires special
462 * handling if the value is swapped out. */
463 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
464 o->storage == REDIS_VM_SWAPPING) {
465 /* Save type, key, value */
466 if (rdbSaveType(fp,o->type) == -1) goto werr;
467 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
468 if (rdbSaveObject(fp,o) == -1) goto werr;
469 } else {
470 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
471 robj *po;
472 /* Get a preview of the object in memory */
473 po = vmPreviewObject(o);
474 /* Save type, key, value */
475 if (rdbSaveType(fp,po->type) == -1) goto werr;
476 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
477 if (rdbSaveObject(fp,po) == -1) goto werr;
478 /* Remove the loaded object from memory */
479 decrRefCount(po);
480 }
481 }
482 dictReleaseIterator(di);
483 }
484 /* EOF opcode */
485 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
486
487 /* Make sure data will not remain on the OS's output buffers */
488 fflush(fp);
489 fsync(fileno(fp));
490 fclose(fp);
491
492 /* Use RENAME to make sure the DB file is changed atomically only
493 * if the generate DB file is ok. */
494 if (rename(tmpfile,filename) == -1) {
495 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
496 unlink(tmpfile);
497 return REDIS_ERR;
498 }
499 redisLog(REDIS_NOTICE,"DB saved on disk");
500 server.dirty = 0;
501 server.lastsave = time(NULL);
502 return REDIS_OK;
503
504 werr:
505 fclose(fp);
506 unlink(tmpfile);
507 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
508 if (di) dictReleaseIterator(di);
509 return REDIS_ERR;
510 }
511
512 int rdbSaveBackground(char *filename) {
513 pid_t childpid;
514
515 if (server.bgsavechildpid != -1) return REDIS_ERR;
516 if (server.vm_enabled) waitEmptyIOJobsQueue();
517 server.dirty_before_bgsave = server.dirty;
518 if ((childpid = fork()) == 0) {
519 /* Child */
520 if (server.vm_enabled) vmReopenSwapFile();
521 if (server.ipfd > 0) close(server.ipfd);
522 if (server.sofd > 0) close(server.sofd);
523 if (rdbSave(filename) == REDIS_OK) {
524 _exit(0);
525 } else {
526 _exit(1);
527 }
528 } else {
529 /* Parent */
530 if (childpid == -1) {
531 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
532 strerror(errno));
533 return REDIS_ERR;
534 }
535 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
536 server.bgsavechildpid = childpid;
537 updateDictResizePolicy();
538 return REDIS_OK;
539 }
540 return REDIS_OK; /* unreached */
541 }
542
543 void rdbRemoveTempFile(pid_t childpid) {
544 char tmpfile[256];
545
546 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
547 unlink(tmpfile);
548 }
549
550 int rdbLoadType(FILE *fp) {
551 unsigned char type;
552 if (fread(&type,1,1,fp) == 0) return -1;
553 return type;
554 }
555
556 time_t rdbLoadTime(FILE *fp) {
557 int32_t t32;
558 if (fread(&t32,4,1,fp) == 0) return -1;
559 return (time_t) t32;
560 }
561
562 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
563 * of this file for a description of how this are stored on disk.
564 *
565 * isencoded is set to 1 if the readed length is not actually a length but
566 * an "encoding type", check the above comments for more info */
567 uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
568 unsigned char buf[2];
569 uint32_t len;
570 int type;
571
572 if (isencoded) *isencoded = 0;
573 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
574 type = (buf[0]&0xC0)>>6;
575 if (type == REDIS_RDB_6BITLEN) {
576 /* Read a 6 bit len */
577 return buf[0]&0x3F;
578 } else if (type == REDIS_RDB_ENCVAL) {
579 /* Read a 6 bit len encoding type */
580 if (isencoded) *isencoded = 1;
581 return buf[0]&0x3F;
582 } else if (type == REDIS_RDB_14BITLEN) {
583 /* Read a 14 bit len */
584 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
585 return ((buf[0]&0x3F)<<8)|buf[1];
586 } else {
587 /* Read a 32 bit len */
588 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
589 return ntohl(len);
590 }
591 }
592
593 /* Load an integer-encoded object from file 'fp', with the specified
594 * encoding type 'enctype'. If encode is true the function may return
595 * an integer-encoded object as reply, otherwise the returned object
596 * will always be encoded as a raw string. */
597 robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
598 unsigned char enc[4];
599 long long val;
600
601 if (enctype == REDIS_RDB_ENC_INT8) {
602 if (fread(enc,1,1,fp) == 0) return NULL;
603 val = (signed char)enc[0];
604 } else if (enctype == REDIS_RDB_ENC_INT16) {
605 uint16_t v;
606 if (fread(enc,2,1,fp) == 0) return NULL;
607 v = enc[0]|(enc[1]<<8);
608 val = (int16_t)v;
609 } else if (enctype == REDIS_RDB_ENC_INT32) {
610 uint32_t v;
611 if (fread(enc,4,1,fp) == 0) return NULL;
612 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
613 val = (int32_t)v;
614 } else {
615 val = 0; /* anti-warning */
616 redisPanic("Unknown RDB integer encoding type");
617 }
618 if (encode)
619 return createStringObjectFromLongLong(val);
620 else
621 return createObject(REDIS_STRING,sdsfromlonglong(val));
622 }
623
624 robj *rdbLoadLzfStringObject(FILE*fp) {
625 unsigned int len, clen;
626 unsigned char *c = NULL;
627 sds val = NULL;
628
629 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
630 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
631 if ((c = zmalloc(clen)) == NULL) goto err;
632 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
633 if (fread(c,clen,1,fp) == 0) goto err;
634 if (lzf_decompress(c,clen,val,len) == 0) goto err;
635 zfree(c);
636 return createObject(REDIS_STRING,val);
637 err:
638 zfree(c);
639 sdsfree(val);
640 return NULL;
641 }
642
643 robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
644 int isencoded;
645 uint32_t len;
646 sds val;
647
648 len = rdbLoadLen(fp,&isencoded);
649 if (isencoded) {
650 switch(len) {
651 case REDIS_RDB_ENC_INT8:
652 case REDIS_RDB_ENC_INT16:
653 case REDIS_RDB_ENC_INT32:
654 return rdbLoadIntegerObject(fp,len,encode);
655 case REDIS_RDB_ENC_LZF:
656 return rdbLoadLzfStringObject(fp);
657 default:
658 redisPanic("Unknown RDB encoding type");
659 }
660 }
661
662 if (len == REDIS_RDB_LENERR) return NULL;
663 val = sdsnewlen(NULL,len);
664 if (len && fread(val,len,1,fp) == 0) {
665 sdsfree(val);
666 return NULL;
667 }
668 return createObject(REDIS_STRING,val);
669 }
670
671 robj *rdbLoadStringObject(FILE *fp) {
672 return rdbGenericLoadStringObject(fp,0);
673 }
674
675 robj *rdbLoadEncodedStringObject(FILE *fp) {
676 return rdbGenericLoadStringObject(fp,1);
677 }
678
679 /* For information about double serialization check rdbSaveDoubleValue() */
680 int rdbLoadDoubleValue(FILE *fp, double *val) {
681 char buf[128];
682 unsigned char len;
683
684 if (fread(&len,1,1,fp) == 0) return -1;
685 switch(len) {
686 case 255: *val = R_NegInf; return 0;
687 case 254: *val = R_PosInf; return 0;
688 case 253: *val = R_Nan; return 0;
689 default:
690 if (fread(buf,len,1,fp) == 0) return -1;
691 buf[len] = '\0';
692 sscanf(buf, "%lg", val);
693 return 0;
694 }
695 }
696
697 /* Load a Redis object of the specified type from the specified file.
698 * On success a newly allocated object is returned, otherwise NULL. */
699 robj *rdbLoadObject(int type, FILE *fp) {
700 robj *o, *ele, *dec;
701 size_t len;
702 unsigned int i;
703
704 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
705 if (type == REDIS_STRING) {
706 /* Read string value */
707 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
708 o = tryObjectEncoding(o);
709 } else if (type == REDIS_LIST) {
710 /* Read list value */
711 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
712
713 /* Use a real list when there are too many entries */
714 if (len > server.list_max_ziplist_entries) {
715 o = createListObject();
716 } else {
717 o = createZiplistObject();
718 }
719
720 /* Load every single element of the list */
721 while(len--) {
722 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
723
724 /* If we are using a ziplist and the value is too big, convert
725 * the object to a real list. */
726 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
727 ele->encoding == REDIS_ENCODING_RAW &&
728 sdslen(ele->ptr) > server.list_max_ziplist_value)
729 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
730
731 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
732 dec = getDecodedObject(ele);
733 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
734 decrRefCount(dec);
735 decrRefCount(ele);
736 } else {
737 ele = tryObjectEncoding(ele);
738 listAddNodeTail(o->ptr,ele);
739 }
740 }
741 } else if (type == REDIS_SET) {
742 /* Read list/set value */
743 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
744
745 /* Use a regular set when there are too many entries. */
746 if (len > server.set_max_intset_entries) {
747 o = createSetObject();
748 /* It's faster to expand the dict to the right size asap in order
749 * to avoid rehashing */
750 if (len > DICT_HT_INITIAL_SIZE)
751 dictExpand(o->ptr,len);
752 } else {
753 o = createIntsetObject();
754 }
755
756 /* Load every single element of the list/set */
757 for (i = 0; i < len; i++) {
758 long long llval;
759 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
760 ele = tryObjectEncoding(ele);
761
762 if (o->encoding == REDIS_ENCODING_INTSET) {
763 /* Fetch integer value from element */
764 if (isObjectRepresentableAsLongLong(ele,&llval) == REDIS_OK) {
765 o->ptr = intsetAdd(o->ptr,llval,NULL);
766 } else {
767 setTypeConvert(o,REDIS_ENCODING_HT);
768 dictExpand(o->ptr,len);
769 }
770 }
771
772 /* This will also be called when the set was just converted
773 * to regular hashtable encoded set */
774 if (o->encoding == REDIS_ENCODING_HT) {
775 dictAdd((dict*)o->ptr,ele,NULL);
776 } else {
777 decrRefCount(ele);
778 }
779 }
780 } else if (type == REDIS_ZSET) {
781 /* Read list/set value */
782 size_t zsetlen;
783 zset *zs;
784
785 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
786 o = createZsetObject();
787 zs = o->ptr;
788 /* Load every single element of the list/set */
789 while(zsetlen--) {
790 robj *ele;
791 double score;
792 zskiplistNode *znode;
793
794 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
795 ele = tryObjectEncoding(ele);
796 if (rdbLoadDoubleValue(fp,&score) == -1) return NULL;
797 znode = zslInsert(zs->zsl,score,ele);
798 dictAdd(zs->dict,ele,&znode->score);
799 incrRefCount(ele); /* added to skiplist */
800 }
801 } else if (type == REDIS_HASH) {
802 size_t hashlen;
803
804 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
805 o = createHashObject();
806 /* Too many entries? Use an hash table. */
807 if (hashlen > server.hash_max_zipmap_entries)
808 convertToRealHash(o);
809 /* Load every key/value, then set it into the zipmap or hash
810 * table, as needed. */
811 while(hashlen--) {
812 robj *key, *val;
813
814 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
815 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
816 /* If we are using a zipmap and there are too big values
817 * the object is converted to real hash table encoding. */
818 if (o->encoding != REDIS_ENCODING_HT &&
819 ((key->encoding == REDIS_ENCODING_RAW &&
820 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
821 (val->encoding == REDIS_ENCODING_RAW &&
822 sdslen(val->ptr) > server.hash_max_zipmap_value)))
823 {
824 convertToRealHash(o);
825 }
826
827 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
828 unsigned char *zm = o->ptr;
829 robj *deckey, *decval;
830
831 /* We need raw string objects to add them to the zipmap */
832 deckey = getDecodedObject(key);
833 decval = getDecodedObject(val);
834 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
835 decval->ptr,sdslen(decval->ptr),NULL);
836 o->ptr = zm;
837 decrRefCount(deckey);
838 decrRefCount(decval);
839 decrRefCount(key);
840 decrRefCount(val);
841 } else {
842 key = tryObjectEncoding(key);
843 val = tryObjectEncoding(val);
844 dictAdd((dict*)o->ptr,key,val);
845 }
846 }
847 } else {
848 redisPanic("Unknown object type");
849 }
850 return o;
851 }
852
853 /* Mark that we are loading in the global state and setup the fields
854 * needed to provide loading stats. */
855 void startLoading(FILE *fp) {
856 struct stat sb;
857
858 /* Load the DB */
859 server.loading = 1;
860 server.loading_start_time = time(NULL);
861 if (fstat(fileno(fp), &sb) == -1) {
862 server.loading_total_bytes = 1; /* just to avoid division by zero */
863 } else {
864 server.loading_total_bytes = sb.st_size;
865 }
866 }
867
868 /* Refresh the loading progress info */
869 void loadingProgress(off_t pos) {
870 server.loading_loaded_bytes = pos;
871 }
872
873 /* Loading finished */
874 void stopLoading(void) {
875 server.loading = 0;
876 }
877
878 int rdbLoad(char *filename) {
879 FILE *fp;
880 uint32_t dbid;
881 int type, retval, rdbver;
882 int swap_all_values = 0;
883 redisDb *db = server.db+0;
884 char buf[1024];
885 time_t expiretime, now = time(NULL);
886 long loops = 0;
887
888 fp = fopen(filename,"r");
889 if (!fp) return REDIS_ERR;
890 if (fread(buf,9,1,fp) == 0) goto eoferr;
891 buf[9] = '\0';
892 if (memcmp(buf,"REDIS",5) != 0) {
893 fclose(fp);
894 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
895 return REDIS_ERR;
896 }
897 rdbver = atoi(buf+5);
898 if (rdbver != 1) {
899 fclose(fp);
900 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
901 return REDIS_ERR;
902 }
903
904 startLoading(fp);
905 while(1) {
906 robj *key, *val;
907 int force_swapout;
908
909 expiretime = -1;
910
911 /* Serve the clients from time to time */
912 if (!(loops++ % 1000)) {
913 loadingProgress(ftello(fp));
914 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
915 }
916
917 /* Read type. */
918 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
919 if (type == REDIS_EXPIRETIME) {
920 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
921 /* We read the time so we need to read the object type again */
922 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
923 }
924 if (type == REDIS_EOF) break;
925 /* Handle SELECT DB opcode as a special case */
926 if (type == REDIS_SELECTDB) {
927 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
928 goto eoferr;
929 if (dbid >= (unsigned)server.dbnum) {
930 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
931 exit(1);
932 }
933 db = server.db+dbid;
934 continue;
935 }
936 /* Read key */
937 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
938 /* Read value */
939 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
940 /* Check if the key already expired */
941 if (expiretime != -1 && expiretime < now) {
942 decrRefCount(key);
943 decrRefCount(val);
944 continue;
945 }
946 /* Add the new object in the hash table */
947 retval = dbAdd(db,key,val);
948 if (retval == REDIS_ERR) {
949 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
950 exit(1);
951 }
952 /* Set the expire time if needed */
953 if (expiretime != -1) setExpire(db,key,expiretime);
954
955 /* Handle swapping while loading big datasets when VM is on */
956
957 /* If we detecter we are hopeless about fitting something in memory
958 * we just swap every new key on disk. Directly...
959 * Note that's important to check for this condition before resorting
960 * to random sampling, otherwise we may try to swap already
961 * swapped keys. */
962 if (swap_all_values) {
963 dictEntry *de = dictFind(db->dict,key->ptr);
964
965 /* de may be NULL since the key already expired */
966 if (de) {
967 vmpointer *vp;
968 val = dictGetEntryVal(de);
969
970 if (val->refcount == 1 &&
971 (vp = vmSwapObjectBlocking(val)) != NULL)
972 dictGetEntryVal(de) = vp;
973 }
974 decrRefCount(key);
975 continue;
976 }
977 decrRefCount(key);
978
979 /* Flush data on disk once 32 MB of additional RAM are used... */
980 force_swapout = 0;
981 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
982 force_swapout = 1;
983
984 /* If we have still some hope of having some value fitting memory
985 * then we try random sampling. */
986 if (!swap_all_values && server.vm_enabled && force_swapout) {
987 while (zmalloc_used_memory() > server.vm_max_memory) {
988 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
989 }
990 if (zmalloc_used_memory() > server.vm_max_memory)
991 swap_all_values = 1; /* We are already using too much mem */
992 }
993 }
994 fclose(fp);
995 stopLoading();
996 return REDIS_OK;
997
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.");
1000 exit(1);
1001 return REDIS_ERR; /* Just to avoid warning */
1002 }
1003
1004 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1005 void backgroundSaveDoneHandler(int statloc) {
1006 int exitcode = WEXITSTATUS(statloc);
1007 int bysignal = WIFSIGNALED(statloc);
1008
1009 if (!bysignal && exitcode == 0) {
1010 redisLog(REDIS_NOTICE,
1011 "Background saving terminated with success");
1012 server.dirty = server.dirty - server.dirty_before_bgsave;
1013 server.lastsave = time(NULL);
1014 } else if (!bysignal && exitcode != 0) {
1015 redisLog(REDIS_WARNING, "Background saving error");
1016 } else {
1017 redisLog(REDIS_WARNING,
1018 "Background saving terminated by signal %d", WTERMSIG(statloc));
1019 rdbRemoveTempFile(server.bgsavechildpid);
1020 }
1021 server.bgsavechildpid = -1;
1022 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1023 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1024 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1025 }