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