]> git.saurik.com Git - redis.git/blame - src/rdb.c
source reshaped a bit to play well with a bgsaving thread, still work to do, does...
[redis.git] / src / rdb.c
CommitLineData
e2641e09 1#include "redis.h"
2#include "lzf.h" /* LZF compression library */
3
4#include <math.h>
3688d7f3 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>
97e7f8ae 10#include <sys/stat.h>
e2641e09 11
9a68cf91
PN
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. */
16static 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
e2641e09 21int rdbSaveType(FILE *fp, unsigned char type) {
9a68cf91 22 return rdbWriteRaw(fp,&type,1);
e2641e09 23}
24
25int rdbSaveTime(FILE *fp, time_t t) {
26 int32_t t32 = (int32_t) t;
9a68cf91 27 return rdbWriteRaw(fp,&t32,4);
e2641e09 28}
29
30/* check rdbLoadLen() comments for more info */
31int rdbSaveLen(FILE *fp, uint32_t len) {
32 unsigned char buf[2];
8a623a98 33 int nwritten;
e2641e09 34
35 if (len < (1<<6)) {
36 /* Save a 6 bit len */
37 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
9a68cf91 38 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
8a623a98 39 nwritten = 1;
e2641e09 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;
9a68cf91 44 if (rdbWriteRaw(fp,buf,2) == -1) return -1;
8a623a98 45 nwritten = 2;
e2641e09 46 } else {
47 /* Save a 32 bit len */
48 buf[0] = (REDIS_RDB_32BITLEN<<6);
9a68cf91 49 if (rdbWriteRaw(fp,buf,1) == -1) return -1;
e2641e09 50 len = htonl(len);
9a68cf91 51 if (rdbWriteRaw(fp,&len,4) == -1) return -1;
8a623a98 52 nwritten = 1+4;
e2641e09 53 }
8a623a98 54 return nwritten;
e2641e09 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. */
62int 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 */
88int 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
104int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
105 size_t comprlen, outlen;
106 unsigned char byte;
8a623a98 107 int n, nwritten = 0;
e2641e09 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;
9a68cf91
PN
121 if ((n = rdbWriteRaw(fp,&byte,1)) == -1) goto writeerr;
122 nwritten += n;
8a623a98
PN
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
9a68cf91
PN
130 if ((n = rdbWriteRaw(fp,out,comprlen)) == -1) goto writeerr;
131 nwritten += n;
8a623a98 132
e2641e09 133 zfree(out);
8a623a98 134 return nwritten;
e2641e09 135
136writeerr:
137 zfree(out);
138 return -1;
139}
140
141/* Save a string objet as [len][data] on disk. If the object is a string
142 * representation of an integer value we try to safe it in a special form */
143int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
144 int enclen;
8a623a98 145 int n, nwritten = 0;
e2641e09 146
147 /* Try integer encoding */
148 if (len <= 11) {
149 unsigned char buf[5];
150 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
9a68cf91 151 if (rdbWriteRaw(fp,buf,enclen) == -1) return -1;
8a623a98 152 return enclen;
e2641e09 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) {
8a623a98
PN
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 */
e2641e09 163 }
164
165 /* Store verbatim */
8a623a98
PN
166 if ((n = rdbSaveLen(fp,len)) == -1) return -1;
167 nwritten += n;
168 if (len > 0) {
9a68cf91 169 if (rdbWriteRaw(fp,s,len) == -1) return -1;
8a623a98
PN
170 nwritten += len;
171 }
172 return nwritten;
e2641e09 173}
174
175/* Save a long long value as either an encoded string or a string. */
176int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
177 unsigned char buf[32];
8a623a98 178 int n, nwritten = 0;
e2641e09 179 int enclen = rdbEncodeInteger(value,buf);
180 if (enclen > 0) {
9a68cf91 181 return rdbWriteRaw(fp,buf,enclen);
e2641e09 182 } else {
183 /* Encode as string */
184 enclen = ll2string((char*)buf,32,value);
185 redisAssert(enclen < 32);
8a623a98
PN
186 if ((n = rdbSaveLen(fp,enclen)) == -1) return -1;
187 nwritten += n;
9a68cf91
PN
188 if ((n = rdbWriteRaw(fp,buf,enclen)) == -1) return -1;
189 nwritten += n;
e2641e09 190 }
8a623a98 191 return nwritten;
e2641e09 192}
193
194/* Like rdbSaveStringObjectRaw() but handle encoded objects */
195int 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 */
214int 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 }
9a68cf91 245 return rdbWriteRaw(fp,buf,len);
e2641e09 246}
247
248/* Save a Redis object. */
249int rdbSaveObject(FILE *fp, robj *o) {
8a623a98
PN
250 int n, nwritten = 0;
251
e2641e09 252 if (o->type == REDIS_STRING) {
253 /* Save a string value */
8a623a98
PN
254 if ((n = rdbSaveStringObject(fp,o)) == -1) return -1;
255 nwritten += n;
e2641e09 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
8a623a98
PN
264 if ((n = rdbSaveLen(fp,ziplistLen(o->ptr))) == -1) return -1;
265 nwritten += n;
266
e2641e09 267 p = ziplistIndex(o->ptr,0);
268 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
269 if (vstr) {
8a623a98 270 if ((n = rdbSaveRawString(fp,vstr,vlen)) == -1)
e2641e09 271 return -1;
8a623a98 272 nwritten += n;
e2641e09 273 } else {
8a623a98 274 if ((n = rdbSaveLongLongAsStringObject(fp,vlong)) == -1)
e2641e09 275 return -1;
8a623a98 276 nwritten += n;
e2641e09 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
8a623a98
PN
285 if ((n = rdbSaveLen(fp,listLength(list))) == -1) return -1;
286 nwritten += n;
287
e2641e09 288 listRewind(list,&li);
289 while((ln = listNext(&li))) {
290 robj *eleobj = listNodeValue(ln);
8a623a98
PN
291 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
292 nwritten += n;
e2641e09 293 }
294 } else {
295 redisPanic("Unknown list encoding");
296 }
297 } else if (o->type == REDIS_SET) {
298 /* Save a set value */
96ffb2fe
PN
299 if (o->encoding == REDIS_ENCODING_HT) {
300 dict *set = o->ptr;
301 dictIterator *di = dictGetIterator(set);
302 dictEntry *de;
e2641e09 303
8a623a98
PN
304 if ((n = rdbSaveLen(fp,dictSize(set))) == -1) return -1;
305 nwritten += n;
306
96ffb2fe
PN
307 while((de = dictNext(di)) != NULL) {
308 robj *eleobj = dictGetEntryKey(de);
8a623a98
PN
309 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
310 nwritten += n;
96ffb2fe
PN
311 }
312 dictReleaseIterator(di);
313 } else if (o->encoding == REDIS_ENCODING_INTSET) {
314 intset *is = o->ptr;
23c64fe5 315 int64_t llval;
96ffb2fe
PN
316 int i = 0;
317
8a623a98
PN
318 if ((n = rdbSaveLen(fp,intsetLen(is))) == -1) return -1;
319 nwritten += n;
320
96ffb2fe 321 while(intsetGet(is,i++,&llval)) {
8a623a98
PN
322 if ((n = rdbSaveLongLongAsStringObject(fp,llval)) == -1) return -1;
323 nwritten += n;
96ffb2fe
PN
324 }
325 } else {
326 redisPanic("Unknown set encoding");
e2641e09 327 }
e2641e09 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
8a623a98
PN
334 if ((n = rdbSaveLen(fp,dictSize(zs->dict))) == -1) return -1;
335 nwritten += n;
336
e2641e09 337 while((de = dictNext(di)) != NULL) {
338 robj *eleobj = dictGetEntryKey(de);
339 double *score = dictGetEntryVal(de);
340
8a623a98
PN
341 if ((n = rdbSaveStringObject(fp,eleobj)) == -1) return -1;
342 nwritten += n;
343 if ((n = rdbSaveDoubleValue(fp,*score)) == -1) return -1;
344 nwritten += n;
e2641e09 345 }
346 dictReleaseIterator(di);
347 } else if (o->type == REDIS_HASH) {
348 /* Save a hash value */
349 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
350 unsigned char *p = zipmapRewind(o->ptr);
351 unsigned int count = zipmapLen(o->ptr);
352 unsigned char *key, *val;
353 unsigned int klen, vlen;
354
8a623a98
PN
355 if ((n = rdbSaveLen(fp,count)) == -1) return -1;
356 nwritten += n;
357
e2641e09 358 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
8a623a98
PN
359 if ((n = rdbSaveRawString(fp,key,klen)) == -1) return -1;
360 nwritten += n;
361 if ((n = rdbSaveRawString(fp,val,vlen)) == -1) return -1;
362 nwritten += n;
e2641e09 363 }
364 } else {
365 dictIterator *di = dictGetIterator(o->ptr);
366 dictEntry *de;
367
8a623a98
PN
368 if ((n = rdbSaveLen(fp,dictSize((dict*)o->ptr))) == -1) return -1;
369 nwritten += n;
370
e2641e09 371 while((de = dictNext(di)) != NULL) {
372 robj *key = dictGetEntryKey(de);
373 robj *val = dictGetEntryVal(de);
374
8a623a98
PN
375 if ((n = rdbSaveStringObject(fp,key)) == -1) return -1;
376 nwritten += n;
377 if ((n = rdbSaveStringObject(fp,val)) == -1) return -1;
378 nwritten += n;
e2641e09 379 }
380 dictReleaseIterator(di);
381 }
382 } else {
383 redisPanic("Unknown object type");
384 }
8a623a98 385 return nwritten;
e2641e09 386}
387
388/* Return the length the object will have on disk if saved with
389 * the rdbSaveObject() function. Currently we use a trick to get
390 * this length with very little changes to the code. In the future
391 * we could switch to a faster solution. */
bd70a5f5
PN
392off_t rdbSavedObjectLen(robj *o) {
393 int len = rdbSaveObject(NULL,o);
394 redisAssert(len != -1);
395 return len;
e2641e09 396}
397
4ab98823 398/* Save a key-value pair, with expire time, type, key, value.
399 * On error -1 is returned.
400 * On success if the key was actaully saved 1 is returned, otherwise 0
401 * is returned (the key was already expired). */
402int rdbSaveKeyValuePair(FILE *fp, redisDb *db, robj *key, robj *val,
403 time_t now)
404{
405 time_t expiretime;
406
1fce3201 407 expiretime = getExpire(db,key);
4ab98823 408
409 /* Save the expire time */
410 if (expiretime != -1) {
411 /* If this key is already expired skip it */
412 if (expiretime < now) return 0;
413 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) return -1;
414 if (rdbSaveTime(fp,expiretime) == -1) return -1;
415 }
416 /* Save type, key, value */
417 if (rdbSaveType(fp,val->type) == -1) return -1;
1fce3201 418 if (rdbSaveStringObject(fp,key) == -1) return -1;
4ab98823 419 if (rdbSaveObject(fp,val) == -1) return -1;
420 return 1;
421}
422
e2641e09 423/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
424int rdbSave(char *filename) {
425 dictIterator *di = NULL;
426 dictEntry *de;
427 FILE *fp;
428 char tmpfile[256];
429 int j;
430 time_t now = time(NULL);
431
249ad25f 432 if (server.ds_enabled) {
433 cacheForcePointInTime();
434 return dsRdbSave(filename);
435 }
e2641e09 436
437 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
438 fp = fopen(tmpfile,"w");
439 if (!fp) {
440 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
441 return REDIS_ERR;
442 }
443 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
444 for (j = 0; j < server.dbnum; j++) {
445 redisDb *db = server.db+j;
446 dict *d = db->dict;
447 if (dictSize(d) == 0) continue;
448 di = dictGetIterator(d);
449 if (!di) {
450 fclose(fp);
451 return REDIS_ERR;
452 }
453
454 /* Write the SELECT DB opcode */
455 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
456 if (rdbSaveLen(fp,j) == -1) goto werr;
457
458 /* Iterate this DB writing every entry */
459 while((de = dictNext(di)) != NULL) {
460 sds keystr = dictGetEntryKey(de);
461 robj key, *o = dictGetEntryVal(de);
e2641e09 462
463 initStaticStringObject(key,keystr);
1fce3201 464 if (rdbSaveKeyValuePair(fp,db,&key,o,now) == -1) goto werr;
e2641e09 465 }
466 dictReleaseIterator(di);
467 }
468 /* EOF opcode */
469 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
470
471 /* Make sure data will not remain on the OS's output buffers */
472 fflush(fp);
473 fsync(fileno(fp));
474 fclose(fp);
475
476 /* Use RENAME to make sure the DB file is changed atomically only
477 * if the generate DB file is ok. */
478 if (rename(tmpfile,filename) == -1) {
479 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
480 unlink(tmpfile);
481 return REDIS_ERR;
482 }
483 redisLog(REDIS_NOTICE,"DB saved on disk");
484 server.dirty = 0;
485 server.lastsave = time(NULL);
486 return REDIS_OK;
487
488werr:
489 fclose(fp);
490 unlink(tmpfile);
491 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
492 if (di) dictReleaseIterator(di);
493 return REDIS_ERR;
494}
495
496int rdbSaveBackground(char *filename) {
497 pid_t childpid;
498
36c17a53 499 if (server.bgsavechildpid != -1 ||
500 server.bgsavethread != (pthread_t) -1) return REDIS_ERR;
249ad25f 501
2f6b31c3 502 server.dirty_before_bgsave = server.dirty;
249ad25f 503
36c17a53 504 if (server.ds_enabled) {
505 cacheForcePointInTime();
506 return dsRdbSave(filename);
507 }
508
e2641e09 509 if ((childpid = fork()) == 0) {
249ad25f 510 int retval;
511
e2641e09 512 /* Child */
a5639e7d
PN
513 if (server.ipfd > 0) close(server.ipfd);
514 if (server.sofd > 0) close(server.sofd);
36c17a53 515 retval = rdbSave(filename);
249ad25f 516 _exit((retval == REDIS_OK) ? 0 : 1);
e2641e09 517 } else {
518 /* Parent */
519 if (childpid == -1) {
520 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
521 strerror(errno));
522 return REDIS_ERR;
523 }
524 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
525 server.bgsavechildpid = childpid;
526 updateDictResizePolicy();
527 return REDIS_OK;
528 }
529 return REDIS_OK; /* unreached */
530}
531
532void rdbRemoveTempFile(pid_t childpid) {
533 char tmpfile[256];
534
535 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
536 unlink(tmpfile);
537}
538
539int rdbLoadType(FILE *fp) {
540 unsigned char type;
541 if (fread(&type,1,1,fp) == 0) return -1;
542 return type;
543}
544
545time_t rdbLoadTime(FILE *fp) {
546 int32_t t32;
547 if (fread(&t32,4,1,fp) == 0) return -1;
548 return (time_t) t32;
549}
550
551/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
552 * of this file for a description of how this are stored on disk.
553 *
554 * isencoded is set to 1 if the readed length is not actually a length but
555 * an "encoding type", check the above comments for more info */
556uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
557 unsigned char buf[2];
558 uint32_t len;
559 int type;
560
561 if (isencoded) *isencoded = 0;
562 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
563 type = (buf[0]&0xC0)>>6;
564 if (type == REDIS_RDB_6BITLEN) {
565 /* Read a 6 bit len */
566 return buf[0]&0x3F;
567 } else if (type == REDIS_RDB_ENCVAL) {
568 /* Read a 6 bit len encoding type */
569 if (isencoded) *isencoded = 1;
570 return buf[0]&0x3F;
571 } else if (type == REDIS_RDB_14BITLEN) {
572 /* Read a 14 bit len */
573 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
574 return ((buf[0]&0x3F)<<8)|buf[1];
575 } else {
576 /* Read a 32 bit len */
577 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
578 return ntohl(len);
579 }
580}
581
582/* Load an integer-encoded object from file 'fp', with the specified
583 * encoding type 'enctype'. If encode is true the function may return
584 * an integer-encoded object as reply, otherwise the returned object
585 * will always be encoded as a raw string. */
586robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
587 unsigned char enc[4];
588 long long val;
589
590 if (enctype == REDIS_RDB_ENC_INT8) {
591 if (fread(enc,1,1,fp) == 0) return NULL;
592 val = (signed char)enc[0];
593 } else if (enctype == REDIS_RDB_ENC_INT16) {
594 uint16_t v;
595 if (fread(enc,2,1,fp) == 0) return NULL;
596 v = enc[0]|(enc[1]<<8);
597 val = (int16_t)v;
598 } else if (enctype == REDIS_RDB_ENC_INT32) {
599 uint32_t v;
600 if (fread(enc,4,1,fp) == 0) return NULL;
601 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
602 val = (int32_t)v;
603 } else {
604 val = 0; /* anti-warning */
605 redisPanic("Unknown RDB integer encoding type");
606 }
607 if (encode)
608 return createStringObjectFromLongLong(val);
609 else
610 return createObject(REDIS_STRING,sdsfromlonglong(val));
611}
612
613robj *rdbLoadLzfStringObject(FILE*fp) {
614 unsigned int len, clen;
615 unsigned char *c = NULL;
616 sds val = NULL;
617
618 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
619 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
620 if ((c = zmalloc(clen)) == NULL) goto err;
621 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
622 if (fread(c,clen,1,fp) == 0) goto err;
623 if (lzf_decompress(c,clen,val,len) == 0) goto err;
624 zfree(c);
625 return createObject(REDIS_STRING,val);
626err:
627 zfree(c);
628 sdsfree(val);
629 return NULL;
630}
631
632robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
633 int isencoded;
634 uint32_t len;
635 sds val;
636
637 len = rdbLoadLen(fp,&isencoded);
638 if (isencoded) {
639 switch(len) {
640 case REDIS_RDB_ENC_INT8:
641 case REDIS_RDB_ENC_INT16:
642 case REDIS_RDB_ENC_INT32:
643 return rdbLoadIntegerObject(fp,len,encode);
644 case REDIS_RDB_ENC_LZF:
645 return rdbLoadLzfStringObject(fp);
646 default:
647 redisPanic("Unknown RDB encoding type");
648 }
649 }
650
651 if (len == REDIS_RDB_LENERR) return NULL;
652 val = sdsnewlen(NULL,len);
653 if (len && fread(val,len,1,fp) == 0) {
654 sdsfree(val);
655 return NULL;
656 }
657 return createObject(REDIS_STRING,val);
658}
659
660robj *rdbLoadStringObject(FILE *fp) {
661 return rdbGenericLoadStringObject(fp,0);
662}
663
664robj *rdbLoadEncodedStringObject(FILE *fp) {
665 return rdbGenericLoadStringObject(fp,1);
666}
667
668/* For information about double serialization check rdbSaveDoubleValue() */
669int rdbLoadDoubleValue(FILE *fp, double *val) {
670 char buf[128];
671 unsigned char len;
672
673 if (fread(&len,1,1,fp) == 0) return -1;
674 switch(len) {
675 case 255: *val = R_NegInf; return 0;
676 case 254: *val = R_PosInf; return 0;
677 case 253: *val = R_Nan; return 0;
678 default:
679 if (fread(buf,len,1,fp) == 0) return -1;
680 buf[len] = '\0';
681 sscanf(buf, "%lg", val);
682 return 0;
683 }
684}
685
686/* Load a Redis object of the specified type from the specified file.
687 * On success a newly allocated object is returned, otherwise NULL. */
688robj *rdbLoadObject(int type, FILE *fp) {
689 robj *o, *ele, *dec;
690 size_t len;
96ffb2fe 691 unsigned int i;
e2641e09 692
693 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
694 if (type == REDIS_STRING) {
695 /* Read string value */
696 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
697 o = tryObjectEncoding(o);
698 } else if (type == REDIS_LIST) {
699 /* Read list value */
700 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
701
702 /* Use a real list when there are too many entries */
703 if (len > server.list_max_ziplist_entries) {
704 o = createListObject();
705 } else {
706 o = createZiplistObject();
707 }
708
709 /* Load every single element of the list */
710 while(len--) {
711 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
712
713 /* If we are using a ziplist and the value is too big, convert
714 * the object to a real list. */
715 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
716 ele->encoding == REDIS_ENCODING_RAW &&
717 sdslen(ele->ptr) > server.list_max_ziplist_value)
718 listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
719
720 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
721 dec = getDecodedObject(ele);
722 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
723 decrRefCount(dec);
724 decrRefCount(ele);
725 } else {
726 ele = tryObjectEncoding(ele);
727 listAddNodeTail(o->ptr,ele);
728 }
729 }
730 } else if (type == REDIS_SET) {
731 /* Read list/set value */
732 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
96ffb2fe
PN
733
734 /* Use a regular set when there are too many entries. */
735 if (len > server.set_max_intset_entries) {
736 o = createSetObject();
737 /* It's faster to expand the dict to the right size asap in order
738 * to avoid rehashing */
739 if (len > DICT_HT_INITIAL_SIZE)
740 dictExpand(o->ptr,len);
741 } else {
742 o = createIntsetObject();
743 }
744
e2641e09 745 /* Load every single element of the list/set */
96ffb2fe
PN
746 for (i = 0; i < len; i++) {
747 long long llval;
e2641e09 748 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
749 ele = tryObjectEncoding(ele);
96ffb2fe
PN
750
751 if (o->encoding == REDIS_ENCODING_INTSET) {
752 /* Fetch integer value from element */
2df84b72 753 if (isObjectRepresentableAsLongLong(ele,&llval) == REDIS_OK) {
96ffb2fe
PN
754 o->ptr = intsetAdd(o->ptr,llval,NULL);
755 } else {
756 setTypeConvert(o,REDIS_ENCODING_HT);
757 dictExpand(o->ptr,len);
758 }
759 }
760
761 /* This will also be called when the set was just converted
762 * to regular hashtable encoded set */
763 if (o->encoding == REDIS_ENCODING_HT) {
764 dictAdd((dict*)o->ptr,ele,NULL);
bad7d097 765 } else {
766 decrRefCount(ele);
96ffb2fe 767 }
e2641e09 768 }
769 } else if (type == REDIS_ZSET) {
770 /* Read list/set value */
771 size_t zsetlen;
772 zset *zs;
773
774 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
775 o = createZsetObject();
776 zs = o->ptr;
777 /* Load every single element of the list/set */
778 while(zsetlen--) {
779 robj *ele;
56e52b69
PN
780 double score;
781 zskiplistNode *znode;
e2641e09 782
783 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
784 ele = tryObjectEncoding(ele);
56e52b69
PN
785 if (rdbLoadDoubleValue(fp,&score) == -1) return NULL;
786 znode = zslInsert(zs->zsl,score,ele);
787 dictAdd(zs->dict,ele,&znode->score);
e2641e09 788 incrRefCount(ele); /* added to skiplist */
789 }
790 } else if (type == REDIS_HASH) {
791 size_t hashlen;
792
793 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
794 o = createHashObject();
795 /* Too many entries? Use an hash table. */
796 if (hashlen > server.hash_max_zipmap_entries)
797 convertToRealHash(o);
798 /* Load every key/value, then set it into the zipmap or hash
799 * table, as needed. */
800 while(hashlen--) {
801 robj *key, *val;
802
803 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
804 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
805 /* If we are using a zipmap and there are too big values
806 * the object is converted to real hash table encoding. */
807 if (o->encoding != REDIS_ENCODING_HT &&
808 ((key->encoding == REDIS_ENCODING_RAW &&
809 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
810 (val->encoding == REDIS_ENCODING_RAW &&
811 sdslen(val->ptr) > server.hash_max_zipmap_value)))
812 {
813 convertToRealHash(o);
814 }
815
816 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
817 unsigned char *zm = o->ptr;
818 robj *deckey, *decval;
819
820 /* We need raw string objects to add them to the zipmap */
821 deckey = getDecodedObject(key);
822 decval = getDecodedObject(val);
823 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
824 decval->ptr,sdslen(decval->ptr),NULL);
825 o->ptr = zm;
826 decrRefCount(deckey);
827 decrRefCount(decval);
828 decrRefCount(key);
829 decrRefCount(val);
830 } else {
831 key = tryObjectEncoding(key);
832 val = tryObjectEncoding(val);
833 dictAdd((dict*)o->ptr,key,val);
834 }
835 }
836 } else {
837 redisPanic("Unknown object type");
838 }
839 return o;
840}
841
97e7f8ae 842/* Mark that we are loading in the global state and setup the fields
843 * needed to provide loading stats. */
844void startLoading(FILE *fp) {
845 struct stat sb;
846
847 /* Load the DB */
848 server.loading = 1;
849 server.loading_start_time = time(NULL);
850 if (fstat(fileno(fp), &sb) == -1) {
851 server.loading_total_bytes = 1; /* just to avoid division by zero */
852 } else {
853 server.loading_total_bytes = sb.st_size;
854 }
855}
856
857/* Refresh the loading progress info */
858void loadingProgress(off_t pos) {
859 server.loading_loaded_bytes = pos;
860}
861
862/* Loading finished */
863void stopLoading(void) {
864 server.loading = 0;
865}
866
e2641e09 867int rdbLoad(char *filename) {
868 FILE *fp;
869 uint32_t dbid;
870 int type, retval, rdbver;
e2641e09 871 redisDb *db = server.db+0;
872 char buf[1024];
873 time_t expiretime, now = time(NULL);
97e7f8ae 874 long loops = 0;
e2641e09 875
876 fp = fopen(filename,"r");
877 if (!fp) return REDIS_ERR;
878 if (fread(buf,9,1,fp) == 0) goto eoferr;
879 buf[9] = '\0';
880 if (memcmp(buf,"REDIS",5) != 0) {
881 fclose(fp);
882 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
883 return REDIS_ERR;
884 }
885 rdbver = atoi(buf+5);
886 if (rdbver != 1) {
887 fclose(fp);
888 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
889 return REDIS_ERR;
890 }
97e7f8ae 891
892 startLoading(fp);
e2641e09 893 while(1) {
894 robj *key, *val;
e2641e09 895 expiretime = -1;
97e7f8ae 896
897 /* Serve the clients from time to time */
898 if (!(loops++ % 1000)) {
899 loadingProgress(ftello(fp));
900 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
901 }
902
e2641e09 903 /* Read type. */
904 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
905 if (type == REDIS_EXPIRETIME) {
906 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
907 /* We read the time so we need to read the object type again */
908 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
909 }
910 if (type == REDIS_EOF) break;
911 /* Handle SELECT DB opcode as a special case */
912 if (type == REDIS_SELECTDB) {
913 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
914 goto eoferr;
915 if (dbid >= (unsigned)server.dbnum) {
916 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
917 exit(1);
918 }
919 db = server.db+dbid;
920 continue;
921 }
922 /* Read key */
923 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
924 /* Read value */
925 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
926 /* Check if the key already expired */
927 if (expiretime != -1 && expiretime < now) {
928 decrRefCount(key);
929 decrRefCount(val);
930 continue;
931 }
932 /* Add the new object in the hash table */
933 retval = dbAdd(db,key,val);
934 if (retval == REDIS_ERR) {
935 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
936 exit(1);
937 }
938 /* Set the expire time if needed */
939 if (expiretime != -1) setExpire(db,key,expiretime);
940
e2641e09 941 decrRefCount(key);
e2641e09 942 }
943 fclose(fp);
97e7f8ae 944 stopLoading();
e2641e09 945 return REDIS_OK;
946
947eoferr: /* unexpected end of file is handled here with a fatal exit */
948 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
949 exit(1);
950 return REDIS_ERR; /* Just to avoid warning */
951}
952
953/* A background saving child (BGSAVE) terminated its work. Handle this. */
36c17a53 954void backgroundSaveDoneHandler(int exitcode, int bysignal) {
e2641e09 955 if (!bysignal && exitcode == 0) {
956 redisLog(REDIS_NOTICE,
957 "Background saving terminated with success");
2f6b31c3 958 server.dirty = server.dirty - server.dirty_before_bgsave;
e2641e09 959 server.lastsave = time(NULL);
960 } else if (!bysignal && exitcode != 0) {
961 redisLog(REDIS_WARNING, "Background saving error");
962 } else {
963 redisLog(REDIS_WARNING,
36c17a53 964 "Background saving terminated by signal %d", bysignal);
e2641e09 965 rdbRemoveTempFile(server.bgsavechildpid);
966 }
967 server.bgsavechildpid = -1;
36c17a53 968 server.bgsavethread = (pthread_t) -1;
969 server.bgsavethread_state = REDIS_BGSAVE_THREAD_UNACTIVE;
e2641e09 970 /* Possibly there are slaves waiting for a BGSAVE in order to be served
971 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
972 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
973}
36c17a53 974
975void saveCommand(redisClient *c) {
976 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread-t)-1) {
977 addReplyError(c,"Background save already in progress");
978 return;
979 }
980 if (rdbSave(server.dbfilename) == REDIS_OK) {
981 addReply(c,shared.ok);
982 } else {
983 addReply(c,shared.err);
984 }
985}
986
987void bgsaveCommand(redisClient *c) {
988 if (server.bgsavechildpid != -1 || server.bgsavethread != (pthread-t)-1) {
989 addReplyError(c,"Background save already in progress");
990 return;
991 }
992 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
993 addReplyStatus(c,"Background saving started");
994 } else {
995 addReply(c,shared.err);
996 }
997}