forked from menwenjun/redis_source_annotation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rdb.c
2228 lines (2014 loc) · 89.4 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 "server.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>
#include <sys/param.h>
#define RDB_LOAD_NONE 0 //不编码,从rio读出
#define RDB_LOAD_ENC (1<<0)
#define RDB_LOAD_PLAIN (1<<1)
#define rdbExitReportCorruptRDB(...) rdbCheckThenExit(__LINE__,__VA_ARGS__)
extern int rdbCheckMode; //在redis-check-rdb文件的一个标志,初始化为0
void rdbCheckError(const char *fmt, ...);
void rdbCheckSetError(const char *fmt, ...);
//检查rdb错误发送信息且退出
void rdbCheckThenExit(int linenum, char *reason, ...) {
va_list ap; // 可变参的宏va_list
char msg[1024];
int len;
// 将错误信息写到msg缓冲区中
len = snprintf(msg,sizeof(msg),
"Internal error in RDB reading function at rdb.c:%d -> ", linenum);
// 用reason初始化ap
va_start(ap,reason);
// 将ap指向的参数写到len长度的后面
vsnprintf(msg+len,sizeof(msg)-len,reason,ap);
// 结束关闭
va_end(ap);
//发送错误信息
if (!rdbCheckMode) {
serverLog(LL_WARNING, "%s", msg);
char *argv[2] = {"",server.rdb_filename};
redis_check_rdb_main(2,argv);
} else {
rdbCheckError("%s",msg);
}
exit(1);
}
// 将长度为len的数组p写到rdb中,返回写的长度
static int rdbWriteRaw(rio *rdb, void *p, size_t len) {
if (rdb && rioWrite(rdb,p,len) == 0)
return -1;
return len;
}
// 将长度为1的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中载入1字节的数据保存在type中,并返回其type
int rdbLoadType(rio *rdb) {
unsigned char type;
if (rioRead(rdb,&type,1) == 0) return -1;
return type;
}
// 从rio读出一个时间,单位为秒,长度为4字节
time_t rdbLoadTime(rio *rdb) {
int32_t t32;
if (rioRead(rdb,&t32,4) == 0) return -1;
return (time_t)t32;
}
// 写一个longlong类型的时间,单位为毫秒
int rdbSaveMillisecondTime(rio *rdb, long long t) {
int64_t t64 = (int64_t) t;
return rdbWriteRaw(rdb,&t64,8);
}
// 从rio中读出一个毫秒时间返回
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 RDB_* definitions for more information
* on the types of encoding. */
// 将一个被编码的长度写入到rio中,返回保存编码后的len需要的字节数
int rdbSaveLen(rio *rdb, uint32_t len) {
unsigned char buf[2];
size_t nwritten;
// 长度小于2^6
if (len < (1<<6)) {
/* Save a 6 bit len */
// 高两位是00表示6位长,第六位表示len的值
buf[0] = (len&0xFF)|(RDB_6BITLEN<<6);
// 将buf[0]写到rio中
if (rdbWriteRaw(rdb,buf,1) == -1) return -1;
nwritten = 1; //1字节
// 长度小于2^14
} else if (len < (1<<14)) {
/* Save a 14 bit len */
// 高两位是01表示14位长,剩下的14位表示len的值
buf[0] = ((len>>8)&0xFF)|(RDB_14BITLEN<<6);
buf[1] = len&0xFF;
// 讲buf[0..1]写到rio中
if (rdbWriteRaw(rdb,buf,2) == -1) return -1;
nwritten = 2; //2字节
// 长度大于2^14
} else {
/* Save a 32 bit len */
// 高两位为10表示32位长,剩下的6位不使用
buf[0] = (RDB_32BITLEN<<6);
// 将buf[0]写入
if (rdbWriteRaw(rdb,buf,1) == -1) return -1;
len = htonl(len); //将len转换为网络序,写入rdb中
if (rdbWriteRaw(rdb,&len,4) == -1) return -1;
nwritten = 1+4; //5个字节
}
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 RDB_ENC_*
* definitions in rdb.h for more information. */
// 返回一个从rio读出的len值,如果该len值不是整数,而是被编码后的值,那么将isencoded设置为1
uint32_t rdbLoadLen(rio *rdb, int *isencoded) {
unsigned char buf[2];
uint32_t len;
int type;
// 默认为没有编码
if (isencoded) *isencoded = 0;
// 将rio中的值读到buf中
if (rioRead(rdb,buf,1) == 0) return RDB_LENERR;
// (buf[0]&0xC0)>>6 = (1100 000 & buf[0]) >> 6 = buf[0]的最高两位
type = (buf[0]&0xC0)>>6;
// 一个编码过的值,返回解码值,设置编码标志
if (type == RDB_ENCVAL) {
/* Read a 6 bit encoding type. */
if (isencoded) *isencoded = 1;
return buf[0]&0x3F; //取出剩下六位表示的长度值
// 一个6位长的值
} else if (type == RDB_6BITLEN) {
/* Read a 6 bit len. */
return buf[0]&0x3F; //取出剩下六位表示的长度值
// 一个14位长的值
} else if (type == RDB_14BITLEN) {
/* Read a 14 bit len. */
// 从buf+1读出1个字节的值
if (rioRead(rdb,buf+1,1) == 0) return RDB_LENERR;
return ((buf[0]&0x3F)<<8)|buf[1]; //取出除最高两位的长度值
// 一个32位长的值
} else if (type == RDB_32BITLEN) {
/* Read a 32 bit len. */
// 读出4个字节的值
if (rioRead(rdb,&len,4) == 0) return RDB_LENERR;
return ntohl(len); //转换为主机序的值
} else {
rdbExitReportCorruptRDB(
"Unknown length encoding %d in rdbLoadLen()",type);
return -1; /* Never reached. */
}
}
/* 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. */
// 将longlong类型的value编码成一个整数编码,如果可以编码,将编码后的值保存在enc中,返回编码后的字节数
int rdbEncodeInteger(long long value, unsigned char *enc) {
// -2^8 <= value <= 2^8-1
// 最高两位设置为 11,表示是一个编码过的值,低6位为 000000 ,表示是 RDB_ENC_INT8 编码格式
// 剩下的1个字节保存value,返回2字节
if (value >= -(1<<7) && value <= (1<<7)-1) {
enc[0] = (RDB_ENCVAL<<6)|RDB_ENC_INT8;
enc[1] = value&0xFF;
return 2;
// -2^16 <= value <= 2^16-1
// 最高两位设置为 11,表示是一个编码过的值,低6位为 000001 ,表示是 RDB_ENC_INT16 编码格式
// 剩下的2个字节保存value,返回3字节
} else if (value >= -(1<<15) && value <= (1<<15)-1) {
enc[0] = (RDB_ENCVAL<<6)|RDB_ENC_INT16;
enc[1] = value&0xFF;
enc[2] = (value>>8)&0xFF;
return 3;
// -2^32 <= value <= 2^32-1
// 最高两位设置为 11,表示是一个编码过的值,低6位为 000010 ,表示是 RDB_ENC_INT32 编码格式
// 剩下的4个字节保存value,返回5字节
} else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
enc[0] = (RDB_ENCVAL<<6)|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".
* The returned value changes according to the flags, see
* rdbGenerincLoadStringObject() for more info. */
// 将rio中的整数值根据不同的编码读出来,并根据flags构建成一个不同类型的值并返回
void *rdbLoadIntegerObject(rio *rdb, int enctype, int flags) {
int plain = flags & RDB_LOAD_PLAIN; //无格式
int encode = flags & RDB_LOAD_ENC; //字符串对象
unsigned char enc[4];
long long val;
// 根据不同的整数编码类型,从rio中读出整数值到enc中
if (enctype == RDB_ENC_INT8) {
if (rioRead(rdb,enc,1) == 0) return NULL;
val = (signed char)enc[0];
} else if (enctype == RDB_ENC_INT16) {
uint16_t v;
if (rioRead(rdb,enc,2) == 0) return NULL;
v = enc[0]|(enc[1]<<8);
val = (int16_t)v;
} else if (enctype == 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 */
rdbExitReportCorruptRDB("Unknown RDB integer encoding type %d",enctype);
}
// 如果是整数,转换为字符串类型返回
if (plain) {
char buf[LONG_STR_SIZE], *p;
int len = ll2string(buf,sizeof(buf),val);
p = zmalloc(len);
memcpy(p,buf,len);
return p;
// 如果是编码过的整数值,则转换为字符串对象,返回
} else if (encode) {
return createStringObjectFromLongLong(val);
} else {
// 返回一个字符串对象
return createObject(OBJ_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 */
// 将一些纯数字的字符串尝试转换为可以编码的整数,以节省内存
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 */
// 尝试将字符串值转换为整数
value = strtoll(s, &endptr, 10);
// 字符串不是纯数字的返回0
if (endptr[0] != '\0') return 0;
// 将value转回字符串类型
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;
// 可以编码则转换成整数,将编码类型保存enc中
return rdbEncodeInteger(value,enc);
}
// 将讲一个LZF压缩过的字符串的信息写入rio,返回写入的字节数
ssize_t rdbSaveLzfBlob(rio *rdb, void *data, size_t compress_len,
size_t original_len) {
unsigned char byte;
ssize_t n, nwritten = 0;
/* Data compressed! Let's save it on disk */
// 将1100 0011保存在byte中,表示编码过,是一个LZF压缩的字符串
byte = (RDB_ENCVAL<<6)|RDB_ENC_LZF;
// 将byte写入rio中
if ((n = rdbWriteRaw(rdb,&byte,1)) == -1) goto writeerr;
nwritten += n;
// 将压缩后的长度值compress_len写入rio
if ((n = rdbSaveLen(rdb,compress_len)) == -1) goto writeerr;
nwritten += n;
// 将压缩前的长度值original_len写入rio
if ((n = rdbSaveLen(rdb,original_len)) == -1) goto writeerr;
nwritten += n;
// 将压缩的字符串值data写入rio
if ((n = rdbWriteRaw(rdb,data,compress_len)) == -1) goto writeerr;
nwritten += n;
return nwritten; //返回写入的字节数
writeerr:
return -1;
}
ssize_t rdbSaveLzfStringObject(rio *rdb, unsigned char *s, size_t len) {
size_t comprlen, outlen;
void *out;
/* We require at least four bytes compression for this to be worth it */
if (len <= 4) return 0;
outlen = len-4;
if ((out = zmalloc(outlen+1)) == NULL) return 0;
comprlen = lzf_compress(s, len, out, outlen);
if (comprlen == 0) {
zfree(out);
return 0;
}
ssize_t nwritten = rdbSaveLzfBlob(rdb, out, comprlen, len);
zfree(out);
return nwritten;
}
/* Load an LZF compressed string in RDB format. The returned value
* changes according to 'flags'. For more info check the
* rdbGenericLoadStringObject() function. */
// 从rio中读出一个压缩过的字符串,将其解压并返回构建成的字符串对象
void *rdbLoadLzfStringObject(rio *rdb, int flags) {
int plain = flags & RDB_LOAD_PLAIN; //无格式的,没有编码过
unsigned int len, clen;
unsigned char *c = NULL;
sds val = NULL;
// 读出clen值,表示压缩的长度
if ((clen = rdbLoadLen(rdb,NULL)) == RDB_LENERR) return NULL;
// 读出len值,表示未压缩的长度
if ((len = rdbLoadLen(rdb,NULL)) == RDB_LENERR) return NULL;
// 分配一个clen长度的空间
if ((c = zmalloc(clen)) == NULL) goto err;
/* Allocate our target according to the uncompressed size. */
// 如果是一个未编码过的值
if (plain) {
val = zmalloc(len); //分配一个未编码值的空间
} else {
// 否则分配一个字符串空间
if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
}
/* Load the compressed representation and uncompress it to target. */
// 从rio中读出压缩过的值
if (rioRead(rdb,c,clen) == 0) goto err;
// 将压缩过的值解压缩,保存在val中,解压后的长度为len
if (lzf_decompress(c,clen,val,len) == 0) {
if (rdbCheckMode) rdbCheckSetError("Invalid LZF compressed string");
goto err;
}
zfree(c); //释放空间
if (plain)
return val; //返回原值
else
return createObject(OBJ_STRING,val); //返回字一个字符串对象
err:
zfree(c);
if (plain)
zfree(val);
else
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 */
// 将一个原生的字符串值写入到rio
ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) {
int enclen;
ssize_t n, nwritten = 0;
/* Try integer encoding */
// 如果字符串可以进行整数编码
if (len <= 11) {
unsigned char buf[5];
if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
// 将编码后的字符串写入rio,返回编码所需的字节数
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 */
// 如果开启了rdb压缩的设置,且字符串长度大于20,进行LZF压缩字符串
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 */
}
/* Store verbatim */
// 字符串既不能被压缩,也不能编码成整数
// 因此直接写入rio中
// 写入长度
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. */
// 将 longlong类型的value转换为字符串对象,并且进行编码,然后写到rio中
ssize_t rdbSaveLongLongAsStringObject(rio *rdb, long long value) {
unsigned char buf[32];
ssize_t n, nwritten = 0;
// 将longlong类型value进行整数编码并将值写到buf中,节约内存
int enclen = rdbEncodeInteger(value,buf);
// 如果可以进行整数编码
if (enclen > 0) {
// 将整数编码后的longlong值写到rio中
return rdbWriteRaw(rdb,buf,enclen);
// 不能进行整数编码
} else {
/* Encode as string */
// 转换为字符串
enclen = ll2string((char*)buf,32,value);
serverAssert(enclen < 32);
// 将字符串长度写入rio中
if ((n = rdbSaveLen(rdb,enclen)) == -1) return -1;
nwritten += n;
// 将字符串写入rio中
if ((n = rdbWriteRaw(rdb,buf,enclen)) == -1) return -1;
nwritten += n;
}
return nwritten; //发送写入的长度
}
/* Like rdbSaveStringObjectRaw() but handle encoded objects */
// 将字符串对象obj写到rio中
int rdbSaveStringObject(rio *rdb, robj *obj) {
/* Avoid to decode the object, then encode it again, if the
* object is already integer encoded. */
// 如果是int编码的是字符串对象
if (obj->encoding == OBJ_ENCODING_INT) {
// 讲对象值进行编码后发送给rio
return rdbSaveLongLongAsStringObject(rdb,(long)obj->ptr);
// RAW或EMBSTR编码类型的字符串对象
} else {
serverAssertWithInfo(NULL,obj,sdsEncodedObject(obj));
// 将字符串类型的对象写到rio
return rdbSaveRawString(rdb,obj->ptr,sdslen(obj->ptr));
}
}
/* Load a string object from an RDB file according to flags:
*
* RDB_LOAD_NONE (no flags): load an RDB object, unencoded.
* RDB_LOAD_ENC: If the returned type is a Redis object, try to
* encode it in a special way to be more memory
* efficient. When this flag is passed the function
* no longer guarantees that obj->ptr is an SDS string.
* RDB_LOAD_PLAIN: Return a plain string allocated with zmalloc()
* instead of a Redis object with an sds in it.
* RDB_LOAD_SDS: Return an SDS string instead of a Redis object.
*/
//RDB_LOAD_NONE:读一个rio,不编码
//
// 根据flags,将从rio读出一个字符串对象进行编码
void *rdbGenericLoadStringObject(rio *rdb, int flags) {
int encode = flags & RDB_LOAD_ENC; //编码
int plain = flags & RDB_LOAD_PLAIN; //原生的值
int isencoded;
uint32_t len;
// 从rio中读出一个字符串对象,编码类型保存在isencoded中,所需的字节为len
len = rdbLoadLen(rdb,&isencoded);
// 如果读出的对象被编码(isencoded被设置为1),则根据不同的长度值len映射到不同的整数编码
if (isencoded) {
switch(len) {
case RDB_ENC_INT8:
case RDB_ENC_INT16:
case RDB_ENC_INT32:
// 以上三种类型的整数编码,根据flags返回不同类型值
return rdbLoadIntegerObject(rdb,len,flags);
case RDB_ENC_LZF:
// 如果是压缩后的字符串,进行构建压缩字符串编码对象
return rdbLoadLzfStringObject(rdb,flags);
default:
rdbExitReportCorruptRDB("Unknown RDB string encoding type %d",len);
}
}
// 如果len值错误,则返回NULL
if (len == RDB_LENERR) return NULL;
// 如果不是原生值
if (!plain) {
// 根据encode编码类型创建不同的字符串对象
robj *o = encode ? createStringObject(NULL,len) :
createRawStringObject(NULL,len);
// 设置o对象的值,从rio中读出来,如果失败,释放对象返回NULL
if (len && rioRead(rdb,o->ptr,len) == 0) {
decrRefCount(o);
return NULL;
}
return o;
// 如果设置了原生值
} else {
// 分配空间
void *buf = zmalloc(len);
// 从rio中读出来
if (len && rioRead(rdb,buf,len) == 0) {
zfree(buf);
return NULL;
}
return buf; //返回
}
}
// 从rio中读出一个字符串编码的对象
robj *rdbLoadStringObject(rio *rdb) {
return rdbGenericLoadStringObject(rdb,RDB_LOAD_NONE);
}
// 从rio中读出一个字符串编码的对象,对象使用不同类型的编码
robj *rdbLoadEncodedStringObject(rio *rdb) {
return rdbGenericLoadStringObject(rdb,RDB_LOAD_ENC);
}
/* 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类型的字符串值,字符串前是一个8位长的无符号整数,它表示浮点数的长度
// 八位整数中的值表示一些特殊情况,
// 253:表示不是数字
// 254:表示正无穷
// 255:表示负无穷
int rdbSaveDoubleValue(rio *rdb, double val) {
unsigned char buf[128];
int len;
// 如果val不是一个数字,则写入253
if (isnan(val)) {
buf[0] = 253;
len = 1;
// 如果val不是一个有限的值,根据正负性,写入255或254
} else if (!isfinite(val)) {
len = 1;
buf[0] = (val < 0) ? 255 : 254;
// 如果不是上面的两种情况,则表示val是一个double类型的数
} else {
// 64位系统中
// DBL_MANT_DIG:表示尾数中的位数为53
// LLONG_MAX:longlong表示的最大数为0x7fffffffffffffffLL
#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类型的最大值和最小值
double min = -4503599627370495; /* (2^52)-1 */
double max = 4503599627370496; /* -(2^52) */
// 如果val在double表示的范围内,且val值是安全的,没有小数
if (val > min && val < max && val == ((double)((long long)val)))
// 将val转换为字符串,添加到8位长度值的后面
ll2string((char*)buf+1,sizeof(buf)-1,(long long)val);
else
#endif
// 以宽度为17位的方式写到8位长度值的后面,17位的double双精度浮点数的长度最短且无损
snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
buf[0] = strlen((char*)buf+1); //将刚才加入buf+1的字符串值的长度写到前8位的长度值中
len = buf[0]+1; //总字节数
}
// 将buf中的字符串原生的写到rio中
return rdbWriteRaw(rdb,buf,len);
}
/* For information about double serialization check rdbSaveDoubleValue() */
// 读出字符串表示的double值
int rdbLoadDoubleValue(rio *rdb, double *val) {
char buf[256];
unsigned char len;
// 从rio中读出一个字节的长度,保存在len中
if (rioRead(rdb,&len,1) == 0) return -1;
// Redis中,0,负无穷,正无穷,非数字分别如下表示,在redis.c中
// static double R_Zero, R_PosInf, R_NegInf, R_Nan;
// R_Zero = 0.0;
// R_PosInf = 1.0/R_Zero;
// R_NegInf = -1.0/R_Zero;
// R_Nan = R_Zero/R_Zero;
// 如果长度值为这三个特殊值,返回0
switch(len) {
case 255: *val = R_NegInf; return 0;
case 254: *val = R_PosInf; return 0;
case 253: *val = R_Nan; return 0;
// 否则从rio读出len长的字符串
default:
if (rioRead(rdb,buf,len) == 0) return -1;
buf[len] = '\0';
sscanf(buf, "%lg", val); //将buf值写到val中
return 0;
}
}
/* Save the object type of object "o". */
// 将对象o的类型写到rio中
int rdbSaveObjectType(rio *rdb, robj *o) {
// 根据不同数据类型,写入不同编码类型
switch (o->type) {
case OBJ_STRING: //字符串类型
return rdbSaveType(rdb,RDB_TYPE_STRING);
case OBJ_LIST: //列表类型
if (o->encoding == OBJ_ENCODING_QUICKLIST)
return rdbSaveType(rdb,RDB_TYPE_LIST_QUICKLIST);
else
serverPanic("Unknown list encoding");
case OBJ_SET: //集合类型
if (o->encoding == OBJ_ENCODING_INTSET)
return rdbSaveType(rdb,RDB_TYPE_SET_INTSET);
else if (o->encoding == OBJ_ENCODING_HT)
return rdbSaveType(rdb,RDB_TYPE_SET);
else
serverPanic("Unknown set encoding");
case OBJ_ZSET: //有序集合类型
if (o->encoding == OBJ_ENCODING_ZIPLIST)
return rdbSaveType(rdb,RDB_TYPE_ZSET_ZIPLIST);
else if (o->encoding == OBJ_ENCODING_SKIPLIST)
return rdbSaveType(rdb,RDB_TYPE_ZSET);
else
serverPanic("Unknown sorted set encoding");
case OBJ_HASH: //哈希类型
if (o->encoding == OBJ_ENCODING_ZIPLIST)
return rdbSaveType(rdb,RDB_TYPE_HASH_ZIPLIST);
else if (o->encoding == OBJ_ENCODING_HT)
return rdbSaveType(rdb,RDB_TYPE_HASH);
else
serverPanic("Unknown hash encoding");
default:
serverPanic("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. */
// 从rio中读出一个类型并返回
int rdbLoadObjectType(rio *rdb) {
int type;
// 从rio中读出类型保存在type中
if ((type = rdbLoadType(rdb)) == -1) return -1;
// 判断是否是一个rio规定的类型
if (!rdbIsObjectType(type)) return -1;
return type;
}
/* Save a Redis object. Returns -1 on error, number of bytes written on success. */
// 将一个对象写到rio中,出错返回-1,成功返回写的字节数
ssize_t rdbSaveObject(rio *rdb, robj *o) {
ssize_t n = 0, nwritten = 0;
// 保存字符串对象
if (o->type == OBJ_STRING) {
/* Save a string value */
if ((n = rdbSaveStringObject(rdb,o)) == -1) return -1;
nwritten += n;
// 保存一个列表对象
} else if (o->type == OBJ_LIST) {
/* Save a list value */
// 列表对象编码为quicklist
if (o->encoding == OBJ_ENCODING_QUICKLIST) {
quicklist *ql = o->ptr; //表头地址
quicklistNode *node = ql->head; //头节点地址
// 将quicklist的节点个数写入rio中
if ((n = rdbSaveLen(rdb,ql->len)) == -1) return -1;
nwritten += n; //更新写入的字节数
do {
// 如果当前节点可以被压缩
if (quicklistNodeIsCompressed(node)) {
void *data; //将节点的数据压缩到data中
size_t compress_len = quicklistGetLzf(node, &data);
// 将一个压缩过的字符串写到rio中
if ((n = rdbSaveLzfBlob(rdb,data,compress_len,node->sz)) == -1) return -1;
nwritten += n;
// 如果不能压缩
} else {
// 将一个原生的字符串写入到rio中
if ((n = rdbSaveRawString(rdb,node->zl,node->sz)) == -1) return -1;
nwritten += n;
}//遍历所有的quicklist节点
} while ((node = node->next));
} else {
serverPanic("Unknown list encoding");
}
// 保存一个集合对象
} else if (o->type == OBJ_SET) {
/* Save a set value */
// 集合对象是字典类型
if (o->encoding == OBJ_ENCODING_HT) {
dict *set = o->ptr;
dictIterator *di = dictGetIterator(set); //创建一个字典迭代器
dictEntry *de;
// 将成员的个数写入rio中
if ((n = rdbSaveLen(rdb,dictSize(set))) == -1) return -1;
nwritten += n;
// 遍历集合成员
while((de = dictNext(di)) != NULL) {
robj *eleobj = dictGetKey(de);
// 将当前节点保存的键对象写入rio中
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
nwritten += n;
}
dictReleaseIterator(di); //释放字典迭代器
// 集合对象是字intset类型
} else if (o->encoding == OBJ_ENCODING_INTSET) {
size_t l = intsetBlobLen((intset*)o->ptr); //获取intset所占的字节数
// 以一个原生字符串对象的方式将intset集合写到rio中
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
} else {
serverPanic("Unknown set encoding");
}
// 保存一个有序集合对象
} else if (o->type == OBJ_ZSET) {
/* Save a sorted set value */
// 有序集合对象是ziplist类型
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
size_t l = ziplistBlobLen((unsigned char*)o->ptr); //ziplist所占的字节数
// 以一个原生字符串对象保存ziplist类型的有序集合
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
// 有序集合对象是skiplist类型
} else if (o->encoding == OBJ_ENCODING_SKIPLIST) {
zset *zs = o->ptr;
dictIterator *di = dictGetIterator(zs->dict); //创建字典迭代器
dictEntry *de;
// 将有序集合的节点个数写入rio中
if ((n = rdbSaveLen(rdb,dictSize(zs->dict))) == -1) return -1;
nwritten += n;
// 遍历所有节点
while((de = dictNext(di)) != NULL) {
robj *eleobj = dictGetKey(de); //获取当前节点保存的键
double *score = dictGetVal(de); //键对应的值
// 以字符串对象的形式将键对象写到rio中
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
nwritten += n;
// 将double值转换为字符串对象,写到rio中
if ((n = rdbSaveDoubleValue(rdb,*score)) == -1) return -1;
nwritten += n;
}
dictReleaseIterator(di); //释放字典迭代器
} else {
serverPanic("Unknown sorted set encoding");
}
// 保存一个哈希对象
} else if (o->type == OBJ_HASH) {
/* Save a hash value */
// 哈希对象是ziplist类型的
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
size_t l = ziplistBlobLen((unsigned char*)o->ptr); //ziplist所占的字节数
// 以一个原生字符串对象保存ziplist类型的有序集合
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
nwritten += n;
// 哈希对象是字典类型的
} else if (o->encoding == OBJ_ENCODING_HT) {
dictIterator *di = dictGetIterator(o->ptr); //创建字典迭代器
dictEntry *de;
// 将哈希表的节点个数写入rio中
if ((n = rdbSaveLen(rdb,dictSize((dict*)o->ptr))) == -1) return -1;
nwritten += n;
// 遍历整个哈希表
while((de = dictNext(di)) != NULL) {
robj *key = dictGetKey(de); // 获取当前节点保存的键
robj *val = dictGetVal(de); // 键对应的值
// 以字符串对象的形式将键对象和值对象写到rio中
if ((n = rdbSaveStringObject(rdb,key)) == -1) return -1;
nwritten += n;
if ((n = rdbSaveStringObject(rdb,val)) == -1) return -1;
nwritten += n;
}
dictReleaseIterator(di);
} else {
serverPanic("Unknown hash encoding");
}
} else {
serverPanic("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. */
// 返回一个对象的长度,通过写入的方式
// 但是已经被放弃使用
size_t rdbSavedObjectLen(robj *o) {
ssize_t len = rdbSaveObject(NULL,o);
serverAssertWithInfo(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). */
// 将一个键对象,值对象,过期时间,和类型写入到rio中,出错返回-1,成功返回1,键过期返回0
int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val,
long long expiretime, long long now)
{
/* Save the expire time */
// 保存过期时间
if (expiretime != -1) {
/* If this key is already expired skip it */
// 判断键是否过期,过期则返回0
if (expiretime < now) return 0;
// 将一个毫秒的过期时间类型写入rio
if (rdbSaveType(rdb,RDB_OPCODE_EXPIRETIME_MS) == -1) return -1;
// 将过期时间写入rio
if (rdbSaveMillisecondTime(rdb,expiretime) == -1) return -1;
}
/* Save type, key, value */
// 将值对象的类型,键对象和值对象到rio中
if (rdbSaveObjectType(rdb,val) == -1) return -1;
if (rdbSaveStringObject(rdb,key) == -1) return -1;
if (rdbSaveObject(rdb,val) == -1) return -1;
return 1;
}
/* Save an AUX field. */
// 写入一个特殊的辅助操作码字段
int rdbSaveAuxField(rio *rdb, void *key, size_t keylen, void *val, size_t vallen) {
// RDB_OPCODE_AUX 对应的操作码是250
if (rdbSaveType(rdb,RDB_OPCODE_AUX) == -1) return -1;
// 写入键对象和值对象
if (rdbSaveRawString(rdb,key,keylen) == -1) return -1;
if (rdbSaveRawString(rdb,val,vallen) == -1) return -1;
return 1;
}
/* Wrapper for rdbSaveAuxField() used when key/val length can be obtained
* with strlen(). */
// rdbSaveAuxField()的封装,适用于key和val是c语言字符串类型
int rdbSaveAuxFieldStrStr(rio *rdb, char *key, char *val) {
return rdbSaveAuxField(rdb,key,strlen(key),val,strlen(val));
}
/* Wrapper for strlen(key) + integer type (up to long long range). */
// rdbSaveAuxField()的封装,适用于key是c语言类型字符串,val是一个longlong类型的整数
int rdbSaveAuxFieldStrInt(rio *rdb, char *key, long long val) {
char buf[LONG_STR_SIZE];
int vlen = ll2string(buf,sizeof(buf),val);
return rdbSaveAuxField(rdb,key,strlen(key),buf,vlen);
}
/* Save a few default AUX fields with information about the RDB generated. */
// 将一个rdb文件的默认信息写入到rio中
int rdbSaveInfoAuxFields(rio *rdb) {
// 判断主机的总线宽度,是64位还是32位
int redis_bits = (sizeof(void*) == 8) ? 64 : 32;
/* Add a few fields about the state when the RDB was created. */
// 添加rdb文件的状态信息:Redis版本,redis位数,当前时间和Redis当前使用的内存数
if (rdbSaveAuxFieldStrStr(rdb,"redis-ver",REDIS_VERSION) == -1) return -1;
if (rdbSaveAuxFieldStrInt(rdb,"redis-bits",redis_bits) == -1) return -1;
if (rdbSaveAuxFieldStrInt(rdb,"ctime",time(NULL)) == -1) return -1;
if (rdbSaveAuxFieldStrInt(rdb,"used-mem",zmalloc_used_memory()) == -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 C_OK is returned, otherwise C_ERR
* is returned and part of the output, or all the output, can be
* missing because of I/O errors.
*
* When the function returns C_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. */
// 将一个RDB格式文件内容写入到rio中,成功返回C_OK,否则C_ERR和一部分或所有的出错信息
// 当函数返回C_ERR,并且error不是NULL,那么error被设置为一个错误码errno
int rdbSaveRio(rio *rdb, int *error) {
dictIterator *di = NULL;
dictEntry *de;
char magic[10];
int j;
long long now = mstime();
uint64_t cksum;
// 开启了校验和选项
if (server.rdb_checksum)
// 设置校验和的函数
rdb->update_cksum = rioGenericUpdateChecksum;
// 将Redis版本信息保存到magic中
snprintf(magic,sizeof(magic),"REDIS%04d",RDB_VERSION);
// 将magic写到rio中
if (rdbWriteRaw(rdb,magic,9) == -1) goto werr;
// 将rdb文件的默认信息写到rio中
if (rdbSaveInfoAuxFields(rdb) == -1) goto werr;
// 遍历所有服务器内的数据库
for (j = 0; j < server.dbnum; j++) {
redisDb *db = server.db+j; //当前的数据库指针
dict *d = db->dict; //当数据库的键值对字典
// 跳过为空的数据库
if (dictSize(d) == 0) continue;
// 创建一个字典类型的迭代器
di = dictGetSafeIterator(d);
if (!di) return C_ERR;
/* Write the SELECT DB opcode */
// 写入数据库的选择标识码 RDB_OPCODE_SELECTDB为254
if (rdbSaveType(rdb,RDB_OPCODE_SELECTDB) == -1) goto werr;
// 写入数据库的id,占了一个字节的长度
if (rdbSaveLen(rdb,j) == -1) goto werr;
/* Write the RESIZE DB opcode. We trim the size to UINT32_MAX, which
* is currently the largest type we are able to represent in RDB sizes.
* However this does not limit the actual size of the DB to load since
* these sizes are just hints to resize the hash tables. */
// 写入调整数据库的操作码,我们将大小限制在UINT32_MAX以内,这并不代表数据库的实际大小,只是提示去重新调整哈希表的大小
uint32_t db_size, expires_size;
// 如果字典的大小大于UINT32_MAX,则设置db_size为最大的UINT32_MAX
db_size = (dictSize(db->dict) <= UINT32_MAX) ?
dictSize(db->dict) :
UINT32_MAX;
// 设置有过期时间键的大小超过UINT32_MAX,则设置expires_size为最大的UINT32_MAX
expires_size = (dictSize(db->expires) <= UINT32_MAX) ?
dictSize(db->expires) :