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