-
Notifications
You must be signed in to change notification settings - Fork 38
/
rdb.c
executable file
·1996 lines (1804 loc) · 77.5 KB
/
rdb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "redis.h"
#include "lzf.h" /* LZF compression library */
#include "zipmap.h"
#include "endianconv.h"
#include <math.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/stat.h>
/* !!!! 下面使用的rio类型定义在rio.h文件中 !!!! */
/* 将p中长度为len的内容写入rdb中,写入成功返回写入的字节数,否则返回-1。 */
static int rdbWriteRaw(rio *rdb, void *p, size_t len) {
if (rdb && rioWrite(rdb,p,len) == 0)
return -1;
return len;
}
/* 将一个字节的type类型写入rdb中 */
int rdbSaveType(rio *rdb, unsigned char type) {
return rdbWriteRaw(rdb,&type,1);
}
/* Load a "type" in RDB format, that is a one byte unsigned integer.
* This function is not only used to load object types, but also special
* "types" like the end-of-file type, the EXPIRE type, and so forth. */
/* 从rdb中加载type类型,该字段是一个字节的无符号整型。
该函数既可以用来加载对象类型,也可以用来加载特殊的类型标识。
函数的返回值为加载的type值。*/
int rdbLoadType(rio *rdb) {
unsigned char type;
if (rioRead(rdb,&type,1) == 0) return -1;
return type;
}
/* 从rdb中加载以秒为单位的过期时间,用time_t类型表示。*/
time_t rdbLoadTime(rio *rdb) {
int32_t t32;
if (rioRead(rdb,&t32,4) == 0) return -1;
return (time_t)t32;
}
/* 将long long类型的、以毫秒为单位的过期时间写入rdb中。写入成功返回写入的字节数,否则返回-1。*/
int rdbSaveMillisecondTime(rio *rdb, long long t) {
int64_t t64 = (int64_t) t;
return rdbWriteRaw(rdb,&t64,8);
}
/* 从rdb中加载以毫秒为单位的过期时间,用long long类型表示。*/
long long rdbLoadMillisecondTime(rio *rdb) {
int64_t t64;
if (rioRead(rdb,&t64,8) == 0) return -1;
return (long long)t64;
}
/* Saves an encoded length. The first two bits in the first byte are used to
* hold the encoding type. See the REDIS_RDB_* definitions for more information
* on the types of encoding. */
/* 对长度len进行编码后写入rdb中。第一个字节的前两个bit用来保存编码类型,关于编码方式可以参看
rdb.h文件中REDIS_RDB_*了解。写入成功后返回写入的字节数。*/
int rdbSaveLen(rio *rdb, uint32_t len) {
unsigned char buf[2];
size_t nwritten;
// REDIS_RDB_6BITLEN编码
if (len < (1<<6)) {
/* Save a 6 bit len */
buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
if (rdbWriteRaw(rdb,buf,1) == -1) return -1;
nwritten = 1;
}
// REDIS_RDB_14BITLEN编码
else if (len < (1<<14)) {
/* Save a 14 bit len */
buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
buf[1] = len&0xFF;
if (rdbWriteRaw(rdb,buf,2) == -1) return -1;
nwritten = 2;
}
// REDIS_RDB_32BITLEN编码
else {
/* Save a 32 bit len */
buf[0] = (REDIS_RDB_32BITLEN<<6);
if (rdbWriteRaw(rdb,buf,1) == -1) return -1;
len = htonl(len);
if (rdbWriteRaw(rdb,&len,4) == -1) return -1;
nwritten = 1+4;
}
return nwritten;
}
/* Load an encoded length. The "isencoded" argument is set to 1 if the length
* is not actually a length but an "encoding type". See the REDIS_RDB_ENC_*
* definitions in rdb.h for more information. */
/* 从rdb中读入一个被编码的长度信息。
如果该长度信息并不是一个整型值,而是一个编码类型,则参数isencoded被设为1。
可以查看rdb.h文件中的REDIS_RDB_ENC_*了解更多信息。*/
uint32_t rdbLoadLen(rio *rdb, int *isencoded) {
unsigned char buf[2];
uint32_t len;
int type;
if (isencoded) *isencoded = 0;
// 从rdb中读入长度信息,这个值可能被编码也可能没有被编码,由前两个bit内容决定
if (rioRead(rdb,buf,1) == 0) return REDIS_RDB_LENERR;
// 取出前两个bit
type = (buf[0]&0xC0)>>6;
if (type == REDIS_RDB_ENCVAL) {
/* Read a 6 bit encoding type. */
if (isencoded) *isencoded = 1;
return buf[0]&0x3F;
}
// REDIS_RDB_6BITLEN编码
else if (type == REDIS_RDB_6BITLEN) {
/* Read a 6 bit len. */
return buf[0]&0x3F;
}
// REDIS_RDB_14BITLEN编码
else if (type == REDIS_RDB_14BITLEN) {
/* Read a 14 bit len. */
if (rioRead(rdb,buf+1,1) == 0) return REDIS_RDB_LENERR;
return ((buf[0]&0x3F)<<8)|buf[1];
}
// REDIS_RDB_32BITLEN编码
else {
/* Read a 32 bit len. */
if (rioRead(rdb,&len,4) == 0) return REDIS_RDB_LENERR;
return ntohl(len);
}
}
/* Encodes the "value" argument as integer when it fits in the supported ranges
* for encoded types. If the function successfully encodes the integer, the
* representation is stored in the buffer pointer to by "enc" and the string
* length is returned. Otherwise 0 is returned. */
/* 如果参数value在编码支持的范围内(编码方式见rdb.h头文件),尝试对其进行特殊的整型编码。
如果编码成功,将编码后的值保存在参数enc指定的缓冲区中并返回其长度。
如果编码失败则返回0。 */
int rdbEncodeInteger(long long value, unsigned char *enc) {
// REDIS_RDB_ENC_INT8编码
if (value >= -(1<<7) && value <= (1<<7)-1) {
enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
enc[1] = value&0xFF;
return 2;
}
// REDIS_RDB_ENC_INT16编码
else if (value >= -(1<<15) && value <= (1<<15)-1) {
enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
enc[1] = value&0xFF;
enc[2] = (value>>8)&0xFF;
return 3;
}
// REDIS_RDB_ENC_INT32编码
else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
enc[1] = value&0xFF;
enc[2] = (value>>8)&0xFF;
enc[3] = (value>>16)&0xFF;
enc[4] = (value>>24)&0xFF;
return 5;
} else {
return 0;
}
}
/* Loads an integer-encoded object with the specified encoding type "enctype".
* If the "encode" argument is set the function may return an integer-encoded
* string object, otherwise it always returns a raw string object. */
/* 从RDB文件中载入参数enctype指定编码方式的整型对象。
如果参数encode被设置,函数可能返回一个整型编码的字符串对象,否则函数总是返回未编码的字符串对象。*/
robj *rdbLoadIntegerObject(rio *rdb, int enctype, int encode) {
unsigned char enc[4];
long long val;
// REDIS_RDB_ENC_INT8编码
if (enctype == REDIS_RDB_ENC_INT8) {
if (rioRead(rdb,enc,1) == 0) return NULL;
val = (signed char)enc[0];
}
// REDIS_RDB_ENC_INT16编码
else if (enctype == REDIS_RDB_ENC_INT16) {
uint16_t v;
if (rioRead(rdb,enc,2) == 0) return NULL;
v = enc[0]|(enc[1]<<8);
val = (int16_t)v;
}
// REDIS_RDB_ENC_INT32编码
else if (enctype == REDIS_RDB_ENC_INT32) {
uint32_t v;
if (rioRead(rdb,enc,4) == 0) return NULL;
v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
val = (int32_t)v;
} else {
val = 0; /* anti-warning */
redisPanic("Unknown RDB integer encoding type");
}
if (encode)
// 整型编码的字符串
return createStringObjectFromLongLong(val);
else
// 未编码的字符串
return createObject(REDIS_STRING,sdsfromlonglong(val));
}
/* String objects in the form "2391" "-100" without any space and with a
* range of values that can fit in an 8, 16 or 32 bit signed value can be
* encoded as integers to save space */
/* 类似“2391”、“-100”这种形式的字符串对象可以编码为8位、16位、32位的带符号整型数以节省空间。
下面这个函数就是尝试将字符串对象编码为整型数,如果编码成功则返回保存整型数值需要的字节数,否则返回0。*/
int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
long long value;
char *endptr, buf[32];
/* Check if it's possible to encode this value as a number */
// 判断是否可以将字符串对象s转换为整型数值
value = strtoll(s, &endptr, 10);
// 转换失败,返回0
if (endptr[0] != '\0') return 0;
// 将转换后的整型转换为字符串对象
ll2string(buf,32,value);
/* If the number converted back into a string is not identical
* then it's not possible to encode the string as integer */
// 如果装换后的整数值不能还远回原来的字符串,则转换失败,返回0
if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
// 经过上面的检查后发现可以转换,则对转换后得到的整型数值进行编码
return rdbEncodeInteger(value,enc);
}
/* 使用lzf算法对参数s表示的字符串进行压缩后再写入RDB文件中。
该函数在操作成功时返回写入RDB文件中的字节数,如果内存不足或压缩失败返回0,如果写入失败返回-1。*/
int rdbSaveLzfStringObject(rio *rdb, unsigned char *s, size_t len) {
size_t comprlen, outlen;
unsigned char byte;
int n, nwritten = 0;
void *out;
/* We require at least four bytes compression for this to be worth it */
// 字符串s至少超过4个字节才值得压缩
if (len <= 4) return 0;
outlen = len-4;
// 内存不足,返回0
if ((out = zmalloc(outlen+1)) == NULL) return 0;
// 使用lzf算法进行字符串压缩
comprlen = lzf_compress(s, len, out, outlen);
// 压缩失败,释放空间后返回0
if (comprlen == 0) {
zfree(out);
return 0;
}
/* Data compressed! Let's save it on disk */
/* 经过上面的操作得到压缩后的字符串,现在讲其保存在RDB文件中。*/
// 写入类型信息,指明这是一个使用lzf压缩后得到的字符串
byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
if ((n = rdbWriteRaw(rdb,&byte,1)) == -1) goto writeerr;
// 记录写入的字节数
nwritten += n;
// 写入压缩后的字符串长度
if ((n = rdbSaveLen(rdb,comprlen)) == -1) goto writeerr;
// 记录写入的字节数
nwritten += n;
// 写入字符串压缩前的原始长度
if ((n = rdbSaveLen(rdb,len)) == -1) goto writeerr;
// 记录写入的字节数
nwritten += n;
// 写入压缩后的字符串
if ((n = rdbWriteRaw(rdb,out,comprlen)) == -1) goto writeerr;
// 记录写入的字节数
nwritten += n;
zfree(out);
// 返回写入的字节数
return nwritten;
writeerr:
zfree(out);
return -1;
}
/* 从RDB中加载被压缩的字符串,解析返回原始字符串对象。*/
robj *rdbLoadLzfStringObject(rio *rdb) {
unsigned int len, clen;
unsigned char *c = NULL;
sds val = NULL;
// 读取压缩后的字符串长度
if ((clen = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
// 读物字符串未压缩前的长度
if ((len = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
// 分配空间保存压缩后的字符串
if ((c = zmalloc(clen)) == NULL) goto err;
if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
// 读取压缩后的字符串信息
if (rioRead(rdb,c,clen) == 0) goto err;
// 解压缩得到原始字符串
if (lzf_decompress(c,clen,val,len) == 0) goto err;
zfree(c);
// 创建字符串对象并返回之
return createObject(REDIS_STRING,val);
err:
// 操作失败后的清理操作
zfree(c);
sdsfree(val);
return NULL;
}
/* Save a string object as [len][data] on disk. If the object is a string
* representation of an integer value we try to save it in a special form */
/* 以[len][data]的形式将字符串对象写入RDB中。如果该对象是字符串形式表示的整型数,则尝试用特殊的形式保存它。
操作成功后该函数返回保存字符串所需的字节数。*/
int rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) {
int enclen;
int n, nwritten = 0;
/* Try integer encoding */
// 尝试进行整型编码
if (len <= 11) {
unsigned char buf[5];
// rdbTryIntegerEncoding函数负责进行整型编码,如果操作成功返回值 > 0
if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
// 整型编码成功,写入RDB中
if (rdbWriteRaw(rdb,buf,enclen) == -1) return -1;
return enclen;
}
}
/* Try LZF compression - under 20 bytes it's unable to compress even
* aaaaaaaaaaaaaaaaaa so skip it */
// 如果服务器开启了lzf压缩功能并且待写入字符串长度超过20字节,则先进行lzf压缩后再写入RDB中
if (server.rdb_compression && len > 20) {
n = rdbSaveLzfStringObject(rdb,s,len);
if (n == -1) return -1;
if (n > 0) return n;
/* Return value of 0 means data can't be compressed, save the old way */
// rdbSaveLzfStringObject的返回值为0表明无法压缩,程序继续往下运行
}
/* Store verbatim */
// 经过上面的尝试,判断出输入字符串s既不能进行整型编码,也不能进行lzf压缩,直接写入RDB中
// 先写入字符串长度
if ((n = rdbSaveLen(rdb,len)) == -1) return -1;
// 记录写入字节数
nwritten += n;
// 写入原始字符串
if (len > 0) {
if (rdbWriteRaw(rdb,s,len) == -1) return -1;
// 记录写入字节数
nwritten += len;
}
return nwritten;
}
/* Save a long long value as either an encoded string or a string. */
/* 将long long类型的数值转换为一个编码字符串或一个普通字符串再写入RDB中。
该函数操作成功后返回写入的字节数,否则返回-1。*/
int rdbSaveLongLongAsStringObject(rio *rdb, long long value) {
unsigned char buf[32];
int n, nwritten = 0;
// 尝试进行整型编码以节省空间
int enclen = rdbEncodeInteger(value,buf);
// 整型编码成功,写入RDB中
if (enclen > 0) {
return rdbWriteRaw(rdb,buf,enclen);
}
// 整型编码失败,则将该数值转换为普通字符串来保存
else {
/* Encode as string */
// 将参数value转换为普通字符串表示
enclen = ll2string((char*)buf,32,value);
redisAssert(enclen < 32);
// 写入字符串长度
if ((n = rdbSaveLen(rdb,enclen)) == -1) return -1;
nwritten += n;
// 写入字符串本身
if ((n = rdbWriteRaw(rdb,buf,enclen)) == -1) return -1;
nwritten += n;
}
return nwritten;
}
/* Like rdbSaveStringObjectRaw() but handle encoded objects */
/* 将给定的字符串对象obj写入到RDB中。*/
int rdbSaveStringObject(rio *rdb, robj *obj) {
/* Avoid to decode the object, then encode it again, if the
* object is already integer encoded. */
// 如果该对象已经是REDIS_ENCODING_INT编码,直接写入
if (obj->encoding == REDIS_ENCODING_INT) {
return rdbSaveLongLongAsStringObject(rdb,(long)obj->ptr);
}
// 处理字符串编码的情况
else {
redisAssertWithInfo(NULL,obj,sdsEncodedObject(obj));
return rdbSaveRawString(rdb,obj->ptr,sdslen(obj->ptr));
}
}
/* 底层函数:从RDB中读取一个字符串对象并返回。参数encode不为0时指明所使用的编码方式。*/
robj *rdbGenericLoadStringObject(rio *rdb, int encode) {
int isencoded;
uint32_t len;
robj *o;
// 读取长度信息
len = rdbLoadLen(rdb,&isencoded);
if (isencoded) {
switch(len) {
// 整型编码
case REDIS_RDB_ENC_INT8:
case REDIS_RDB_ENC_INT16:
case REDIS_RDB_ENC_INT32:
return rdbLoadIntegerObject(rdb,len,encode);
// 使用lzf算法压缩后的字符串
case REDIS_RDB_ENC_LZF:
return rdbLoadLzfStringObject(rdb);
default:
redisPanic("Unknown RDB encoding type");
}
}
// 下面的代码处理非整型编码和非lzf压缩的情况
if (len == REDIS_RDB_LENERR) return NULL;
o = encode ? createStringObject(NULL,len) :
createRawStringObject(NULL,len);
// 直接读取原始字符串
if (len && rioRead(rdb,o->ptr,len) == 0) {
decrRefCount(o);
return NULL;
}
return o;
}
robj *rdbLoadStringObject(rio *rdb) {
return rdbGenericLoadStringObject(rdb,0);
}
robj *rdbLoadEncodedStringObject(rio *rdb) {
return rdbGenericLoadStringObject(rdb,1);
}
/* Save a double value. Doubles are saved as strings prefixed by an unsigned
* 8 bit integer specifying the length of the representation.
* This 8 bit integer has special values in order to specify the following
* conditions:
* 253: not a number
* 254: + inf
* 255: - inf
*/
/* 以字符串形式保存一个double数值,该字符串的前缀是一个8bit的无符号整型数,用以指明字符串double的长度信息。
其中有以下特殊值:
253:表示输入不是一个数值
254:表示输入的是正无穷
255:表示输入的是负无穷 */
int rdbSaveDoubleValue(rio *rdb, double val) {
unsigned char buf[128];
int len;
// not a number 不是一个数
if (isnan(val)) {
buf[0] = 253;
len = 1;
}
// 正无穷 or 负无穷
else if (!isfinite(val)) {
len = 1;
buf[0] = (val < 0) ? 255 : 254;
} else {
#if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
/* Check if the float is in a safe range to be casted into a
* long long. We are assuming that long long is 64 bit here.
* Also we are assuming that there are no implementations around where
* double has precision < 52 bit.
*
* Under this assumptions we test if a double is inside an interval
* where casting to long long is safe. Then using two castings we
* make sure the decimal part is zero. If all this is true we use
* integer printing function that is much faster. */
double min = -4503599627370495; /* (2^52)-1 */
double max = 4503599627370496; /* -(2^52) */
if (val > min && val < max && val == ((double)((long long)val)))
ll2string((char*)buf+1,sizeof(buf)-1,(long long)val);
else
#endif
// 转换为字符串表示,写入的起始位置为buf[1],buf[0]为长度信息
snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
buf[0] = strlen((char*)buf+1);
len = buf[0]+1;
}
// 将字符串写入RDB中
return rdbWriteRaw(rdb,buf,len);
}
/* For information about double serialization check rdbSaveDoubleValue() */
/* 从RDB中读取字符串表示的double数值并保存在指针val中。*/
int rdbLoadDoubleValue(rio *rdb, double *val) {
char buf[256];
unsigned char len;
// 读取字符串长度
if (rioRead(rdb,&len,1) == 0) return -1;
switch(len) {
// 读取特殊值:不是数 or 正无穷 or 负无穷
case 255: *val = R_NegInf; return 0;
case 254: *val = R_PosInf; return 0;
case 253: *val = R_Nan; return 0;
// 读取原始字符串
default:
if (rioRead(rdb,buf,len) == 0) return -1;
buf[len] = '\0';
// 将字符串转换为double数值
sscanf(buf, "%lg", val);
return 0;
}
}
/* Save the object type of object "o". */
/* 将对象o的类型信息写入RDB中,底层调用rdbSaveType函数实现。
操作成功返回写入的字节数,操作失败返回-1。*/
int rdbSaveObjectType(rio *rdb, robj *o) {
switch (o->type) {
case REDIS_STRING:
// REDIS_RDB_TYPE_STRING编码
return rdbSaveType(rdb,REDIS_RDB_TYPE_STRING);
case REDIS_LIST:
if (o->encoding == REDIS_ENCODING_ZIPLIST)
// REDIS_ENCODING_ZIPLIST编码的list
return rdbSaveType(rdb,REDIS_RDB_TYPE_LIST_ZIPLIST);
else if (o->encoding == REDIS_ENCODING_LINKEDLIST)
// REDIS_ENCODING_LINKEDLIST编码的list
return rdbSaveType(rdb,REDIS_RDB_TYPE_LIST);
else
redisPanic("Unknown list encoding");
case REDIS_SET:
if (o->encoding == REDIS_ENCODING_INTSET)
// REDIS_ENCODING_INTSET编码的set
return rdbSaveType(rdb,REDIS_RDB_TYPE_SET_INTSET);
else if (o->encoding == REDIS_ENCODING_HT)
// REDIS_ENCODING_HT编码的set
return rdbSaveType(rdb,REDIS_RDB_TYPE_SET);
else
redisPanic("Unknown set encoding");
case REDIS_ZSET:
if (o->encoding == REDIS_ENCODING_ZIPLIST)
// REDIS_ENCODING_ZIPLIST编码的zset
return rdbSaveType(rdb,REDIS_RDB_TYPE_ZSET_ZIPLIST);
else if (o->encoding == REDIS_ENCODING_SKIPLIST)
// REDIS_ENCODING_SKIPLIST编码的zset
return rdbSaveType(rdb,REDIS_RDB_TYPE_ZSET);
else
redisPanic("Unknown sorted set encoding");
case REDIS_HASH:
if (o->encoding == REDIS_ENCODING_ZIPLIST)
// REDIS_ENCODING_ZIPLIST编码的hash
return rdbSaveType(rdb,REDIS_RDB_TYPE_HASH_ZIPLIST);
else if (o->encoding == REDIS_ENCODING_HT)
// REDIS_ENCODING_HT编码的hash
return rdbSaveType(rdb,REDIS_RDB_TYPE_HASH);
else
redisPanic("Unknown hash encoding");
default:
redisPanic("Unknown object type");
}
return -1; /* avoid warning */
}
/* Use rdbLoadType() to load a TYPE in RDB format, but returns -1 if the
* type is not specifically a valid Object Type. */
/* 该函数使用rdbLoadType函数从RDB中读取类型信息并返回,如果该类型并不是一个合法的
Redis对象类型则返回-1。*/
int rdbLoadObjectType(rio *rdb) {
int type;
if ((type = rdbLoadType(rdb)) == -1) return -1;
if (!rdbIsObjectType(type)) return -1;
return type;
}
/* Save a Redis object. Returns -1 on error, number of bytes written on success. */
/* 将给定的Redis对象o写入RDB中。
该函数操作成功返回写入的字节数,操作失败返回-1。*/
int rdbSaveObject(rio *rdb, robj *o) {
int n, nwritten = 0;
// 处理REDIS_STRING类型对象
if (o->type == REDIS_STRING) {
/* Save a string value */
// 保存字符串值
if ((n = rdbSaveStringObject(rdb,o)) == -1) return -1;
// 记录写入字节数
nwritten += n;
}
// 处理REDIS_LIST类型对象
else if (o->type == REDIS_LIST) {
/* Save a list value */
// 处理REDIS_ENCODING_ZIPLIST编码的list
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
// 获取ziplist占用的空间大小
size_t l = ziplistBlobLen((unsigned char*)o->ptr);
// ziplist本身就是一个字符数组,这里以字符串的形式保存整个ziplist
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
}
// 处理REDIS_ENCODING_LINKEDLIST编码的list
else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
list *list = o->ptr;
listIter li;
listNode *ln;
// 写入长度信息(节点个数)
if ((n = rdbSaveLen(rdb,listLength(list))) == -1) return -1;
nwritten += n;
listRewind(list,&li);
// 遍历list中的每一项
while((ln = listNext(&li))) {
// 获取当前节点中的保存的数据内容
robj *eleobj = listNodeValue(ln);
// 以字符串的形式保存当前节点的内容
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
nwritten += n;
}
} else {
redisPanic("Unknown list encoding");
}
}
// 处理REDIS_SET类型对象
else if (o->type == REDIS_SET) {
/* Save a set value */
// 处理REDIS_ENCODING_HT编码的set
if (o->encoding == REDIS_ENCODING_HT) {
dict *set = o->ptr;
dictIterator *di = dictGetIterator(set);
dictEntry *de;
// 写入长度信息
if ((n = rdbSaveLen(rdb,dictSize(set))) == -1) return -1;
nwritten += n;
// 遍历字典dict的每个成员
while((de = dictNext(di)) != NULL) {
// 获取当前节点的key值
robj *eleobj = dictGetKey(de);
// 以字符串的形式保存当前节点的key
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
nwritten += n;
}
dictReleaseIterator(di);
}
// 处理REDIS_ENCODING_INTSET编码的set
else if (o->encoding == REDIS_ENCODING_INTSET) {
// 计算inset所占用空间大小
size_t l = intsetBlobLen((intset*)o->ptr);
// inset本身是一个字符数组,这里以字符串的形式保存整个inset
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
} else {
redisPanic("Unknown set encoding");
}
}
// 处理REDIS_ZSET类型对象
else if (o->type == REDIS_ZSET) {
/* Save a sorted set value */
// 处理REDIS_ENCODING_ZIPLIST编码的zset
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
// 计算ziplist所占用空间大小
size_t l = ziplistBlobLen((unsigned char*)o->ptr);
// ziplist本身是一个字符数组,这里以字符串的形式保存整个ziplist
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
}
// 处理REDIS_ENCODING_SKIPLIST编码的zset
else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
zset *zs = o->ptr;
dictIterator *di = dictGetIterator(zs->dict);
dictEntry *de;
// 保存字典dict的节点个数
if ((n = rdbSaveLen(rdb,dictSize(zs->dict))) == -1) return -1;
nwritten += n;
// 遍历字典dict的每一个节点
while((de = dictNext(di)) != NULL) {
// 获取当前节点(键值对)的key值
robj *eleobj = dictGetKey(de);
// 获取分值score值
double *score = dictGetVal(de);
// 以字符串的形式保存key值
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
nwritten += n;
// 保存分值score
if ((n = rdbSaveDoubleValue(rdb,*score)) == -1) return -1;
nwritten += n;
}
// 释放迭代器
dictReleaseIterator(di);
} else {
redisPanic("Unknown sorted set encoding");
}
}
// 处理REDIS_HASH类型对象
else if (o->type == REDIS_HASH) {
/* Save a hash value */
// 处理REDIS_ENCODING_ZIPLIST编码的hash
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
// 计算ziplist所占用空间大小
size_t l = ziplistBlobLen((unsigned char*)o->ptr);
// ziplist本身是一个字符数组,这里以字符串的形式保存整个ziplist
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
}
// 处理REDIS_ENCODING_HT编码的hash
else if (o->encoding == REDIS_ENCODING_HT) {
dictIterator *di = dictGetIterator(o->ptr);
dictEntry *de;
// 保存字典dict的节点个数
if ((n = rdbSaveLen(rdb,dictSize((dict*)o->ptr))) == -1) return -1;
nwritten += n;
// 遍历字典dict的每一个节点
while((de = dictNext(di)) != NULL) {
// 获取当前节点(键值对)的key值和value值
robj *key = dictGetKey(de);
robj *val = dictGetVal(de);
// 以字符串的形式保存key值和value值
if ((n = rdbSaveStringObject(rdb,key)) == -1) return -1;
nwritten += n;
if ((n = rdbSaveStringObject(rdb,val)) == -1) return -1;
nwritten += n;
}
dictReleaseIterator(di);
} else {
redisPanic("Unknown hash encoding");
}
} else {
redisPanic("Unknown object type");
}
return nwritten;
}
/* Return the length the object will have on disk if saved with
* the rdbSaveObject() function. Currently we use a trick to get
* this length with very little changes to the code. In the future
* we could switch to a faster solution. */
/* 返回对象o保存在RDB中所占用的字节长度。*/
off_t rdbSavedObjectLen(robj *o) {
int len = rdbSaveObject(NULL,o);
redisAssertWithInfo(NULL,o,len != -1);
return len;
}
/* Save a key-value pair, with expire time, type, key, value.
* On error -1 is returned.
* On success if the key was actually saved 1 is returned, otherwise 0
* is returned (the key was already expired). */
/* 将键值对相关的键、值、过期时间、类型信息写入RDB中。
如果操作失败返回-1。
如果操作成功则返回1。
如果该key已经过期则返回0。*/
int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val,
long long expiretime, long long now)
{
/* Save the expire time */
// 保存key的过期时间
if (expiretime != -1) {
/* If this key is already expired skip it */
// 如果该key已经过期,直接返回
if (expiretime < now) return 0;
// 保存类型信息
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_EXPIRETIME_MS) == -1) return -1;
/// 保存过期时间
if (rdbSaveMillisecondTime(rdb,expiretime) == -1) return -1;
}
/* Save type, key, value */
// 分别保存类型、key、value值信息
if (rdbSaveObjectType(rdb,val) == -1) return -1;
if (rdbSaveStringObject(rdb,key) == -1) return -1;
if (rdbSaveObject(rdb,val) == -1) return -1;
return 1;
}
/* Produces a dump of the database in RDB format sending it to the specified
* Redis I/O channel. On success REDIS_OK is returned, otherwise REDIS_ERR
* is returned and part of the output, or all the output, can be
* missing because of I/O errors.
*
* When the function returns REDIS_ERR and if 'error' is not NULL, the
* integer pointed by 'error' is set to the value of errno just after the I/O
* error. */
/* 将Redis数据库中的数据以RDB格式保存,该RDB文件以后将会发送到指定的Redis I/O通道。
如果保存成功函数返回REDIS_OK,如果保存失败则返回REDIS_ERR。*/
int rdbSaveRio(rio *rdb, int *error) {
dictIterator *di = NULL;
dictEntry *de;
char magic[10];
int j;
long long now = mstime();
uint64_t cksum;
// 设置校验和函数,rioGenericUpdateChecksum定义在rio.h文件中
if (server.rdb_checksum)
rdb->update_cksum = rioGenericUpdateChecksum;
// 生成RDB文件版本号
snprintf(magic,sizeof(magic),"REDIS%04d",REDIS_RDB_VERSION);
// 写入RDB版本号
if (rdbWriteRaw(rdb,magic,9) == -1) goto werr;
// 遍历Redis服务器上的所有数据库
for (j = 0; j < server.dbnum; j++) {
// 获取当前数据库
redisDb *db = server.db+j;
// 获取当前数据库的键空间key space
dict *d = db->dict;
// 如果当前数据库为空,跳过
if (dictSize(d) == 0) continue;
di = dictGetSafeIterator(d);
if (!di) return REDIS_ERR;
/* Write the SELECT DB opcode */
// 写入数据库DB的编号,即 j
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_SELECTDB) == -1) goto werr;
if (rdbSaveLen(rdb,j) == -1) goto werr;
/* Iterate this DB writing every entry */
// 遍历键空间中的每一项,并写入RDB中
while((de = dictNext(di)) != NULL) {
// 获取key和value
sds keystr = dictGetKey(de);
robj key, *o = dictGetVal(de);
long long expire;
// 创建一个key对象
initStaticStringObject(key,keystr);
// 获取key的过期信息
expire = getExpire(db,&key);
// 保存当前键值对
if (rdbSaveKeyValuePair(rdb,&key,o,expire,now) == -1) goto werr;
}
dictReleaseIterator(di);
}
di = NULL; /* So that we don't release it again on error. */
/* EOF opcode */
// 写入EOF符
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_EOF) == -1) goto werr;
/* CRC64 checksum. It will be zero if checksum computation is disabled, the
* loading code skips the check in this case. */
// CRC64校验和,如果Redis校验和功能被关闭则cksum的值为0。在这种情况下当Redis载入RDB时会
// 跳过该校验和的检查
cksum = rdb->cksum;
memrev64ifbe(&cksum);
// 写入校验和
if (rioWrite(rdb,&cksum,8) == 0) goto werr;
return REDIS_OK;
werr:
if (error) *error = errno;
if (di) dictReleaseIterator(di);
return REDIS_ERR;
}
/* This is just a wrapper to rdbSaveRio() that additionally adds a prefix
* and a suffix to the generated RDB dump. The prefix is:
*
* $EOF:<40 bytes unguessable hex string>\r\n
*
* While the suffix is the 40 bytes hex string we announced in the prefix.
* This way processes receiving the payload can understand when it ends
* without doing any processing of the content. */
/* 该函数是rdbSaveRio()的包装,只是额外地往RDB文件中添加了前缀和后缀。
前缀为:
$EOF:<40 bytes unguessable hex string>\r\n
后缀为前缀中的“<40 bytes unguessable hex string>”部分。
这种方式可以在不改变RDB原始内容的前提下让接受进程知道结束位置
*/
int rdbSaveRioWithEOFMark(rio *rdb, int *error) {
char eofmark[REDIS_EOF_MARK_SIZE];
getRandomHexChars(eofmark,REDIS_EOF_MARK_SIZE);
if (error) *error = 0;
if (rioWrite(rdb,"$EOF:",5) == 0) goto werr;
if (rioWrite(rdb,eofmark,REDIS_EOF_MARK_SIZE) == 0) goto werr;
if (rioWrite(rdb,"\r\n",2) == 0) goto werr;
if (rdbSaveRio(rdb,error) == REDIS_ERR) goto werr;
if (rioWrite(rdb,eofmark,REDIS_EOF_MARK_SIZE) == 0) goto werr;
return REDIS_OK;
werr: /* Write error. */
/* Set 'error' only if not already set by rdbSaveRio() call. */
if (error && *error == 0) *error = errno;
return REDIS_ERR;
}
/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success. */
/* save命令的底层函数。将Redis数据库db保存到磁盘中,如果操作成功函数返回REDIS_OK,如果操作失败函数返回REDIS_ERR。*/
int rdbSave(char *filename) {
char tmpfile[256];
FILE *fp;
rio rdb;
int error;
// 生成临时文件名称
snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
// 创建临时文件
fp = fopen(tmpfile,"w");
if (!fp) {
redisLog(REDIS_WARNING, "Failed opening .rdb for saving: %s",
strerror(errno));
return REDIS_ERR;
}
// 初始化file rio对象
rioInitWithFile(&rdb,fp);
// 调用rdbSaveRio将db中的数据写入RDB文件中
if (rdbSaveRio(&rdb,&error) == REDIS_ERR) {
errno = error;
goto werr;
}
/* Make sure data will not remain on the OS's output buffers */
// flush操作,确保所有数据都写入RDB文件中
if (fflush(fp) == EOF) goto werr;
if (fsync(fileno(fp)) == -1) goto werr;
if (fclose(fp) == EOF) goto werr;
/* Use RENAME to make sure the DB file is changed atomically only
* if the generate DB file is ok. */
// 重命名临时文件
if (rename(tmpfile,filename) == -1) {
// 如果操作失败,删除临时文件
redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
unlink(tmpfile);
return REDIS_ERR;
}
redisLog(REDIS_NOTICE,"DB saved on disk");
server.dirty = 0;
server.lastsave = time(NULL);
server.lastbgsave_status = REDIS_OK;
return REDIS_OK;
werr:
// 发生错误清理资源
redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
fclose(fp);
unlink(tmpfile);
return REDIS_ERR;
}