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