-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathnetworking.c
2453 lines (2247 loc) · 97.5 KB
/
networking.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 <sys/uio.h>
#include <math.h>
static void setProtocolError(client *c, int pos);
/* Return the size consumed from the allocator, for the specified SDS string,
* including internal fragmentation. This function is used in order to compute
* the client output buffer size. */
// 计算sds保存字符串数据的空间大小
size_t sdsZmallocSize(sds s) {
// 返回buf[]柔性数组的地址
void *sh = sdsAllocPtr(s);
return zmalloc_size(sh);
}
/* Return the amount of memory used by the sds string at object->ptr
* for a string object. */
// 返回字符串对象所使用的内存数
size_t getStringObjectSdsUsedMemory(robj *o) {
serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);
switch(o->encoding) {
// 返回buf的内存大小
case OBJ_ENCODING_RAW: return sdsZmallocSize(o->ptr);
case OBJ_ENCODING_EMBSTR: return zmalloc_size(o)-sizeof(robj);
default: return 0; /* Just integer encoding for now. */
}
}
// 复制client的回复内容,增加引用计数
void *dupClientReplyValue(void *o) {
incrRefCount((robj*)o);
return o;
}
// 订阅模式下,比较两个字符串对象,以二进制安全的方式进行比较
int listMatchObjects(void *a, void *b) {
return equalStringObjects(a,b);
}
// 创建一个新的client
client *createClient(int fd) {
client *c = zmalloc(sizeof(client)); //分配空间
/* passing -1 as fd it is possible to create a non connected client.
* This is useful since all the commands needs to be executed
* in the context of a client. When commands are executed in other
* contexts (for instance a Lua script) we need a non connected client. */
// 如果fd为-1,表示创建的是一个无网络连接的伪客户端,用于执行lua脚本的时候。
// 如果fd不等于-1,表示创建一个有网络连接的客户端
if (fd != -1) {
// 设置fd为非阻塞模式
anetNonBlock(NULL,fd);
// 禁止使用 Nagle 算法,client向内核递交的每个数据包都会立即发送给server出去,TCP_NODELAY
anetEnableTcpNoDelay(NULL,fd);
// 如果开启了tcpkeepalive,则设置 SO_KEEPALIVE
if (server.tcpkeepalive)
// 设置tcp连接的keep alive选项
anetKeepAlive(NULL,fd,server.tcpkeepalive);
// 创建一个文件事件状态el,且监听读事件,开始接受命令的输入
if (aeCreateFileEvent(server.el,fd,AE_READABLE,
readQueryFromClient, c) == AE_ERR)
{
close(fd);
zfree(c);
return NULL;
}
}
// 默认选0号数据库
selectDb(c,0);
// 设置client的ID
c->id = server.next_client_id++;
// client的套接字
c->fd = fd;
// client的名字
c->name = NULL;
// 回复固定(静态)缓冲区的偏移量
c->bufpos = 0;
// 输入缓存区
c->querybuf = sdsempty();
// 输入缓存区的峰值
c->querybuf_peak = 0;
// 请求协议类型,内联或者多条命令,初始化为0
c->reqtype = 0;
// 参数个数
c->argc = 0;
// 参数列表
c->argv = NULL;
// 当前执行的命令和最近一次执行的命令
c->cmd = c->lastcmd = NULL;
// 查询缓冲区剩余未读取命令的数量
c->multibulklen = 0;
// 读入参数的长度
c->bulklen = -1;
// 已发的字节数
c->sentlen = 0;
// client的状态
c->flags = 0;
// 设置创建client的时间和最后一次互动的时间
c->ctime = c->lastinteraction = server.unixtime;
// 认证状态
c->authenticated = 0;
// replication复制的状态,初始为无
c->replstate = REPL_STATE_NONE;
// 设置从节点的写处理器为ack,是否在slave向master发送ack
c->repl_put_online_on_ack = 0;
// replication复制的偏移量
c->reploff = 0;
// 通过ack命令接收到的偏移量
c->repl_ack_off = 0;
// 通过ack命令接收到的偏移量所用的时间
c->repl_ack_time = 0;
// 从节点的端口号
c->slave_listening_port = 0;
// 从节点IP地址
c->slave_ip[0] = '\0';
// 从节点的功能
c->slave_capa = SLAVE_CAPA_NONE;
// 回复链表
c->reply = listCreate();
// 回复链表的字节数
c->reply_bytes = 0;
// 回复缓冲区的内存大小软限制
c->obuf_soft_limit_reached_time = 0;
// 回复链表的释放和复制方法
listSetFreeMethod(c->reply,decrRefCountVoid);
listSetDupMethod(c->reply,dupClientReplyValue);
// 阻塞类型
c->btype = BLOCKED_NONE;
// 阻塞超过时间
c->bpop.timeout = 0;
// 造成阻塞的键字典
c->bpop.keys = dictCreate(&setDictType,NULL);
// 存储解除阻塞的键,用于保存PUSH入元素的键,也就是dstkey
c->bpop.target = NULL;
// 阻塞状态
c->bpop.numreplicas = 0;
// 要达到的复制偏移量
c->bpop.reploffset = 0;
// 全局的复制偏移量
c->woff = 0;
// 监控的键
c->watched_keys = listCreate();
// 订阅频道
c->pubsub_channels = dictCreate(&setDictType,NULL);
// 订阅模式
c->pubsub_patterns = listCreate();
// 被缓存的peerid,peerid就是 ip:port
c->peerid = NULL;
// 订阅发布模式的释放和比较方法
listSetFreeMethod(c->pubsub_patterns,decrRefCountVoid);
listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
// 将真正的client放在服务器的客户端链表中
if (fd != -1) listAddNodeTail(server.clients,c);
// 初始化client的事物状态
initClientMultiState(c);
return c;
}
/* This function is called every time we are going to transmit new data
* to the client. The behavior is the following:
*
* If the client should receive new data (normal clients will) the function
* returns C_OK, and make sure to install the write handler in our event
* loop so that when the socket is writable new data gets written.
*
* If the client should not receive new data, because it is a fake client
* (used to load AOF in memory), a master or because the setup of the write
* handler failed, the function returns C_ERR.
*
* The function may return C_OK without actually installing the write
* event handler in the following cases:
*
* 1) The event handler should already be installed since the output buffer
* already contained something.
* 2) The client is a slave but not yet online, so we want to just accumulate
* writes in the buffer but not actually sending them yet.
*
* Typically gets called every time a reply is built, before adding more
* data to the clients output buffers. If the function returns C_ERR no
* data should be appended to the output buffers. */
/*
这个函数每次向客户端发送新数据时会调用,有如下行为:
如果client应该接收到了新数据,函数返回 C_OK,并且将写处理程序设置到数据循环中以便socket可写时将新数据写入
如果client不应该接收到新数据,可能是因为:载入AOF的伪client,主节点或者写处理程序设置失败,函数返回C_ERR
函数可能返回C_OK,在没有安装写处理程序的情况如下:
1.事件处理程序已经已经被安装,因为之前输出缓冲区已经有数据
2.client是一个从节点,但是还没有在线,所以只是想在缓冲区累计写操作,而不是想发送他们
通常每次在回复被创建时调用,在添加数据到client的缓冲区之前。如果函数返回C_ERR,没有数据被追加到输出缓冲区
*/
// 准备一个可写的client
int prepareClientToWrite(client *c) {
/* If it's the Lua client we always return ok without installing any
* handler since there is no socket at all. */
// 如果是要执行lua脚本的伪client,则总是返回C_OK,总是可写的
if (c->flags & CLIENT_LUA) return C_OK;
/* CLIENT REPLY OFF / SKIP handling: don't send replies. */
// 如果client没有开启这条命令的回复功能,则返回C_ERR
// CLIENT_REPLY_OFF设置为不开启,服务器不会回复client命令
// CLIENT_REPLY_SKIP设置为跳过该条回复,服务器会跳过这条命令的回复
if (c->flags & (CLIENT_REPLY_OFF|CLIENT_REPLY_SKIP)) return C_ERR;
/* Masters don't receive replies, unless CLIENT_MASTER_FORCE_REPLY flag
* is set. */
// 如果主节点服务器且没有设置强制回复,返回C_ERR
if ((c->flags & CLIENT_MASTER) &&
!(c->flags & CLIENT_MASTER_FORCE_REPLY)) return C_ERR;
// 如果是载入AOF的伪client,则返回C_ERR
if (c->fd <= 0) return C_ERR; /* Fake client for AOF loading. */
/* Schedule the client to write the output buffers to the socket only
* if not already done (there were no pending writes already and the client
* was yet not flagged), and, for slaves, if the slave can actually
* receive writes at this stage. */
// 如果client的回复缓冲区为空,且client还有输出的数据,但是没有设置写处理程序,且
// replication的状态为关闭状态,或已经将RDB传输完成且不向主节点发送ack
if (!clientHasPendingReplies(c) &&
!(c->flags & CLIENT_PENDING_WRITE) &&
(c->replstate == REPL_STATE_NONE ||
(c->replstate == SLAVE_STATE_ONLINE && !c->repl_put_online_on_ack)))
{
/* Here instead of installing the write handler, we just flag the
* client and put it into a list of clients that have something
* to write to the socket. This way before re-entering the event
* loop, we can try to directly write to the client sockets avoiding
* a system call. We'll only really install the write handler if
* we'll not be able to write the whole reply at once. */
// 将client设置为还有输出的数据,但是没有设置写处理程序
c->flags |= CLIENT_PENDING_WRITE;
// 将当前client加入到要写或者安装写处理程序的client链表
listAddNodeHead(server.clients_pending_write,c);
}
/* Authorize the caller to queue in the output buffer of this client. */
// 授权调用者在这个client的输出缓冲区排队
return C_OK;
}
/* Create a duplicate of the last object in the reply list when
* it is not exclusively owned by the reply list. */
// 当回复链表的最后一个对象被其他程序引用,则创建一份复制品
robj *dupLastObjectIfNeeded(list *reply) {
robj *new, *cur;
listNode *ln;
serverAssert(listLength(reply) > 0);
// 尾节点地址
ln = listLast(reply);
// 节点保存的对象
cur = listNodeValue(ln);
// 创建一份非共享的对象,替代原有的对象
if (cur->refcount > 1) {
new = dupStringObject(cur);
decrRefCount(cur);
listNodeValue(ln) = new;
}
return listNodeValue(ln);
}
/* -----------------------------------------------------------------------------
* Low level functions to add more data to output buffers.
* -------------------------------------------------------------------------- */
// 将字符串s添加到固定回复缓冲区c->buf中
int _addReplyToBuffer(client *c, const char *s, size_t len) {
// 固定回复缓冲区可用的大小
size_t available = sizeof(c->buf)-c->bufpos;
// 如果client即将关闭,则直接成功返回
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return C_OK;
/* If there already are entries in the reply list, we cannot
* add anything more to the static buffer. */
// 如果回复链表中有内容,就不能继续添加到固定回复缓冲区中
if (listLength(c->reply) > 0) return C_ERR;
/* Check that the buffer has enough space available for this string. */
// 检查空间大小是否满足
if (len > available) return C_ERR;
// 将s拷贝到client的buf中,并更新buf的偏移量
memcpy(c->buf+c->bufpos,s,len);
c->bufpos+=len;
return C_OK;
}
// 添加大小到回复链表中
void _addReplyObjectToList(client *c, robj *o) {
robj *tail;
// 如果client即将关闭,则直接成功返回
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return;
// 如果链表为空,则将对象追加到链表末尾
if (listLength(c->reply) == 0) {
incrRefCount(o);
listAddNodeTail(c->reply,o);
// 返回字符串对象所使用的内存数,更新回复链表所占的字节数大小
c->reply_bytes += getStringObjectSdsUsedMemory(o);
// 链表不为空
} else {
// 获取尾节点的值
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
// 如果是sds,且最后一个节点的sds大小加上添加对象的sds大小小于16k
if (tail->ptr != NULL &&
tail->encoding == OBJ_ENCODING_RAW &&
sdslen(tail->ptr)+sdslen(o->ptr) <= PROTO_REPLY_CHUNK_BYTES)
{
// 从链表字节数中,减去尾节点sds保存字符串数据的空间大小
c->reply_bytes -= sdsZmallocSize(tail->ptr);
// 然后创建一个份尾节点的非共享的复制品替代链表原有的
tail = dupLastObjectIfNeeded(c->reply);
// 将两者拼接到一起
tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
// 重新计算链表字节数
c->reply_bytes += sdsZmallocSize(tail->ptr);
// 空间大小超过16k
} else {
incrRefCount(o);
// 添加到链表尾部
listAddNodeTail(c->reply,o);
// 重新计算链表字节数
c->reply_bytes += getStringObjectSdsUsedMemory(o);
}
}
// 检查回复缓冲区的大小是否超过系统限制,如果超过则关闭client
asyncCloseClientOnOutputBufferLimitReached(c);
}
/* This method takes responsibility over the sds. When it is no longer
* needed it will be free'd, otherwise it ends up in a robj. */
// 添加一个sds到回复链表中,会负责释放sds
void _addReplySdsToList(client *c, sds s) {
robj *tail;
// 如果client即将关闭,则释放s,返回
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) {
sdsfree(s);
return;
}
// 如果链表为空,则将对象追加到链表末尾
if (listLength(c->reply) == 0) {
// 将sds构建成字符串的追加到链表末尾
listAddNodeTail(c->reply,createObject(OBJ_STRING,s));
// 重新计算链表字节数
c->reply_bytes += sdsZmallocSize(s);
// 链表不为空
} else {
// 获取尾节点的值
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
// 最后一个节点的sds大小加上添加的sds大小小于16k
if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW &&
sdslen(tail->ptr)+sdslen(s) <= PROTO_REPLY_CHUNK_BYTES)
{
// 将sds和尾节点的sds拼接起来,更新链表字节数
c->reply_bytes -= sdsZmallocSize(tail->ptr);
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
c->reply_bytes += sdsZmallocSize(tail->ptr);
sdsfree(s);
// 空间大小超过16k,新创建一个节点,追加到链表尾部
} else {
listAddNodeTail(c->reply,createObject(OBJ_STRING,s));
c->reply_bytes += sdsZmallocSize(s);
}
}
// 检查回复缓冲区的大小是否超过系统限制,如果超过则关闭client
asyncCloseClientOnOutputBufferLimitReached(c);
}
// 添加一个c字符串到回复链表中
void _addReplyStringToList(client *c, const char *s, size_t len) {
robj *tail;
// 如果client即将关闭,则释放s,返回
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return;
// 如果链表为空,则将对象追加到链表末尾
if (listLength(c->reply) == 0) {
// 将c字符串构建成字符串的追加到链表末尾
robj *o = createStringObject(s,len);
// 追加到链表末尾
listAddNodeTail(c->reply,o);
// 更新链表字节数
c->reply_bytes += getStringObjectSdsUsedMemory(o);
// 链表不为空
} else {
// 获取尾节点的值
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
// 最后一个节点的sds大小加上添加字符串长度大小小于16k
if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW &&
sdslen(tail->ptr)+len <= PROTO_REPLY_CHUNK_BYTES)
{
// 将字符串和尾节点的sds拼接起来,更新链表字节数
c->reply_bytes -= sdsZmallocSize(tail->ptr);
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,len);
c->reply_bytes += sdsZmallocSize(tail->ptr);
// 空间大小超过16k,新创建一个节点,追加到链表尾部
} else {
robj *o = createStringObject(s,len);
listAddNodeTail(c->reply,o);
c->reply_bytes += getStringObjectSdsUsedMemory(o);
}
}
// 检查回复缓冲区的大小是否超过系统限制,如果超过则关闭client
asyncCloseClientOnOutputBufferLimitReached(c);
}
/* -----------------------------------------------------------------------------
* Higher level functions to queue data on the client output buffer.
* The following functions are the ones that commands implementations will call.
* -------------------------------------------------------------------------- */
// 添加obj到client的回复缓冲区中
void addReply(client *c, robj *obj) {
// 准备client为可写的
if (prepareClientToWrite(c) != C_OK) return;
/* This is an important place where we can avoid copy-on-write
* when there is a saving child running, avoiding touching the
* refcount field of the object if it's not needed.
*
* If the encoding is RAW and there is room in the static buffer
* we'll be able to send the object to the client without
* messing with its page. */
// 如果子进程正在执行save操作,尽量不要避免修改对象的引用计数
// 如果是原生的字符串编码,则添加到固定的回复缓冲区中,
if (sdsEncodedObject(obj)) {
// 如果固定的回复缓冲区空间不足够,则添加到回复链表中,可能引起内存分配
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK)
_addReplyObjectToList(c,obj);
// 如果是int编码的对象
} else if (obj->encoding == OBJ_ENCODING_INT) {
/* youhua: if there is room in the static buffer for 32 bytes
* (more than the max chars a 64 bit integer can take as string) we
* avoid decoding the object and go for the lower level approach. */
// 最优化:如果固定的缓冲区大小等于多于32字节,则将整数转换成字符串,保存在固定的缓冲区buf中
if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) {
char buf[32];
int len;
// 转换为字符串
len = ll2string(buf,sizeof(buf),(long)obj->ptr);
// 将字符串添加到client的buf中
if (_addReplyToBuffer(c,buf,len) == C_OK)
return;
/* else... continue with the normal code path, but should never
* happen actually since we verified there is room. */
}
// 当前对象是整数,但是长度大于32位,则解码成字符串对象
obj = getDecodedObject(obj);
// 添加字符串对象的值到固定的回复buf中
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK)
// 如果添加失败,则保存到回复链表中
_addReplyObjectToList(c,obj);
decrRefCount(obj);
} else {
serverPanic("Wrong obj->encoding in addReply()");
}
}
// 将sds复制到client的回复缓冲区中
void addReplySds(client *c, sds s) {
// 准备client为可写的
if (prepareClientToWrite(c) != C_OK) {
/* The caller expects the sds to be free'd. */
sdsfree(s);
return;
}
// 将sds复制到client的回复缓冲区中,成功要释放
if (_addReplyToBuffer(c,s,sdslen(s)) == C_OK) {
sdsfree(s);
} else {
/* This method free's the sds when it is no longer needed. */
// 否则追加到回复链表中
_addReplySdsToList(c,s);
}
}
// 将c字符串复制到client的回复缓冲区中
void addReplyString(client *c, const char *s, size_t len) {
if (prepareClientToWrite(c) != C_OK) return; //准备client为可写的
if (_addReplyToBuffer(c,s,len) != C_OK) //将字符串复制到client的回复缓冲区中
_addReplyStringToList(c,s,len);
}
// 按格式添加一个错误回复
void addReplyErrorLength(client *c, const char *s, size_t len) {
addReplyString(c,"-ERR ",5);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
// 按格式添加一个错误回复
void addReplyError(client *c, const char *err) {
addReplyErrorLength(c,err,strlen(err));
}
// 按格式添加多个错误回复
void addReplyErrorFormat(client *c, const char *fmt, ...) {
size_t l, j;
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
/* Make sure there are no newlines in the string, otherwise invalid protocol
* is emitted. */
l = sdslen(s);
for (j = 0; j < l; j++) {
if (s[j] == '\r' || s[j] == '\n') s[j] = ' ';
}
addReplyErrorLength(c,s,sdslen(s));
sdsfree(s);
}
// 按格式添加一个状态回复
void addReplyStatusLength(client *c, const char *s, size_t len) {
addReplyString(c,"+",1);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
// 按格式添加一个状态回复
void addReplyStatus(client *c, const char *status) {
addReplyStatusLength(c,status,strlen(status));
}
// 按格式添加多个状态回复
void addReplyStatusFormat(client *c, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
addReplyStatusLength(c,s,sdslen(s));
sdsfree(s);
}
/* Adds an empty object to the reply list that will contain the multi bulk
* length, which is not known when this function is called. */
// 添加一个空对象到回复链表中,之后去在往链表中添加回复
void *addDeferredMultiBulkLength(client *c) {
/* Note that we install the write event here even if the object is not
* ready to be sent, since we are sure that before returning to the
* event loop setDeferredMultiBulkLength() will be called. */
// 准备client为可写的
if (prepareClientToWrite(c) != C_OK) return NULL;
// 创建一个空字符串对象追加到回复链表的末尾
listAddNodeTail(c->reply,createObject(OBJ_STRING,NULL));
// 返回这个空对象的地址
return listLast(c->reply);
}
/* Populate the length object and try gluing it to the next chunk. */
// 设置回复的一个length对象,并尝试粘合下一个节点
void setDeferredMultiBulkLength(client *c, void *node, long length) {
listNode *ln = (listNode*)node;
robj *len, *next;
/* Abort when *node is NULL (see addDeferredMultiBulkLength). */
if (node == NULL) return;
// 节点的值对象
len = listNodeValue(ln);
// length写入值对象
len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
// 设置对象的编码
len->encoding = OBJ_ENCODING_RAW; /* in case it was an EMBSTR. */
// 更新回复链表的字节数
c->reply_bytes += sdsZmallocSize(len->ptr);
// 后继节点不为空
if (ln->next != NULL) {
next = listNodeValue(ln->next);
/* Only glue when the next node is non-NULL (an sds in this case) */
// 尝试将当前节点和后继节点的值粘合起来
if (next->ptr != NULL) {
c->reply_bytes -= sdsZmallocSize(len->ptr);
c->reply_bytes -= getStringObjectSdsUsedMemory(next);
len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
c->reply_bytes += sdsZmallocSize(len->ptr);
listDelNode(c->reply,ln->next);
}
}
// 检查回复缓冲区的大小是否超过系统限制,如果超过则关闭client
asyncCloseClientOnOutputBufferLimitReached(c);
}
/* Add a double as a bulk reply */
// 按照格式添加一个double类型的回复
void addReplyDouble(client *c, double d) {
char dbuf[128], sbuf[128];
int dlen, slen;
// 是否是正负无穷值
if (isinf(d)) {
/* Libc in odd systems (Hi Solaris!) will format infinite in a
* different way, so better to handle it in an explicit way. */
addReplyBulkCString(c, d > 0 ? "inf" : "-inf");
// 双精度浮点数
} else {
// 获取double的位数
dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
// 按照获取长度
slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
// 将以字符串添加到回复中
addReplyString(c,sbuf,slen);
}
}
/* Add a long double as a bulk reply, but uses a human readable formatting
* of the double instead of exposing the crude behavior of doubles to the
* dear user. */
// 根据long double构建建一个人类友好的字符串对象,添加到回复中
void addReplyHumanLongDouble(client *c, long double d) {
robj *o = createStringObjectFromLongDouble(d,1);
addReplyBulk(c,o);
decrRefCount(o);
}
/* Add a long long as integer reply or bulk len / multi bulk count.
* Basically this is used to output <prefix><long long><crlf>. */
// 添加一个longlong作为整型回复或回复的长度,格式:<prefix><long long><crlf>
void addReplyLongLongWithPrefix(client *c, long long ll, char prefix) {
char buf[128];
int len;
/* Things like $3\r\n or *2\r\n are emitted very often by the protocol
* so we have a few shared objects to use if the integer is small
* like it is most of the times. */
// *2\r\n,前缀是'*',ll小于共享的长度,则添加多条回复
if (prefix == '*' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) {
addReply(c,shared.mbulkhdr[ll]);
return;
// $3\r\n,前缀是'$',ll小于共享的长度,则添加一条回复
} else if (prefix == '$' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) {
addReply(c,shared.bulkhdr[ll]);
return;
}
// 超过共享的长度,则自己构建一条回复添加到client中
buf[0] = prefix;
len = ll2string(buf+1,sizeof(buf)-1,ll);
buf[len+1] = '\r';
buf[len+2] = '\n';
addReplyString(c,buf,len+3);
}
// 添加一个整数回复
void addReplyLongLong(client *c, long long ll) {
if (ll == 0)
addReply(c,shared.czero);
else if (ll == 1)
addReply(c,shared.cone);
else // :<ll>\r\n
addReplyLongLongWithPrefix(c,ll,':');
}
// 添加多条回复的长度
void addReplyMultiBulkLen(client *c, long length) {
if (length < OBJ_SHARED_BULKHDR_LEN)
addReply(c,shared.mbulkhdr[length]);
else // *<length>\r\n
addReplyLongLongWithPrefix(c,length,'*');
}
/* Create the length prefix of a bulk reply, example: $2234 */
// 创建一个回复的前缀长度,例如:$2234
void addReplyBulkLen(client *c, robj *obj) {
size_t len;
// 解码成字符串对象,获取长度
if (sdsEncodedObject(obj)) {
len = sdslen(obj->ptr);
// 整数值
} else {
long n = (long)obj->ptr;
/* Compute how many bytes will take this integer as a radix 10 string */
// 计算出整数有多少位
len = 1;
// 负数还要加上负号
if (n < 0) {
len++;
n = -n;
}
while((n = n/10) != 0) {
len++;
}
}
// 添加一个有前缀的整数回复
if (len < OBJ_SHARED_BULKHDR_LEN)
addReply(c,shared.bulkhdr[len]);
else
addReplyLongLongWithPrefix(c,len,'$');
}
/* Add a Redis Object as a bulk reply */
// 添加一个对象回复
void addReplyBulk(client *c, robj *obj) {
addReplyBulkLen(c,obj);
addReply(c,obj);
addReply(c,shared.crlf);
}
/* Add a C buffer as bulk reply */
// 添加一个c缓冲区回复
void addReplyBulkCBuffer(client *c, const void *p, size_t len) {
addReplyLongLongWithPrefix(c,len,'$');
addReplyString(c,p,len);
addReply(c,shared.crlf);
}
/* Add sds to reply (takes ownership of sds and frees it) */
// 添加一个sds回复
void addReplyBulkSds(client *c, sds s) {
addReplySds(c,sdscatfmt(sdsempty(),"$%u\r\n",
(unsigned long)sdslen(s)));
addReplySds(c,s);
addReply(c,shared.crlf);
}
/* Add a C nul term string as bulk reply */
// 添加一个c字符串回复
void addReplyBulkCString(client *c, const char *s) {
if (s == NULL) {
addReply(c,shared.nullbulk);
} else {
addReplyBulkCBuffer(c,s,strlen(s));
}
}
/* Add a long long as a bulk reply */
// 添加一个 long long类型的回复
void addReplyBulkLongLong(client *c, long long ll) {
char buf[64];
int len;
len = ll2string(buf,64,ll);
addReplyBulkCBuffer(c,buf,len);
}
/* Copy 'src' client output buffers into 'dst' client output buffers.
* The function takes care of freeing the old output buffers of the
* destination client. */
// 将src的所有输出拷贝给dst的所有输出中
void copyClientOutputBuffer(client *dst, client *src) {
// 释放dst的回复链表
listRelease(dst->reply);
// 拷贝一份回复链表
dst->reply = listDup(src->reply);
// 拷贝固定回复缓冲区的内容
memcpy(dst->buf,src->buf,src->bufpos);
// 拷贝固定回复缓冲区的偏移量和回复链表的字节数
dst->bufpos = src->bufpos;
dst->reply_bytes = src->reply_bytes;
}
/* Return true if the specified client has pending reply buffers to write to
* the socket. */
// 如果指定的client的回复缓冲区中还有数据,则返回真,表示可以写socket
int clientHasPendingReplies(client *c) {
return c->bufpos || listLength(c->reply);
}
#define MAX_ACCEPTS_PER_CALL 1000
// TCP连接处理程序,创建一个client的连接状态
static void acceptCommonHandler(int fd, int flags, char *ip) {
client *c;
// 创建一个新的client
if ((c = createClient(fd)) == NULL) {
serverLog(LL_WARNING,
"Error registering fd event for the new client: %s (fd=%d)",
strerror(errno),fd);
close(fd); /* May be already closed, just ignore errors */
return;
}
/* If maxclient directive is set and this is one client more... close the
* connection. Note that we create the client instead to check before
* for this condition, since now the socket is already set in non-blocking
* mode and we can send an error for free using the Kernel I/O */
// 如果新的client超过server规定的maxclients的限制,那么想新client的fd写入错误信息,关闭该client
// 先创建client,在进行数量检查,是因为更好的写入错误信息
if (listLength(server.clients) > server.maxclients) {
char *err = "-ERR max number of clients reached\r\n";
/* That's a best effort error message, don't check write errors */
if (write(c->fd,err,strlen(err)) == -1) {
/* Nothing to do, Just to avoid the warning... */
}
// 更新拒接连接的个数
server.stat_rejected_conn++;
freeClient(c);
return;
}
/* If the server is running in protected mode (the default) and there
* is no password set, nor a specific interface is bound, we don't accept
* requests from non loopback interfaces. Instead we try to explain the
* user what to do to fix it if needed. */
// 如果服务器正在以保护模式运行(默认),且没有设置密码,也没有绑定指定的接口,我们就不接受非回环接口的请求。相反,如果需要,我们会尝试解释用户如何解决问题
if (server.protected_mode &&
server.bindaddr_count == 0 &&
server.requirepass == NULL &&
!(flags & CLIENT_UNIX_SOCKET) &&
ip != NULL)
{
if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) {
char *err =
"-DENIED Redis is running in protected mode because protected "
"mode is enabled, no bind address was specified, no "
"authentication password is requested to clients. In this mode "
"connections are only accepted from the loopback interface. "
"If you want to connect from external computers to Redis you "
"may adopt one of the following solutions: "
"1) Just disable protected mode sending the command "
"'CONFIG SET protected-mode no' from the loopback interface "
"by connecting to Redis from the same host the server is "
"running, however MAKE SURE Redis is not publicly accessible "
"from internet if you do so. Use CONFIG REWRITE to make this "
"change permanent. "
"2) Alternatively you can just disable the protected mode by "
"editing the Redis configuration file, and setting the protected "
"mode option to 'no', and then restarting the server. "
"3) If you started the server manually just for testing, restart "
"it with the '--protected-mode no' option. "
"4) Setup a bind address or an authentication password. "
"NOTE: You only need to do one of the above things in order for "
"the server to start accepting connections from the outside.\r\n";
if (write(c->fd,err,strlen(err)) == -1) {
/* Nothing to do, Just to avoid the warning... */
}
// 更新拒接连接的个数
server.stat_rejected_conn++;
freeClient(c);
return;
}
}
// 更新连接的数量
server.stat_numconnections++;
// 更新client状态的标志
c->flags |= flags;
}
// 创建一个TCP的连接处理程序
void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cport, cfd, max = MAX_ACCEPTS_PER_CALL; //最大一个处理1000次连接
char cip[NET_IP_STR_LEN];
UNUSED(el);
UNUSED(mask);
UNUSED(privdata);
while(max--) {
// accept接受client的连接
cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
if (cfd == ANET_ERR) {
if (errno != EWOULDBLOCK)
serverLog(LL_WARNING,
"Accepting client connection: %s", server.neterr);
return;
}
// 打印连接的日志
serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport);
// 创建一个连接状态的client
acceptCommonHandler(cfd,0,cip);
}
}
// 创建一个本地连接处理程序
void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cfd, max = MAX_ACCEPTS_PER_CALL;
UNUSED(el);
UNUSED(mask);
UNUSED(privdata);
while(max--) {
// accept接受client的连接
cfd = anetUnixAccept(server.neterr, fd);
if (cfd == ANET_ERR) {
if (errno != EWOULDBLOCK)
serverLog(LL_WARNING,
"Accepting client connection: %s", server.neterr);
return;
}
serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket);
// 创建一个本地连接状态的client
acceptCommonHandler(cfd,CLIENT_UNIX_SOCKET,NULL);
}
}
// 释放client的参数列表
static void freeClientArgv(client *c) {
int j;
for (j = 0; j < c->argc; j++)
decrRefCount(c->argv[j]);
c->argc = 0;
c->cmd = NULL;
}
/* Close all the slaves connections. This is useful in chained replication
* when we resync with our own master and want to force all our slaves to
* resync with us as well. */
// 关闭所有从节点服务器的连接,强制从节点服务器进行重新同步操作
void disconnectSlaves(void) {
// 遍历服务器的从节点链表,释放
while (listLength(server.slaves)) {
listNode *ln = listFirst(server.slaves);
freeClient((client*)ln->value);
}
}
/* Remove the specified client from global lists where the client could
* be referenced, not including the Pub/Sub channels.
* This is used by freeClient() and replicationCacheMaster(). */
// 从client所有保存各种client状态的链表中删除指定的client
void unlinkClient(client *c) {
listNode *ln;
/* If this is marked as current client unset it. */
// 如果指定的client被被标记为用于崩溃报告的client,则删除
if (server.current_client == c) server.current_client = NULL;
/* Certain operations must be done only if the client has an active socket.
* If the client was already unlinked or if it's a "fake client" the
* fd is already set to -1. */
// 指定的client不是伪client,或不是已经删除的client
if (c->fd != -1) {
/* Remove from the list of active clients. */
// 从client链表中找到地址
ln = listSearchKey(server.clients,c);
serverAssert(ln != NULL);
// 删除当前client的节点
listDelNode(server.clients,ln);
/* Unregister async I/O handlers and close the socket. */
// 从文件事件中删除对该client的fd的监听
aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
// 释放文件描述符
close(c->fd);
c->fd = -1;
}
/* Remove from the list of pending writes if needed. */
// 如果client还有输出的数据,但是没有设置写处理程序
if (c->flags & CLIENT_PENDING_WRITE) {
// 要写或者安装写处理程序的client链表找到当前client
ln = listSearchKey(server.clients_pending_write,c);
serverAssert(ln != NULL);
// 删除当前client的节点
listDelNode(server.clients_pending_write,ln);
// 取消标志
c->flags &= ~CLIENT_PENDING_WRITE;
}
/* When client was just unblocked because of a blocking operation,
* remove it from the list of unblocked clients. */
// 如果指定的client是非阻塞的
if (c->flags & CLIENT_UNBLOCKED) {
// 则从非阻塞的client链表中找到并删除
ln = listSearchKey(server.unblocked_clients,c);