-
Notifications
You must be signed in to change notification settings - Fork 263
/
server.h
2100 lines (1921 loc) · 96.7 KB
/
server.h
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.
*/
#ifndef __REDIS_H
#define __REDIS_H
#include "fmacros.h"
#include "config.h"
#include "solarisfixes.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <syslog.h>
#include <netinet/in.h>
#include <lua.h>
#include <signal.h>
typedef long long mstime_t; /* 毫秒时间类型millisecond time type. */
#include "ae.h" /* Event driven programming library */
#include "sds.h" /* Dynamic safe strings */
#include "dict.h" /* Hash tables */
#include "adlist.h" /* Linked lists */
#include "zmalloc.h" /* total memory usage aware version of malloc/free */
#include "anet.h" /* Networking the easy way */
#include "ziplist.h" /* Compact list data structure */
#include "intset.h" /* Compact integer set structure */
#include "version.h" /* Version macro */
#include "util.h" /* Misc functions useful in many places */
#include "latency.h" /* Latency monitor API */
#include "sparkline.h" /* ASCII graphs API */
#include "quicklist.h"
/* Following includes allow test functions to be called from Redis main() */
#include "zipmap.h"
#include "sha1.h"
#include "endianconv.h"
#include "crc64.h"
/* Error codes */
#define C_OK 0
#define C_ERR -1
/* Static server configuration */
// 默认的频率:每10秒执行一次
#define CONFIG_DEFAULT_HZ 10 /* Time interrupt calls/sec. */
#define CONFIG_MIN_HZ 1
#define CONFIG_MAX_HZ 500
#define CONFIG_DEFAULT_SERVER_PORT 6379 /* TCP port */
#define CONFIG_DEFAULT_TCP_BACKLOG 511 /* TCP listen backlog */
#define CONFIG_DEFAULT_CLIENT_TIMEOUT 0 /* default client timeout: infinite */
#define CONFIG_DEFAULT_DBNUM 16
#define CONFIG_MAX_LINE 1024
#define CRON_DBS_PER_CALL 16
#define NET_MAX_WRITES_PER_EVENT (1024*64)
#define PROTO_SHARED_SELECT_CMDS 10
#define OBJ_SHARED_INTEGERS 10000
#define OBJ_SHARED_BULKHDR_LEN 32 //共享的回复长度
#define LOG_MAX_LEN 1024 /* Default maximum length of syslog messages */
#define AOF_REWRITE_PERC 100
#define AOF_REWRITE_MIN_SIZE (64*1024*1024)
#define AOF_REWRITE_ITEMS_PER_CMD 64
#define CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN 10000
#define CONFIG_DEFAULT_SLOWLOG_MAX_LEN 128
#define CONFIG_DEFAULT_MAX_CLIENTS 10000
#define CONFIG_AUTHPASS_MAX_LEN 512
#define CONFIG_DEFAULT_SLAVE_PRIORITY 100
#define CONFIG_DEFAULT_REPL_TIMEOUT 60
#define CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD 10
#define CONFIG_RUN_ID_SIZE 40
#define RDB_EOF_MARK_SIZE 40 //rdb文件EOF的长度
#define CONFIG_DEFAULT_REPL_BACKLOG_SIZE (1024*1024) /* 1mb */
#define CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT (60*60) /* 1 hour */
#define CONFIG_REPL_BACKLOG_MIN_SIZE (1024*16) /* 16k */
#define CONFIG_BGSAVE_RETRY_DELAY 5 /* Wait a few secs before trying again. */
#define CONFIG_DEFAULT_PID_FILE "/var/run/redis.pid"
#define CONFIG_DEFAULT_SYSLOG_IDENT "redis"
#define CONFIG_DEFAULT_CLUSTER_CONFIG_FILE "nodes.conf"
#define CONFIG_DEFAULT_DAEMONIZE 0
#define CONFIG_DEFAULT_UNIX_SOCKET_PERM 0
#define CONFIG_DEFAULT_TCP_KEEPALIVE 300
#define CONFIG_DEFAULT_PROTECTED_MODE 1
#define CONFIG_DEFAULT_LOGFILE ""
#define CONFIG_DEFAULT_SYSLOG_ENABLED 0
#define CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR 1
#define CONFIG_DEFAULT_RDB_COMPRESSION 1
#define CONFIG_DEFAULT_RDB_CHECKSUM 1
#define CONFIG_DEFAULT_RDB_FILENAME "dump.rdb"
#define CONFIG_DEFAULT_REPL_DISKLESS_SYNC 0
#define CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY 5
#define CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA 1
#define CONFIG_DEFAULT_SLAVE_READ_ONLY 1
#define CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP NULL
#define CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT 0
#define CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY 0
#define CONFIG_DEFAULT_MAXMEMORY 0
#define CONFIG_DEFAULT_MAXMEMORY_SAMPLES 5
#define CONFIG_DEFAULT_AOF_FILENAME "appendonly.aof"
#define CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE 0
#define CONFIG_DEFAULT_AOF_LOAD_TRUNCATED 1
#define CONFIG_DEFAULT_ACTIVE_REHASHING 1
#define CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC 1
#define CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE 0
#define CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG 10
// 46 here is to support ipv4-mapped-on-ipv6
// 0000:0000:0000:0000:0000:FFFF:111.222.212.222
#define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */
#define NET_PEER_ID_LEN (NET_IP_STR_LEN+32) /* Must be enough for ip:port */
#define CONFIG_BINDADDR_MAX 16
#define CONFIG_MIN_RESERVED_FDS 32
#define CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD 0
#define ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP 20 /* Loopkups per loop. */
#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds */
#define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* CPU max % for keys collection */
#define ACTIVE_EXPIRE_CYCLE_SLOW 0
#define ACTIVE_EXPIRE_CYCLE_FAST 1
/* Instantaneous metrics tracking. */
#define STATS_METRIC_SAMPLES 16 /* Number of samples per metric. */
#define STATS_METRIC_COMMAND 0 /* Number of commands executed. */
#define STATS_METRIC_NET_INPUT 1 /* Bytes read to network .*/
#define STATS_METRIC_NET_OUTPUT 2 /* Bytes written to network. */
#define STATS_METRIC_COUNT 3
/* Protocol and I/O related defines */
#define PROTO_MAX_QUERYBUF_LEN (1024*1024*1024) /* 1GB max query buffer. */
// IO大小
#define PROTO_IOBUF_LEN (1024*16) /*IO大小 Generic I/O buffer size */
// 16k输出缓冲区的大小
#define PROTO_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */
#define PROTO_INLINE_MAX_SIZE (1024*64) /* Max size of inline reads */
#define PROTO_MBULK_BIG_ARG (1024*32)
// long类型转换为字符串所能使用的最大字节数
#define LONG_STR_SIZE 21 /* Bytes needed for long -> str + '\0' */
#define AOF_AUTOSYNC_BYTES (1024*1024*32) /* 自动执行同步的限制 fdatasync every 32MB */
/* When configuring the server eventloop, we setup it so that the total number
* of file descriptors we can handle are server.maxclients + RESERVED_FDS +
* a few more to stay safe. Since RESERVED_FDS defaults to 32, we add 96
* in order to make sure of not over provisioning more than 128 fds. */
#define CONFIG_FDSET_INCR (CONFIG_MIN_RESERVED_FDS+96)
/* Hash table parameters */
#define HASHTABLE_MIN_FILL 10 /* Minimal hash table fill 10% */
/* Command flags. Please check the command table defined in the redis.c file
* for more information about the meaning of every flag. */
#define CMD_WRITE 1 /* "w" flag */
#define CMD_READONLY 2 /* "r" flag */
#define CMD_DENYOOM 4 /* "m" flag */
#define CMD_NOT_USED_1 8 /* no longer used flag */
#define CMD_ADMIN 16 /* "a" flag */
#define CMD_PUBSUB 32 /* "p" flag */
#define CMD_NOSCRIPT 64 /* "s" flag */
#define CMD_RANDOM 128 /* "R" flag */
#define CMD_SORT_FOR_SCRIPT 256 /* "S" flag */
#define CMD_LOADING 512 /* "l" flag */
#define CMD_STALE 1024 /* "t" flag */
#define CMD_SKIP_MONITOR 2048 /* "M" flag */
#define CMD_ASKING 4096 /* "k" flag */
#define CMD_FAST 8192 /* "F" flag */
/* Object types */
#define OBJ_STRING 0 //字符串对象
#define OBJ_LIST 1 //列表对象
#define OBJ_SET 2 //集合对象
#define OBJ_ZSET 3 //有序集合对象
#define OBJ_HASH 4 //哈希对象
/* Objects encoding. Some kind of objects like Strings and Hashes can be
* internally represented in multiple ways. The 'encoding' field of the object
* is set to one of this fields for this object. */
#define OBJ_ENCODING_RAW 0 /* Raw representation */ //原始表示方式,字符串对象是简单动态字符串
#define OBJ_ENCODING_INT 1 /* Encoded as integer */ //long类型的整数
#define OBJ_ENCODING_HT 2 /* Encoded as hash table */ //字典
#define OBJ_ENCODING_ZIPMAP 3 /* Encoded as zipmap */ //已废弃,不使用
#define OBJ_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */ //双端链表
#define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */ //压缩列表
#define OBJ_ENCODING_INTSET 6 /* Encoded as intset */ //整数集合
#define OBJ_ENCODING_SKIPLIST 7 /* Encoded as skiplist */ //跳跃表和字典
#define OBJ_ENCODING_EMBSTR 8 /* Embedded sds string encoding */ //embstr编码的简单动态字符串
#define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */ //快速列表
/* Defines related to the dump file format. To store 32 bits lengths for short
* keys requires a lot of space, so we check the most significant 2 bits of
* the first byte to interpreter the length:
*
* 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
* 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
* 10|000000 [32 bit integer] => if it's 10, a full 32 bit len will follow
* 11|000000 this means: specially encoded object will follow. The six bits
* number specify the kind of object that follows.
* See the RDB_ENC_* defines.
*
* Lengths up to 63 are stored using a single byte, most DB keys, and may
* values, will fit inside. */
#define RDB_6BITLEN 0 //6位长
#define RDB_14BITLEN 1 //14位长
#define RDB_32BITLEN 2 //32位长
#define RDB_ENCVAL 3 //编码值
#define RDB_LENERR UINT_MAX //错误值
/* When a length of a string object stored on disk has the first two bits
* set, the remaining two bits specify a special encoding for the object
* accordingly to the following defines: */
#define RDB_ENC_INT8 0 /* 8位有符号整数 8 bit signed integer */
#define RDB_ENC_INT16 1 /* 16位有符号整数 16 bit signed integer */
#define RDB_ENC_INT32 2 /* 32位有符号整数 32 bit signed integer */
#define RDB_ENC_LZF 3 /* LZF压缩过的字符串 string compressed with FASTLZ */
/* AOF states */
#define AOF_OFF 0 /* AOF is off */
#define AOF_ON 1 /* AOF is on */
#define AOF_WAIT_REWRITE 2 /* AOF waits rewrite to start appending */
/* Client flags */
// client是从节点服务器
#define CLIENT_SLAVE (1<<0) /* This client is a slave server */
// client是主节点服务器
#define CLIENT_MASTER (1<<1) /* This client is a master server */
// client是一个从节点监控器
#define CLIENT_MONITOR (1<<2) /* This client is a slave monitor, see MONITOR */
// client处于事务环境中
#define CLIENT_MULTI (1<<3) /* This client is in a MULTI context */
#define CLIENT_BLOCKED (1<<4) /* The client is waiting in a blocking operation */
// 监视的键被修改,EXEC执行失败
#define CLIENT_DIRTY_CAS (1<<5) /* Watched keys modified. EXEC will fail. */
// 发送回复后要关闭client,当执行client kill命令等
#define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */
// 不被阻塞的client,保存在unblocked_clients中
#define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in
server.unblocked_clients */
// 表示该客户端是一个专门处理lua脚本的伪客户端
#define CLIENT_LUA (1<<8) /* This is a non connected client used by Lua */
// 发送了ASKING命令
#define CLIENT_ASKING (1<<9) /* Client issued the ASKING command */
// 正要关闭的client
#define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */
#define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */
// 命令入队时错误
#define CLIENT_DIRTY_EXEC (1<<12) /* EXEC will fail for errors while queueing */
// 强制进行回复
#define CLIENT_MASTER_FORCE_REPLY (1<<13) /* Queue replies even if is master */
// 强制将节点传播到AOF中
#define CLIENT_FORCE_AOF (1<<14) /* Force AOF propagation of current cmd. */
// 强制将命令传播到从节点
#define CLIENT_FORCE_REPL (1<<15) /* Force replication of current cmd. */
// Redis 2.8版本以前只有SYNC命令,该这个宏来标记client的版本以便选择不同的同步命令
#define CLIENT_PRE_PSYNC (1<<16) /* Instance don't understand PSYNC. */
#define CLIENT_READONLY (1<<17) /* Cluster client is in read-only state. */
#define CLIENT_PUBSUB (1<<18) /* Client is in Pub/Sub mode. */
#define CLIENT_PREVENT_AOF_PROP (1<<19) /* Don't propagate to AOF. */
#define CLIENT_PREVENT_REPL_PROP (1<<20) /* Don't propagate to slaves. */
#define CLIENT_PREVENT_PROP (CLIENT_PREVENT_AOF_PROP|CLIENT_PREVENT_REPL_PROP)
// client还有输出的数据,但是没有设置写处理程序
#define CLIENT_PENDING_WRITE (1<<21) /* Client has output to send but a write
handler is yet not installed. */
// 控制服务器是否回复客户端,默认为开启ON,
// 设置为不开启,服务器不会回复client命令
#define CLIENT_REPLY_OFF (1<<22) /* Don't send replies to client. */
// 为下一条命令设置CLIENT_REPLY_SKIP标志
#define CLIENT_REPLY_SKIP_NEXT (1<<23) /* Set CLIENT_REPLY_SKIP for next cmd */
// 设置为跳过该条回复,服务器会跳过这条命令的回复
#define CLIENT_REPLY_SKIP (1<<24) /* Don't send just this reply. */
#define CLIENT_LUA_DEBUG (1<<25) /* Run EVAL in debug mode. */
#define CLIENT_LUA_DEBUG_SYNC (1<<26) /* EVAL debugging without fork() */
/* Client block type (btype field in client structure)
* if CLIENT_BLOCKED flag is set. */
#define BLOCKED_NONE 0 /* Not blocked, no CLIENT_BLOCKED flag set. */
#define BLOCKED_LIST 1 /* BLPOP & co. */
#define BLOCKED_WAIT 2 /* WAIT for synchronous replication. */
/* Client request types */
#define PROTO_REQ_INLINE 1
#define PROTO_REQ_MULTIBULK 2
/* Client classes for client limits, currently used only for
* the max-client-output-buffer limit implementation. */
#define CLIENT_TYPE_NORMAL 0 /* Normal req-reply clients + MONITORs */
#define CLIENT_TYPE_SLAVE 1 /* Slaves. */
#define CLIENT_TYPE_PUBSUB 2 /* Clients subscribed to PubSub channels. */
#define CLIENT_TYPE_MASTER 3 /* Master. */
#define CLIENT_TYPE_OBUF_COUNT 3 /* Number of clients to expose to output
buffer configuration. Just the first
three: normal, slave, pubsub. */
/* Slave replication state. Used in server.repl_state for slaves to remember
* what to do next. */
// replication关闭状态
#define REPL_STATE_NONE 0 /* No active replication */
// 必须重新连接主节点
#define REPL_STATE_CONNECT 1 /* Must connect to master */
// 处于和主节点正在连接的状态
#define REPL_STATE_CONNECTING 2 /* Connecting to master */
/* --- Handshake states, must be ordered --- */
// 握手状态,有序
// 等待主节点回复PING命令一个PONG
#define REPL_STATE_RECEIVE_PONG 3 /* Wait for PING reply */
// 发送认证命令AUTH给主节点
#define REPL_STATE_SEND_AUTH 4 /* Send AUTH to master */
// 设置状态为等待接受认证回复
#define REPL_STATE_RECEIVE_AUTH 5 /* Wait for AUTH reply */
// 发送从节点的端口号
#define REPL_STATE_SEND_PORT 6 /* Send REPLCONF listening-port */
// 接受一个从节点监听端口号
#define REPL_STATE_RECEIVE_PORT 7 /* Wait for REPLCONF reply */
#define REPL_STATE_SEND_IP 8 /* Send REPLCONF ip-address */
#define REPL_STATE_RECEIVE_IP 9 /* Wait for REPLCONF reply */
// 发送一个
#define REPL_STATE_SEND_CAPA 10 /* Send REPLCONF capa */
#define REPL_STATE_RECEIVE_CAPA 11 /* Wait for REPLCONF reply */
#define REPL_STATE_SEND_PSYNC 12 /* Send PSYNC */
// 等待一个PSYNC回复
#define REPL_STATE_RECEIVE_PSYNC 13 /* Wait for PSYNC reply */
/* --- End of handshake states --- */
// 正从主节点接受RDB文件
#define REPL_STATE_TRANSFER 14 /* Receiving .rdb from master */
// 和主节点保持连接
#define REPL_STATE_CONNECTED 15 /* Connected to master */
/* State of slaves from the POV of the master. Used in client->replstate.
* In SEND_BULK and ONLINE state the slave receives new updates
* in its output queue. In the WAIT_BGSAVE states instead the server is waiting
* to start the next background saving in order to send updates to it. */
// 从服务器节点等待BGSAVE节点的开始,因此要生成一个新的RDB文件
#define SLAVE_STATE_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */
// 已经创建子进程执行写RDB操作,等待完成
#define SLAVE_STATE_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */
// 正在发送RDB文件给从节点
#define SLAVE_STATE_SEND_BULK 8 /* Sending RDB file to slave. */
// RDB文件传输完成
#define SLAVE_STATE_ONLINE 9 /* RDB file transmitted, sending just updates. */
/* Slave capabilities. */
#define SLAVE_CAPA_NONE 0
// 能够解析出RDB文件的EOF流格式
#define SLAVE_CAPA_EOF (1<<0) /* Can parse the RDB EOF streaming format. */
/* Synchronous read timeout - slave side */
#define CONFIG_REPL_SYNCIO_TIMEOUT 5
/* List related stuff */
#define LIST_HEAD 0 //列表头
#define LIST_TAIL 1 //列表尾
/* Sort operations */
#define SORT_OP_GET 0
/* Log levels */
#define LL_DEBUG 0
#define LL_VERBOSE 1
#define LL_NOTICE 2 //日志通知
#define LL_WARNING 3 //日志的警告
#define LL_RAW (1<<10) /* Modifier to log without timestamp */
#define CONFIG_DEFAULT_VERBOSITY LL_NOTICE
/* Supervision options */
#define SUPERVISED_NONE 0
#define SUPERVISED_AUTODETECT 1
#define SUPERVISED_SYSTEMD 2
#define SUPERVISED_UPSTART 3
/* Anti-warning macro... */
#define UNUSED(V) ((void) V)
#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
/* Append only defines */
#define AOF_FSYNC_NO 0 //不执行同步,由系统执行
#define AOF_FSYNC_ALWAYS 1 //每次写入都执行同步
#define AOF_FSYNC_EVERYSEC 2 //每秒同步一次
#define CONFIG_DEFAULT_AOF_FSYNC AOF_FSYNC_EVERYSEC
/* Zip structure related defaults */
#define OBJ_HASH_MAX_ZIPLIST_ENTRIES 512
#define OBJ_HASH_MAX_ZIPLIST_VALUE 64
#define OBJ_SET_MAX_INTSET_ENTRIES 512
#define OBJ_ZSET_MAX_ZIPLIST_ENTRIES 128
#define OBJ_ZSET_MAX_ZIPLIST_VALUE 64
/* List defaults */
#define OBJ_LIST_MAX_ZIPLIST_SIZE -2
#define OBJ_LIST_COMPRESS_DEPTH 0
/* HyperLogLog defines */
#define CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES 3000
/* Sets operations codes */
#define SET_OP_UNION 0
#define SET_OP_DIFF 1
#define SET_OP_INTER 2
/* Redis maxmemory strategies */
// Redis 过期键回收策略
#define MAXMEMORY_VOLATILE_LRU 0
#define MAXMEMORY_VOLATILE_TTL 1
#define MAXMEMORY_VOLATILE_RANDOM 2
#define MAXMEMORY_ALLKEYS_LRU 3
#define MAXMEMORY_ALLKEYS_RANDOM 4
#define MAXMEMORY_NO_EVICTION 5
#define CONFIG_DEFAULT_MAXMEMORY_POLICY MAXMEMORY_NO_EVICTION
/* Scripting */
#define LUA_SCRIPT_TIME_LIMIT 5000 /* milliseconds */
/* Units */
#define UNIT_SECONDS 0 //单位是秒
#define UNIT_MILLISECONDS 1 //单位是毫秒
/* SHUTDOWN flags */
#define SHUTDOWN_NOFLAGS 0 /* 不指定标志 No flags. */
#define SHUTDOWN_SAVE 1 /* 指定停机保存标志即使配置了SHUTDOWN_NOSAVE标志 Force SAVE on SHUTDOWN even if no save
points are configured. */
#define SHUTDOWN_NOSAVE 2 /* 指定停机不保存标志 Don't SAVE on SHUTDOWN. */
/* Command call flags, see call() function */
#define CMD_CALL_NONE 0
#define CMD_CALL_SLOWLOG (1<<0)
#define CMD_CALL_STATS (1<<1)
#define CMD_CALL_PROPAGATE_AOF (1<<2)
#define CMD_CALL_PROPAGATE_REPL (1<<3)
#define CMD_CALL_PROPAGATE (CMD_CALL_PROPAGATE_AOF|CMD_CALL_PROPAGATE_REPL)
#define CMD_CALL_FULL (CMD_CALL_SLOWLOG | CMD_CALL_STATS | CMD_CALL_PROPAGATE)
/* Command propagation flags, see propagate() function */
#define PROPAGATE_NONE 0
#define PROPAGATE_AOF 1
#define PROPAGATE_REPL 2
/* RDB active child save type. */
#define RDB_CHILD_TYPE_NONE 0
#define RDB_CHILD_TYPE_DISK 1 /* RDB 被写入磁盘 RDB is written to disk. */
#define RDB_CHILD_TYPE_SOCKET 2 /* RDB 被写到从节点的套接字中 RDB is written to slave socket. */
/* Keyspace changes notification classes. Every class is associated with a
* character for configuration purposes. */
// 键空间通知的类型,每个类型都关联着一个有目的的字符
#define NOTIFY_KEYSPACE (1<<0) /* K */ //键空间
#define NOTIFY_KEYEVENT (1<<1) /* E */ //键事件
#define NOTIFY_GENERIC (1<<2) /* g */ //通用无类型通知
#define NOTIFY_STRING (1<<3) /* $ */ //字符串类型键通知
#define NOTIFY_LIST (1<<4) /* l */ //列表键通知
#define NOTIFY_SET (1<<5) /* s */ //集合键通知
#define NOTIFY_HASH (1<<6) /* h */ //哈希键通知
#define NOTIFY_ZSET (1<<7) /* z */ //有序集合键通知
#define NOTIFY_EXPIRED (1<<8) /* x */ //过期有关的键通知
#define NOTIFY_EVICTED (1<<9) /* e */ //驱逐有关的键通知
#define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED) /* A */ //所有键通知
/* Get the first bind addr or NULL */
#define NET_FIRST_BIND_ADDR (server.bindaddr_count ? server.bindaddr[0] : NULL)
/* Using the following macro you can run code inside serverCron() with the
* specified period, specified in milliseconds.
* The actual resolution depends on server.hz. */
// 用这个宏来控制if条件中的代码执行的频率
#define run_with_period(_ms_) if ((_ms_ <= 1000/server.hz) || !(server.cronloops%((_ms_)/(1000/server.hz))))
/* We can print the stacktrace, so our assert is defined this way: */
#define serverAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_serverAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),_exit(1)))
#define serverAssert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1)))
#define serverPanic(_e) _serverPanic(#_e,__FILE__,__LINE__),_exit(1) //#_e 将_e字符串化
/*-----------------------------------------------------------------------------
* Data types
*----------------------------------------------------------------------------*/
/* A redis object, that is a type able to hold a string / list / set */
/* The actual Redis Object */
#define LRU_BITS 24
#define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */
#define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */
typedef struct redisObject {
//对象的数据类型,占4bits,共5种类型
unsigned type:4;
//对象的编码,占4bits,共10种类型
unsigned encoding:4;
//least recently used
//实用LRU算法计算相对server.lruclock的LRU时间
unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */
//引用计数
int refcount;
//指向底层数据实现的指针
void *ptr;
} robj;
/* Macro used to obtain the current LRU clock.
* If the current resolution is lower than the frequency we refresh the
* LRU clock (as it should be in production servers) we return the
* precomputed value, otherwise we need to resort to a system call. */
//计算当前LRU时间
#define LRU_CLOCK() ((1000/server.hz <= LRU_CLOCK_RESOLUTION) ? server.lruclock : getLRUClock())
/* Macro used to initialize a Redis object allocated on the stack.
* Note that this macro is taken near the structure definition to make sure
* we'll update it when the structure is changed, to avoid bugs like
* bug #85 introduced exactly in this way. */
// 初始化一个在栈中分配的Redis对象
#define initStaticStringObject(_var,_ptr) do { \
_var.refcount = 1; \
_var.type = OBJ_STRING; \
_var.encoding = OBJ_ENCODING_RAW; \
_var.ptr = _ptr; \
} while(0)
/* To improve the quality of the LRU approximation we take a set of keys
* that are good candidate for eviction across freeMemoryIfNeeded() calls.
*
* Entries inside the eviciton pool are taken ordered by idle time, putting
* greater idle times to the right (ascending order).
*
* Empty entries have the key pointer set to NULL. */
#define MAXMEMORY_EVICTION_POOL_SIZE 16
struct evictionPoolEntry {
// 空转时间
unsigned long long idle; /* Object idle time. */
// 键名称,一个字符串
sds key; /* Key name. */
};
/* Redis database representation. There are multiple databases identified
* by integers from 0 (the default database) up to the max configured
* database. The database number is the 'id' field in the structure. */
typedef struct redisDb {
// 键值对字典,保存数据库中所有的键值对
dict *dict; /* The keyspace for this DB */
// 过期字典,保存着设置过期的键和键的过期时间
dict *expires; /* Timeout of keys with a timeout set */
// 保存着 所有造成客户端阻塞的键和被阻塞的客户端
dict *blocking_keys; /*Keys with clients waiting for data (BLPOP) */
// 保存着 处于阻塞状态的键,value为NULL
dict *ready_keys; /* Blocked keys that received a PUSH */
// 事物模块,用于保存被WATCH命令所监控的键
dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
// 当内存不足时,Redis会根据LRU算法回收一部分键所占的空间,而该eviction_pool是一个长为16数组,保存可能被回收的键
// eviction_pool中所有键按照idle空转时间,从小到大排序,每次回收空转时间最长的键
struct evictionPoolEntry *eviction_pool; /* Eviction pool of keys */
// 数据库ID
int id; /* Database ID */
// 键的平均过期时间
long long avg_ttl; /* Average TTL, just for stats */
} redisDb;
/* Client MULTI/EXEC state */
// 事务命令状态
typedef struct multiCmd {
// 命令的参数列表
robj **argv;
// 命令的参数个数
int argc;
// 命令函数指针
struct redisCommand *cmd;
} multiCmd;
// 事务状态
typedef struct multiState {
// 事务命令队列数组
multiCmd *commands; /* Array of MULTI commands */
// 事务命令的个数
int count; /* Total number of MULTI commands */
// 同步复制的标识
int minreplicas; /* MINREPLICAS for synchronous replication */
// 同步复制的超时时间
time_t minreplicas_timeout; /* MINREPLICAS timeout as unixtime. */
} multiState;
/* This structure holds the blocking operation state for a client.
* The fields used depend on client->btype. */
typedef struct blockingState {
/* Generic fields. */
//阻塞的时间
mstime_t timeout; /* Blocking operation timeout. If UNIX current time
* is > timeout then the operation timed out. */
/* BLOCKED_LIST */
//造成阻塞的键
dict *keys; /* The keys we are waiting to terminate a blocking
* operation such as BLPOP. Otherwise NULL. */
//用于BRPOPLPUSH命令
//用于保存PUSH入元素的键,也就是dstkey
robj *target; /* The key that should receive the element,
* for BRPOPLPUSH. */
/* BLOCKED_WAIT */
// 阻塞状态
int numreplicas; /* Number of replicas we are waiting for ACK. */
// 要达到的复制偏移量
long long reploffset; /* Replication offset to reach. */
} blockingState;
/* The following structure represents a node in the server.ready_keys list,
* where we accumulate all the keys that had clients blocked with a blocking
* operation such as B[LR]POP, but received new data in the context of the
* last executed command.
*
* After the execution of every command or script, we run this list to check
* if as a result we should serve data to clients blocked, unblocking them.
* Note that server.ready_keys will not have duplicates as there dictionary
* also called ready_keys in every structure representing a Redis database,
* where we make sure to remember if a given key was already added in the
* server.ready_keys list. */
typedef struct readyList {
redisDb *db;
robj *key;
} readyList;
/* With multiplexing we need to take per-client state.
* Clients are taken in a linked list. */
typedef struct client {
// client独一无二的ID
uint64_t id; /* Client incremental unique ID. */
// client的套接字
int fd; /* Client socket. */
// 指向当前的数据库
redisDb *db; /* Pointer to currently SELECTed DB. */
// 保存指向数据库的ID
int dictid; /* ID of the currently SELECTed DB. */
// client的名字
robj *name; /* As set by CLIENT SETNAME. */
// 输入缓冲区
sds querybuf; /* Buffer we use to accumulate client queries. */
// 输入缓存的峰值
size_t querybuf_peak; /* Recent (100ms or more) peak of querybuf size. */
// client输入命令时,参数的数量
int argc; /* Num of arguments of current command. */
// client输入命令的参数列表
robj **argv; /* Arguments of current command. */
// 保存客户端执行命令的历史记录
struct redisCommand *cmd, *lastcmd; /* Last command executed. */
// 请求协议类型,内联或者多条命令
int reqtype; /* Request protocol type: PROTO_REQ_* */
// 参数列表中未读取命令参数的数量,读取一个,该值减1
int multibulklen; /* Number of multi bulk arguments left to read. */
// 命令内容的长度
long bulklen; /* Length of bulk argument in multi bulk request. */
// 回复缓存列表,用于发送大于固定回复缓冲区的回复
list *reply; /* List of reply objects to send to the client. */
// 回复缓存列表对象的总字节数
unsigned long long reply_bytes; /* Tot bytes of objects in reply list. */
// 已发送的字节数或对象的字节数
size_t sentlen; /* Amount of bytes already sent in the current
buffer or object being sent. */
// client创建所需时间
time_t ctime; /* Client creation time. */
// 最后一次和服务器交互的时间
time_t lastinteraction; /* Time of the last interaction, used for timeout */
// 客户端的输出缓冲区超过软性限制的时间,记录输出缓冲区第一次到达软性限制的时间
time_t obuf_soft_limit_reached_time;
// client状态的标志
int flags; /* Client flags: CLIENT_* macros. */
// 认证标志,0表示未认证,1表示已认证
int authenticated; /* When requirepass is non-NULL. */
// 从节点的复制状态
int replstate; /* Replication state if this is a slave. */
// 在ack上设置从节点的写处理器,是否在slave向master发送ack,
int repl_put_online_on_ack; /* Install slave write handler on ACK. */
// 保存主服务器传来的RDB文件的文件描述符
int repldbfd; /* Replication DB file descriptor. */
// 读取主服务器传来的RDB文件的偏移量
off_t repldboff; /* Replication DB file offset. */
// 主服务器传来的RDB文件的大小
off_t repldbsize; /* Replication DB file size. */
// 主服务器传来的RDB文件的大小,符合协议的字符串形式
sds replpreamble; /* Replication DB preamble. */
// replication复制的偏移量
long long reploff; /* Replication offset if this is our master. */
// 通过ack命令接收到的偏移量
long long repl_ack_off; /* Replication ack offset, if this is a slave. */
// 通过ack命令接收到的偏移量所用的时间
long long repl_ack_time;/* Replication ack time, if this is a slave. */
// FULLRESYNC回复给从节点的offset
long long psync_initial_offset; /* FULLRESYNC reply offset other slaves
copying this slave output buffer
should use. */
char replrunid[CONFIG_RUN_ID_SIZE+1]; /* Master run id if is a master. */
// 从节点的端口号
int slave_listening_port; /* As configured with: REPLCONF listening-port */
// 从节点IP地址
char slave_ip[NET_IP_STR_LEN]; /* Optionally given by REPLCONF ip-address */
// 从节点的功能
int slave_capa; /* Slave capabilities: SLAVE_CAPA_* bitwise OR. */
// 事物状态
multiState mstate; /* MULTI/EXEC state */
// 阻塞类型
int btype; /* Type of blocking op if CLIENT_BLOCKED. */
// 阻塞的状态
blockingState bpop; /* blocking state */
// 最近一个写全局的复制偏移量
long long woff; /* Last write global replication offset. */
// 监控列表
list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
// 订阅频道
dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
// 订阅的模式
list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
// 被缓存的ID
sds peerid; /* Cached peer ID. */
/* Response buffer */
// 回复固定缓冲区的偏移量
int bufpos;
// 回复固定缓冲区
char buf[PROTO_REPLY_CHUNK_BYTES];
} client;
// SAVE 900 1
// SAVE 300 10
// SAVE 60 10000
// 服务器在900秒之内,对数据库执行了至少1次修改
struct saveparam {
time_t seconds; //秒数
int changes; //修改的次数
};
struct sharedObjectsStruct {
robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
*colon, *nullbulk, *nullmultibulk, *queued,
*emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
*outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *bgsaveerr,
*masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr,
*busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk,
*unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *rpop, *lpop,
*lpush, *emptyscan, *minstring, *maxstring,
*select[PROTO_SHARED_SELECT_CMDS],
*integers[OBJ_SHARED_INTEGERS],
*mbulkhdr[OBJ_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */
*bulkhdr[OBJ_SHARED_BULKHDR_LEN]; /* "$<value>\r\n" */
};
/* ZSETs use a specialized version of Skiplists */
typedef struct zskiplistNode {
robj *obj; //保存成员对象的地址
double score; //分值
struct zskiplistNode *backward; //后退指针
struct zskiplistLevel {
struct zskiplistNode *forward; //前进指针
unsigned int span; //跨度
} level[]; //层级,柔型数组
} zskiplistNode;
typedef struct zskiplist {
struct zskiplistNode *header, *tail;//header指向跳跃表的表头节点,tail指向跳跃表的表尾节点
unsigned long length; //跳跃表的长度或跳跃表节点数量计数器,除去第一个节点
int level; //跳跃表中节点的最大层数,除了第一个节点
} zskiplist;
typedef struct zset {
dict *dict; //字典
zskiplist *zsl; //跳跃表
} zset; //有序集合类型
typedef struct clientBufferLimitsConfig {
unsigned long long hard_limit_bytes;
unsigned long long soft_limit_bytes;
time_t soft_limit_seconds;
} clientBufferLimitsConfig;
extern clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT];
/* The redisOp structure defines a Redis Operation, that is an instance of
* a command with an argument vector, database ID, propagation target
* (PROPAGATE_*), and command pointer.
*
* Currently only used to additionally propagate more commands to AOF/Replication
* after the propagation of the executed command. */
typedef struct redisOp {
robj **argv; //命令的参数列表
int argc, dbid, target; //参数个数,数据库的ID,传播的目标
struct redisCommand *cmd; //命令指针
} redisOp; //Redis操作
/* Defines an array of Redis operations. There is an API to add to this
* structure in a easy way.
*
* redisOpArrayInit();
* redisOpArrayAppend();
* redisOpArrayFree();
*/
typedef struct redisOpArray {
redisOp *ops; //数组指针
int numops; //数组个数
} redisOpArray; //Redis操作数组
/*-----------------------------------------------------------------------------
* Global server state
*----------------------------------------------------------------------------*/
struct clusterState;
/* AIX defines hz to __hz, we don't use this define and in order to allow
* Redis build on AIX we need to undef it. */
#ifdef _AIX
#undef hz
#endif
struct redisServer {
/* General ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××*/
pid_t pid; /* Main process pid. */
// 配置文件的绝对路径
char *configfile; /* Absolute config file path, or NULL */
// 可执行文件的绝对路径
char *executable; /* Absolute executable file path. */
// 执行executable文件的参数
char **exec_argv; /* Executable argv vector (copy). */
// serverCron()调用的频率
int hz; /* serverCron() calls frequency in hertz */
// 数据库数组,长度为16
redisDb *db;
// 命令表
dict *commands; /* Command table */
// rename之前的命令表
dict *orig_commands; /* Command table before command renaming. */
// 事件循环
aeEventLoop *el;
// 服务器的LRU时钟
unsigned lruclock:LRU_BITS; /* Clock for LRU eviction */
// 立即关闭服务器
int shutdown_asap; /* SHUTDOWN needed ASAP */
// 主动rehashing的标志
int activerehashing; /* Incremental rehash in serverCron() */
// 是否设置了密码
char *requirepass; /* Pass for AUTH command, or NULL */
// 保存子进程pid文件
char *pidfile; /* PID file path */
int arch_bits; /* 32 or 64 depending on sizeof(long) */
// serverCron()函数运行的次数
int cronloops; /* Number of times the cron function run */
// 服务器每次重启都会分配一个ID
char runid[CONFIG_RUN_ID_SIZE+1]; /* ID always different at every exec. */
// 哨兵模式
int sentinel_mode; /* True if this instance is a Sentinel. */
/* Networking ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××*/
// TCP监听的端口
int port; /* TCP listening port */
// listen()函数的backlog参数,提示系统该进程要入队的未完成连接请求的数量。默认值为128
int tcp_backlog; /* TCP listen() backlog */
char *bindaddr[CONFIG_BINDADDR_MAX]; /* Addresses we should bind to */
// 绑定地址的数量
int bindaddr_count; /* Number of addresses in server.bindaddr[] */
// Unix socket的路径
char *unixsocket; /* UNIX socket path */
mode_t unixsocketperm; /* UNIX socket permission */
int ipfd[CONFIG_BINDADDR_MAX]; /* TCP socket file descriptors */
int ipfd_count; /* Used slots in ipfd[] */
// 本地Unix连接的fd
int sofd; /* Unix socket file descriptor */
// 集群的fd
int cfd[CONFIG_BINDADDR_MAX];/* Cluster bus listening socket */
// 集群的fd个数
int cfd_count; /* Used slots in cfd[] */
list *clients; /* List of active clients */
// 所有待关闭的client链表
list *clients_to_close; /* Clients to close asynchronously */
// 要写或者安装写处理程序的client链表
list *clients_pending_write; /* There is to write or install handler. */
// 从节点列表和监视器列表
list *slaves, *monitors; /* List of slaves and MONITORs */
// 当前的client,被用于崩溃报告
client *current_client; /* Current client, only used on crash report */
// 如果当前client正处于暂停状态,则设置为真
int clients_paused; /* True if clients are currently paused */
// 取消暂停状态的时间
mstime_t clients_pause_end_time; /* Time when we undo clients_paused */
char neterr[ANET_ERR_LEN]; /* Error buffer for anet.c */
// 迁移缓存套接字的字典,键是host:ip,值是TCP socket的的结构
dict *migrate_cached_sockets;/* MIGRATE cached sockets */
uint64_t next_client_id; /* Next client unique ID. Incremental. */
// 受保护模式,不接受外部的连接
int protected_mode; /* Don't accept external connections. */
/* RDB / AOF loading information ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××*/
// 正在载入状态
int loading; /* We are loading data from disk if true */
// 设置载入的总字节
off_t loading_total_bytes;
// 已载入的字节数
off_t loading_loaded_bytes;
// 载入的开始时间
time_t loading_start_time;
// 在load时,用来设置读或写的最大字节数max_processing_chunk
off_t loading_process_events_interval_bytes;
/* Fast pointers to often looked up command ×××××××××××××××××××××××××××××××××××××××××××××××*/
struct redisCommand *delCommand, *multiCommand, *lpushCommand, *lpopCommand,
*rpopCommand, *sremCommand, *execCommand;
/* Fields used only for stats ×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××*/
time_t stat_starttime; /* Server start time */
// 命令执行的次数
long long stat_numcommands; /* Number of processed commands */
// 连接接受的数量
long long stat_numconnections; /* Number of connections received */
// 过期键的数量
long long stat_expiredkeys; /* Number of expired keys */
// 回收键的个数
long long stat_evictedkeys; /* Number of evicted keys (maxmemory) */
long long stat_keyspace_hits; /* Number of successful lookups of keys */
long long stat_keyspace_misses; /* Number of failed lookups of keys */
// 服务器内存使用的
size_t stat_peak_memory; /* Max used memory record */
// 计算fork()消耗的时间
long long stat_fork_time; /* Time needed to perform latest fork() */
// 计算fork的速率,GB/每秒
double stat_fork_rate; /* Fork rate in GB/sec. */
// 因为最大连接数限制而被拒绝的client个数
long long stat_rejected_conn; /* Clients rejected because of maxclients */
// 执行全量重同步的次数
long long stat_sync_full; /* Number of full resyncs with slaves. */
// 接受PSYNC请求的个数
long long stat_sync_partial_ok; /* Number of accepted PSYNC requests. */
long long stat_sync_partial_err;/* Number of unaccepted PSYNC requests. */
list *slowlog; /* SLOWLOG list of commands */
long long slowlog_entry_id; /* SLOWLOG current entry ID */
long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */
unsigned long slowlog_max_len; /* SLOWLOG max number of items logged */
// 常驻内存的大小
size_t resident_set_size; /* RSS sampled in serverCron(). */
// 从网络读的字节数
long long stat_net_input_bytes; /* Bytes read from network. */
// 已经写到网络的字节数
long long stat_net_output_bytes; /* Bytes written to network. */
/* The following two are used to track instantaneous metrics, like number of operations per second,
* network traffic. ××××××××××××××××××××××××××××××××××××××*/
struct {
// 上一个进行抽样的时间戳
long long last_sample_time; /* Timestamp of last sample in ms */
// 上一个抽样时的样品数量
long long last_sample_count;/* Count in last sample */
// 样品表
long long samples[STATS_METRIC_SAMPLES];
// 样品表的下标
int idx;
} inst_metric[STATS_METRIC_COUNT];
/* Configuration ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××*/
// 可见性日志,日志级别
int verbosity; /* Loglevel in redis.conf */
// client超过的最大时间,单位秒
int maxidletime; /* Client timeout in seconds */
int tcpkeepalive; /* Set SO_KEEPALIVE if non-zero. */
// 关闭测试,默认初始化为1
int active_expire_enabled; /* Can be disabled for testing purposes. */
size_t client_max_querybuf_len; /* Limit for client query buffer length */
int dbnum; /* Total number of configured DBs */
// 1表示被监视,否则0
int supervised; /* 1 if supervised, 0 otherwise. */
// 监视模式
int supervised_mode; /* See SUPERVISED_* */
// 如果是以守护进程运行,则为真
int daemonize; /* True if running as a daemon */
// 不同类型的client的输出缓冲区限制
clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT];