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