-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy patht_string.c
1212 lines (1061 loc) · 48.3 KB
/
t_string.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 <math.h> /* isnan(), isinf() */
/* Forward declarations */
/* 前向声明 */
int getGenericCommand(client *c);
/*-----------------------------------------------------------------------------
* String Commands
*----------------------------------------------------------------------------*/
/* 检查输入字符串长度,
* 是由 master 发出的命令且字符串小于限制的最大长度 512MB 返回 C_OK,否则返回 C_ERR */
static int checkStringLength(client *c, long long size) {
if (!mustObeyClient(c) && size > server.proto_max_bulk_len) {
addReplyError(c,"string exceeds maximum allowed size (proto-max-bulk-len)");
return C_ERR;
}
return C_OK;
}
/* The setGenericCommand() function implements the SET operation with different
* options and variants. This function is called in order to implement the
* following commands: SET, SETEX, PSETEX, SETNX, GETSET.
*
* 'flags' changes the behavior of the command (NX, XX or GET, see below).
*
* 'expire' represents an expire to set in form of a Redis object as passed
* by the user. It is interpreted according to the specified 'unit'.
*
* 'ok_reply' and 'abort_reply' is what the function will reply to the client
* if the operation is performed, or when it is not because of NX or
* XX flags.
*
* If ok_reply is NULL "+OK" is used.
* If abort_reply is NULL, "$-1" is used. */
/* setGenericCommand()函数使用不同的选项和变量,
* 调用此函数是为了实现以下命令:
* SET , SETEX , PSETEX , SETNX , GETSET.
*
* flags 影响函数的执行过程(NX、XX 或 GET,见下文的 define)
* flags 如何使用?以 OBJ_SET_NX 为例:
* 没设置任何标志位的时候 flags = 0,
* 设置 OBJ_SET_NX 标志则是用 flags 保存 flags 与 OBJ_SET_NX 异或结果(flags |= OBJ_SET_NX)
* 判断是否有 OBJ_SET_NX 标志,若存在该标志则 flags & OBJ_SET_NX == 1
*
* "expire" 表示给用户传递的 Redis 对象设置的过期时间,
* 过期时间单位根据 'unit' 参数进行解析。
*
* 'ok_reply' 和 'abort_reply' 是在执行操作时,
* 函数将向客户端回复的内容。
*
* 如果 ok_reply 为 NULL,则返回 "+OK"
* 如果 abort_reply 为 NULL,则返回 "-1"。
*/
#define OBJ_NO_FLAGS 0
#define OBJ_SET_NX (1<<0) /* Set if key not exists. */
#define OBJ_SET_XX (1<<1) /* Set if key exists. */
#define OBJ_EX (1<<2) /* Set if time in seconds is given */
#define OBJ_PX (1<<3) /* Set if time in ms in given */
#define OBJ_KEEPTTL (1<<4) /* Set and keep the ttl */
#define OBJ_SET_GET (1<<5) /* Set if want to get key before set */
#define OBJ_EXAT (1<<6) /* Set if timestamp in second is given */
#define OBJ_PXAT (1<<7) /* Set if timestamp in ms is given */
#define OBJ_PERSIST (1<<8) /* Set if we need to remove the ttl */
/* Forward declaration */
static int getExpireMillisecondsOrReply(client *c, robj *expire, int flags, int unit, long long *milliseconds);
void setGenericCommand(client *c, int flags, robj *key, robj *val, robj *expire, int unit, robj *ok_reply, robj *abort_reply) {
long long milliseconds = 0; /* initialized to avoid any harmness warning */
int found = 0;
int setkey_flags = 0;
/* 若命令带有设置过期功能,取出过期时间,若输入过期时间不合法返回 C_ERR ,导致报错并返回,
* 调用 getExpireMillisecondsOrReply 函数后 milliseconds 将会被赋值成毫秒过期时间,
* 注意 redis 都是以毫秒保存过期时间,若输入单位为秒则会转换为毫秒 */
if (expire && getExpireMillisecondsOrReply(c, expire, flags, unit, &milliseconds) != C_OK) {
return;
}
/* 若输入命令为 GETSET ,先执行 getGenericCommand 检查 key,
* 若 key 类型不为 string 会返回 C_ERR ,导致报错并返回 */
if (flags & OBJ_SET_GET) {
if (getGenericCommand(c) == C_ERR) return;
}
/* 若 key 存在,found = 1 */
found = (lookupKeyWrite(c->db,key) != NULL);
/* 若输入命令带有 NX 而 key 存在,或带有 XX 而 key 不存在,则在这返回 */
if ((flags & OBJ_SET_NX && found) ||
(flags & OBJ_SET_XX && !found))
{
if (!(flags & OBJ_SET_GET)) {
addReply(c, abort_reply ? abort_reply : shared.null[c->resp]);
}
return;
}
/* 设置 setkey_flags ,setkey_flags 将影响 setKey 函数的执行过程,
* 第一个是 set 命令是否带有 keepttl 可选参数,若没有将会撤销 key 的过期时间(如果有),
* 第二个是 key 是否已经存在,若不存在会在 setKey 时创建该 key ,若已经存在则重写 */
setkey_flags |= (flags & OBJ_KEEPTTL) ? SETKEY_KEEPTTL : 0;
setkey_flags |= found ? SETKEY_ALREADY_EXIST : SETKEY_DOESNT_EXIST;
/* 在数据库中设置键值 */
setKey(c,c->db,key,val,setkey_flags);
/* 脏数据 + 1,
* dirty 记录缓存对本地存储而言的数据变动次数,
* 持久化时将会削减计数(削减值为保存到本地的数据量),主动使用 SAVE 或 BGSAVE 成功保存将会清零 */
server.dirty++;
/* 发送事件通知 */
notifyKeyspaceEvent(NOTIFY_STRING,"set",key,c->db->id);
/* 如果命令要求设置过期时间,则设置它 */
if (expire) {
setExpire(c,c->db,key,milliseconds);
/* Propagate as SET Key Value PXAT millisecond-timestamp if there is
* EX/PX/EXAT/PXAT flag. */
/* 如果有 EX/PX/EXAT/PXAT 标志,
* 则修改客户端参数数组为 SET Key Value PXAT millisecond-timestamp 进行传播(传播到 AOF 或从服务器) */
robj *milliseconds_obj = createStringObjectFromLongLong(milliseconds);
rewriteClientCommandVector(c, 5, shared.set, key, val, shared.pxat, milliseconds_obj);
decrRefCount(milliseconds_obj);
notifyKeyspaceEvent(NOTIFY_GENERIC,"expire",key,c->db->id);
}
/* 命令非 GETSET ,则向客户端发送回复 */
if (!(flags & OBJ_SET_GET)) {
addReply(c, ok_reply ? ok_reply : shared.ok);
}
/* Propagate without the GET argument (Isn't needed if we had expire since in that case we completely re-written the command argv) */
/* 如果输入命令为 GETSET,
* 在没有 GET 参数的情况下进行传播(如果有 "expire" 就不要了,因为在这种情况下我们完全重新编写了命令参数数组 argv)*/
if ((flags & OBJ_SET_GET) && !expire) {
int argc = 0;
int j;
robj **argv = zmalloc((c->argc-1)*sizeof(robj*));
for (j=0; j < c->argc; j++) {
char *a = c->argv[j]->ptr;
/* Skip GET which may be repeated multiple times. */
if (j >= 3 &&
(a[0] == 'g' || a[0] == 'G') &&
(a[1] == 'e' || a[1] == 'E') &&
(a[2] == 't' || a[2] == 'T') && a[3] == '\0')
continue;
argv[argc++] = c->argv[j];
incrRefCount(c->argv[j]);
}
replaceClientCommandVector(c, argc, argv);
}
}
/*
* Extract the `expire` argument of a given GET/SET command as an absolute timestamp in milliseconds.
*
* "client" is the client that sent the `expire` argument.
* "expire" is the `expire` argument to be extracted.
* "flags" represents the behavior of the command (e.g. PX or EX).
* "unit" is the original unit of the given `expire` argument (e.g. UNIT_SECONDS).
* "milliseconds" is output argument.
*
* If return C_OK, "milliseconds" output argument will be set to the resulting absolute timestamp.
* If return C_ERR, an error reply has been added to the given client.
*/
/*
* 提取一个给定的 GET/SET 命令的 `expire` 参数,作为一个绝对的时间戳,单位是毫秒。
*
* "client" 是发送 `expire' 参数的客户端。
* "expire" 是要提取的 `expire` 参数。
* "flags" 代表该命令的行为(例如 PX 或 EX)
* "unit" 是给定的 `expire` 参数的原始单位(例如 UNIT_SECONDS)
* "milliseconds" 是输出参数。
*
* 如果返回 C_OK ,"milliseconds" 输出参数将被设置为结果的绝对时间戳。
* 如果返回 C_ERR ,一个错误回复已被添加到发送该命令的客户端。
*/
static int getExpireMillisecondsOrReply(client *c, robj *expire, int flags, int unit, long long *milliseconds) {
/* 调用 getLongLongFromObjectOrReply 后,若无报错则 milliseconds 被赋值成输入的过期时间数值 */
int ret = getLongLongFromObjectOrReply(c, expire, milliseconds, NULL);
if (ret != C_OK) {
return ret;
}
if (*milliseconds <= 0 || (unit == UNIT_SECONDS && *milliseconds > LLONG_MAX / 1000)) {
/* Negative value provided or multiplication is gonna overflow. */
/* milliseconds 为负,或超出最大限制值将导致报错并返回。 */
addReplyErrorExpireTime(c);
return C_ERR;
}
/* 若输入单位为秒,则转换为毫秒 */
if (unit == UNIT_SECONDS) *milliseconds *= 1000;
if ((flags & OBJ_PX) || (flags & OBJ_EX)) {
*milliseconds += mstime();
}
if (*milliseconds <= 0) {
/* Overflow detected. */
/* 此时发生上溢 */
addReplyErrorExpireTime(c);
return C_ERR;
}
return C_OK;
}
/* 用于在下方 parseExtendedStringArgumentsOrReply() 函数表示命令为 SET 还是 GET */
#define COMMAND_GET 0
#define COMMAND_SET 1
/*
* The parseExtendedStringArgumentsOrReply() function performs the common validation for extended
* string arguments used in SET and GET command.
*
* Get specific commands - PERSIST/DEL
* Set specific commands - XX/NX/GET
* Common commands - EX/EXAT/PX/PXAT/KEEPTTL
*
* Function takes pointers to client, flags, unit, pointer to pointer of expire obj if needed
* to be determined and command_type which can be COMMAND_GET or COMMAND_SET.
*
* If there are any syntax violations C_ERR is returned else C_OK is returned.
*
* Input flags are updated upon parsing the arguments. Unit and expire are updated if there are any
* EX/EXAT/PX/PXAT arguments. Unit is updated to millisecond if PX/PXAT is set.
*/
/*
* parseExtendedStringArgumentsOrReply()函数对SET和GET命令中使用的扩展命令进行普通验证。
*
* GET 特定的命令 - PERSIST/DEL
* SET 特定的命令 - XX/NX/GET
* 通用命令 - EX/EXAT/PX/PXAT/KEEPTTL
*
* 该函数需要指向客户端(c)、标志(flags)、单位(unit)的指针,如果需要的话,还需要指向过期时间的指针(expire)以及命令类型(command_type),
* 命令类型可以是 COMMAND_GET 或 COMMAND_SET。
*
* 如果有任何违反语法的行为,将返回 C_ERR ,否则将返回 C_OK。
*
* 在解析参数的时候,输入标志会被更新。如果有任何 EXAT/PX/PXAT 参数,单位和过期时间将被更新。
* 如果设置了 PX/PXAT ,单位将被更新为毫秒。
*/
int parseExtendedStringArgumentsOrReply(client *c, int *flags, int *unit, robj **expire, int command_type) {
int j = command_type == COMMAND_GET ? 2 : 3;
for (; j < c->argc; j++) {
char *opt = c->argv[j]->ptr;
robj *next = (j == c->argc-1) ? NULL : c->argv[j+1];
if ((opt[0] == 'n' || opt[0] == 'N') &&
(opt[1] == 'x' || opt[1] == 'X') && opt[2] == '\0' &&
!(*flags & OBJ_SET_XX) && (command_type == COMMAND_SET))
{
*flags |= OBJ_SET_NX;
} else if ((opt[0] == 'x' || opt[0] == 'X') &&
(opt[1] == 'x' || opt[1] == 'X') && opt[2] == '\0' &&
!(*flags & OBJ_SET_NX) && (command_type == COMMAND_SET))
{
*flags |= OBJ_SET_XX;
} else if ((opt[0] == 'g' || opt[0] == 'G') &&
(opt[1] == 'e' || opt[1] == 'E') &&
(opt[2] == 't' || opt[2] == 'T') && opt[3] == '\0' &&
(command_type == COMMAND_SET))
{
*flags |= OBJ_SET_GET;
} else if (!strcasecmp(opt, "KEEPTTL") && !(*flags & OBJ_PERSIST) &&
!(*flags & OBJ_EX) && !(*flags & OBJ_EXAT) &&
!(*flags & OBJ_PX) && !(*flags & OBJ_PXAT) && (command_type == COMMAND_SET))
{
*flags |= OBJ_KEEPTTL;
} else if (!strcasecmp(opt,"PERSIST") && (command_type == COMMAND_GET) &&
!(*flags & OBJ_EX) && !(*flags & OBJ_EXAT) &&
!(*flags & OBJ_PX) && !(*flags & OBJ_PXAT) &&
!(*flags & OBJ_KEEPTTL))
{
*flags |= OBJ_PERSIST;
} else if ((opt[0] == 'e' || opt[0] == 'E') &&
(opt[1] == 'x' || opt[1] == 'X') && opt[2] == '\0' &&
!(*flags & OBJ_KEEPTTL) && !(*flags & OBJ_PERSIST) &&
!(*flags & OBJ_EXAT) && !(*flags & OBJ_PX) &&
!(*flags & OBJ_PXAT) && next)
{
*flags |= OBJ_EX;
*expire = next;
j++;
} else if ((opt[0] == 'p' || opt[0] == 'P') &&
(opt[1] == 'x' || opt[1] == 'X') && opt[2] == '\0' &&
!(*flags & OBJ_KEEPTTL) && !(*flags & OBJ_PERSIST) &&
!(*flags & OBJ_EX) && !(*flags & OBJ_EXAT) &&
!(*flags & OBJ_PXAT) && next)
{
*flags |= OBJ_PX;
*unit = UNIT_MILLISECONDS;
*expire = next;
j++;
} else if ((opt[0] == 'e' || opt[0] == 'E') &&
(opt[1] == 'x' || opt[1] == 'X') &&
(opt[2] == 'a' || opt[2] == 'A') &&
(opt[3] == 't' || opt[3] == 'T') && opt[4] == '\0' &&
!(*flags & OBJ_KEEPTTL) && !(*flags & OBJ_PERSIST) &&
!(*flags & OBJ_EX) && !(*flags & OBJ_PX) &&
!(*flags & OBJ_PXAT) && next)
{
*flags |= OBJ_EXAT;
*expire = next;
j++;
} else if ((opt[0] == 'p' || opt[0] == 'P') &&
(opt[1] == 'x' || opt[1] == 'X') &&
(opt[2] == 'a' || opt[2] == 'A') &&
(opt[3] == 't' || opt[3] == 'T') && opt[4] == '\0' &&
!(*flags & OBJ_KEEPTTL) && !(*flags & OBJ_PERSIST) &&
!(*flags & OBJ_EX) && !(*flags & OBJ_EXAT) &&
!(*flags & OBJ_PX) && next)
{
*flags |= OBJ_PXAT;
*unit = UNIT_MILLISECONDS;
*expire = next;
j++;
} else {
addReplyErrorObject(c,shared.syntaxerr);
return C_ERR;
}
}
return C_OK;
}
/* SET key value [NX] [XX] [KEEPTTL] [GET] [EX <seconds>] [PX <milliseconds>]
* [EXAT <seconds-timestamp>][PXAT <milliseconds-timestamp>] */
/* 处理 set 命令的函数 */
void setCommand(client *c) {
robj *expire = NULL;
int unit = UNIT_SECONDS;
int flags = OBJ_NO_FLAGS;
if (parseExtendedStringArgumentsOrReply(c,&flags,&unit,&expire,COMMAND_SET) != C_OK) {
return;
}
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,flags,c->argv[1],c->argv[2],expire,unit,NULL,NULL);
}
/* 处理 setnx 命令的函数 */
void setnxCommand(client *c) {
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,OBJ_SET_NX,c->argv[1],c->argv[2],NULL,0,shared.cone,shared.czero);
}
/* 处理 setex 命令的函数 */
void setexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_EX,c->argv[1],c->argv[3],c->argv[2],UNIT_SECONDS,NULL,NULL);
}
/* 处理 psetex 命令的函数 */
void psetexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_PX,c->argv[1],c->argv[3],c->argv[2],UNIT_MILLISECONDS,NULL,NULL);
}
/* get 的通用实现函数 */
int getGenericCommand(client *c) {
robj *o;
/* 若查找不到该 key,向客户端发送 nil(lookupKeyReadOrReply函数中完成),返回 C_OK */
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.null[c->resp])) == NULL)
return C_OK;
/* 查找到 key ,但对应的对象类型不是 string 则 checkType 会返回 1,返回 C_ERR */
if (checkType(c,o,OBJ_STRING)) {
return C_ERR;
}
/* 向客户端回复对象的值 */
addReplyBulk(c,o);
return C_OK;
}
/* 处理 get 命令的函数 */
void getCommand(client *c) {
getGenericCommand(c);
}
/*
* GETEX <key> [PERSIST][EX seconds][PX milliseconds][EXAT seconds-timestamp][PXAT milliseconds-timestamp]
*
* The getexCommand() function implements extended options and variants of the GET command. Unlike GET
* command this command is not read-only.
*
* The default behavior when no options are specified is same as GET and does not alter any TTL.
*
* Only one of the below options can be used at a given time.
*
* 1. PERSIST removes any TTL associated with the key.
* 2. EX Set expiry TTL in seconds.
* 3. PX Set expiry TTL in milliseconds.
* 4. EXAT Same like EX instead of specifying the number of seconds representing the TTL
* (time to live), it takes an absolute Unix timestamp
* 5. PXAT Same like PX instead of specifying the number of milliseconds representing the TTL
* (time to live), it takes an absolute Unix timestamp
*
* Command would either return the bulk string, error or nil.
*/
/* GETEX <key>[PERSIST][EX seconds][PX milliseconds][EXAT seconds - timestamp][PXAT milliseconds - timestamp]。
*
* getexCommand() 函数实现了 GET 命令的扩展选项和变体。但不像 GET 命令,这个命令不是只读的。
* 没有指定选项时的默认行为与 GET 相同,不会改变任何 TTL(对象的生存时间)
*
* 在一次命令内只能使用以下选项之一
*
* 1. PERSIST 删除任何与键相关的 TTL
* 2. EX 以秒为单位设置过期 TTL
* 3. PX 以毫秒为单位设置过期的 TTL
* 4. EXAT 与 EX 作用相同,但不是指定代表TTL的秒数,而是采用一个绝对的 Unix 时间戳
*
* 5. PXAT 与 PX 作用相同,但不是指定代表TTL的毫秒数,而是采用一个绝对的 Unix 时间戳
*
* 命令将返回批量字符串、错误或 nil
*/
void getexCommand(client *c) {
robj *expire = NULL;
int unit = UNIT_SECONDS;
int flags = OBJ_NO_FLAGS;
/* 解析输入的命令字符串 */
if (parseExtendedStringArgumentsOrReply(c,&flags,&unit,&expire,COMMAND_GET) != C_OK) {
return;
}
robj *o;
/* 在数据库中查找 key ,并给 o 赋值为 key 所对应的对象,若为 NULL 则返回 */
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.null[c->resp])) == NULL)
return;
/* 检查对象类型 */
if (checkType(c,o,OBJ_STRING)) {
return;
}
/* Validate the expiration time value first */
/* 首先验证并获取过期时间值 */
long long milliseconds = 0;
if (expire && getExpireMillisecondsOrReply(c, expire, flags, unit, &milliseconds) != C_OK) {
return;
}
/* We need to do this before we expire the key or delete it */
/* 在过期或删除 key 之前,我们需要先将 value 回复给客户端 */
addReplyBulk(c,o);
/* This command is never propagated as is. It is either propagated as PEXPIRE[AT],DEL,UNLINK or PERSIST.
* This why it doesn't need special handling in feedAppendOnlyFile to convert relative expire time to absolute one. */
/* 该命令不会被原封不动地传播。它要么以 PEXPIRE[AT] 、 DEL 、 UNLINK 或 PERSIST 的形式传播 */
/* 这就是为什么它不需要在 feedAppendOnlyFile 函数中进行将相对过期时间转换成绝对过期时间的特殊处理 */
if (((flags & OBJ_PXAT) || (flags & OBJ_EXAT)) && checkAlreadyExpired(milliseconds)) {
/* When PXAT/EXAT absolute timestamp is specified, there can be a chance that timestamp
* has already elapsed so delete the key in that case. */
/*当指定 PXAT/EXAT 绝对时间戳时,有可能出现时间戳已经过期的情况,所以要删除该键 */
/* 根据 lazyfree_lazy_expire 选项设置选择异步删除或是同步删除,该选项默认为0,即选择同步删除 */
int deleted = server.lazyfree_lazy_expire ? dbAsyncDelete(c->db, c->argv[1]) :
dbSyncDelete(c->db, c->argv[1]);
serverAssert(deleted);
robj *aux = server.lazyfree_lazy_expire ? shared.unlink : shared.del;
rewriteClientCommandVector(c,2,aux,c->argv[1]);
signalModifiedKey(c, c->db, c->argv[1]);
notifyKeyspaceEvent(NOTIFY_GENERIC, "del", c->argv[1], c->db->id);
server.dirty++;
} else if (expire) {
setExpire(c,c->db,c->argv[1],milliseconds);
/* Propagate as PXEXPIREAT millisecond-timestamp if there is
* EX/PX/EXAT/PXAT flag and the key has not expired. */
/* 如果有 EX/PX/EXAT/PXAT 标志且 key 未过期,
* 则作为 pexpireat 毫秒时间戳进行传播 */
robj *milliseconds_obj = createStringObjectFromLongLong(milliseconds);
rewriteClientCommandVector(c,3,shared.pexpireat,c->argv[1],milliseconds_obj);
decrRefCount(milliseconds_obj);
signalModifiedKey(c, c->db, c->argv[1]);
notifyKeyspaceEvent(NOTIFY_GENERIC,"expire",c->argv[1],c->db->id);
server.dirty++;
/* 带 PERSIST 参数,则执行删除该 key 过期时间的操作 */
} else if (flags & OBJ_PERSIST) {
if (removeExpire(c->db, c->argv[1])) {
signalModifiedKey(c, c->db, c->argv[1]);
rewriteClientCommandVector(c, 2, shared.persist, c->argv[1]);
notifyKeyspaceEvent(NOTIFY_GENERIC,"persist",c->argv[1],c->db->id);
server.dirty++;
}
}
}
/* 处理 getdel 命令的函数 */
void getdelCommand(client *c) {
/* 先调用 getGenericCommand 函数获取值并回复客户端,再进行删除操作 */
if (getGenericCommand(c) == C_ERR) return;
int deleted = server.lazyfree_lazy_user_del ? dbAsyncDelete(c->db, c->argv[1]) :
dbSyncDelete(c->db, c->argv[1]);
if (deleted) {
/* Propagate as DEL/UNLINK command */
/* 作为 DEL/UNLINK 命令传播 */
robj *aux = server.lazyfree_lazy_user_del ? shared.unlink : shared.del;
rewriteClientCommandVector(c,2,aux,c->argv[1]);
signalModifiedKey(c, c->db, c->argv[1]);
notifyKeyspaceEvent(NOTIFY_GENERIC, "del", c->argv[1], c->db->id);
server.dirty++;
}
}
/* 处理 getset 命令的函数 */
void getsetCommand(client *c) {
/* 先调用 getGenericCommand 函数获取值并回复客户端,再进行设置操作 */
if (getGenericCommand(c) == C_ERR) return;
/* 调用 tryObjectEncoding 函数,给要设置的值选择合适的编码类型 */
c->argv[2] = tryObjectEncoding(c->argv[2]);
/* 在数据库中设置键值对 */
setKey(c,c->db,c->argv[1],c->argv[2],0);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[1],c->db->id);
server.dirty++;
/* Propagate as SET command */
/* 作为 SET 命令传播 */
rewriteClientCommandArgument(c,0,shared.set);
}
/* 处理 setrange 命令的函数 */
void setrangeCommand(client *c) {
robj *o;
long offset;
sds value = c->argv[3]->ptr;
/* 取出 offset */
if (getLongFromObjectOrReply(c,c->argv[2],&offset,NULL) != C_OK)
return;
/* offset 为负报错并返回 */
if (offset < 0) {
addReplyError(c,"offset is out of range");
return;
}
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Return 0 when setting nothing on a non-existing string */
/* 如果 o 为 NULL 且 value 长度为 0 ,向客户端回复0并返回 */
if (sdslen(value) == 0) {
addReply(c,shared.czero);
return;
}
/* Return when the resulting string exceeds allowed size */
/* 如果设置后的新字符串长度会超过长度最大值限制,则报错并返回 */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
/* 根据输入的命令参数创建一个字符串对象 */
o = createObject(OBJ_STRING,sdsnewlen(NULL, offset+sdslen(value)));
/* 将对象加入到数据库 */
dbAdd(c->db,c->argv[1],o);
} else {
size_t olen;
/* Key exists, check type */
/* Key 存在,检查类型 */
if (checkType(c,o,OBJ_STRING))
return;
/* Return existing string length when setting nothing */
/* 如果要设置的值长度为0,即什么也不会修改,直接返回已经存在的字符串值 */
olen = stringObjectLen(o);
if (sdslen(value) == 0) {
addReplyLongLong(c,olen);
return;
}
/* Return when the resulting string exceeds allowed size */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
/* Create a copy when the object is shared or encoded. */
/* 当对象被共享或编码时,创建一个副本,
* 因为我们不要去修改一个共享对象,什么是共享对象可以拉到最底下有注释 */
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
if (sdslen(value) > 0) {
/* 令原本的字符串值进行扩容 */
o->ptr = sdsgrowzero(o->ptr,offset+sdslen(value));
/* 使用 memcpy 将 value 按字节拷贝到原字符串值对应的位置(起始地址 + offset) */
memcpy((char*)o->ptr+offset,value,sdslen(value));
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,
"setrange",c->argv[1],c->db->id);
server.dirty++;
}
addReplyLongLong(c,sdslen(o->ptr));
}
/* 处理 getrange 命令的函数 */
void getrangeCommand(client *c) {
robj *o;
long long start, end;
char *str, llbuf[32];
size_t strlen;
/* 检查输入参数 start , end 是否可以转化为 long long ,可以则取出 start 和 end ,否则报错并返回 */
if (getLongLongFromObjectOrReply(c,c->argv[2],&start,NULL) != C_OK)
return;
if (getLongLongFromObjectOrReply(c,c->argv[3],&end,NULL) != C_OK)
return;
/* 检查 key 是否存在,存在就取出 key 对应的对象,之后检查对象类型是否为 string */
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptybulk)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
/* 根据不同的字符串编码,选择不同的方法做一样的事:
* str = 字符串值(value) , strlen = 字符串长度 */
if (o->encoding == OBJ_ENCODING_INT) {
str = llbuf;
strlen = ll2string(llbuf,sizeof(llbuf),(long)o->ptr);
} else {
str = o->ptr;
strlen = sdslen(str);
}
/* Convert negative indexes */
/* 检查 start 和 end 是否合法与转化负数的索引 start , end 为正数 */
if (start < 0 && end < 0 && start > end) {
addReply(c,shared.emptybulk);
return;
}
if (start < 0) start = strlen+start;
if (end < 0) end = strlen+end;
if (start < 0) start = 0;
if (end < 0) end = 0;
if ((unsigned long long)end >= strlen) end = strlen-1;
/* Precondition: end >= 0 && end < strlen, so the only condition where
* nothing can be returned is: start > end. */
/* 前提条件:end >= 0 && end < strlen,所以唯一可以返回 empty 的条件是:start > end */
if (start > end || strlen == 0) {
addReply(c,shared.emptybulk);
} else {
addReplyBulkCBuffer(c,(char*)str+start,end-start+1);
}
}
/* 处理 mget 命令的函数 */
void mgetCommand(client *c) {
int j;
addReplyArrayLen(c,c->argc-1);
/* 查找并返回所有输入键的值 */
for (j = 1; j < c->argc; j++) {
robj *o = lookupKeyRead(c->db,c->argv[j]);
if (o == NULL) {
addReplyNull(c);
} else {
if (o->type != OBJ_STRING) {
addReplyNull(c);
} else {
addReplyBulk(c,o);
}
}
}
}
/* mset 命令通用处理函数,实现 mset 和 msetnx 命令 */
void msetGenericCommand(client *c, int nx) {
int j;
/* mset 命令输入的参数个数一定是奇数,
* 例如: mset key1 value1 key2 value2 (5个),
* 如果是偶数则报错并返回 */
if ((c->argc % 2) == 0) {
addReplyErrorArity(c);
return;
}
/* Handle the NX flag. The MSETNX semantic is to return zero and don't
* set anything if at least one key already exists. */
/* 先处理 NX 标志。如果至少有一个键已经存在,msetnx 命令直接向客户端回复0并返回 */
if (nx) {
for (j = 1; j < c->argc; j += 2) {
if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
addReply(c, shared.czero);
return;
}
}
}
/* 设置每一个键值对 */
for (j = 1; j < c->argc; j += 2) {
c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
setKey(c,c->db,c->argv[j],c->argv[j+1],0);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[j],c->db->id);
}
server.dirty += (c->argc-1)/2;
addReply(c, nx ? shared.cone : shared.ok);
}
/* 处理 mset 命令的函数 */
void msetCommand(client *c) {
msetGenericCommand(c,0);
}
/* 处理 msetnx 命令的函数 */
void msetnxCommand(client *c) {
msetGenericCommand(c,1);
}
/* incr, decr 通用处理函数,
* 实现incr, incrby, decr, decrby 命令 */
void incrDecrCommand(client *c, long long incr) {
long long value, oldvalue;
robj *o, *new;
/* 1.查 key,对应的对象赋值给 o 2.检查 o 的对象类型 3.取出对象的整数值并保存到 value 中 */
o = lookupKeyWrite(c->db,c->argv[1]);
if (checkType(c,o,OBJ_STRING)) return;
if (getLongLongFromObjectOrReply(c,o,&value,NULL) != C_OK) return;
oldvalue = value;
/* 判断原值加上增量是否会超出范围,是的话报错并返回 */
if ((incr < 0 && oldvalue < 0 && incr < (LLONG_MIN-oldvalue)) ||
(incr > 0 && oldvalue > 0 && incr > (LLONG_MAX-oldvalue))) {
addReplyError(c,"increment or decrement would overflow");
return;
}
value += incr;
/* 这里的if条件需要特别说明的有两个:
* o->refcount == 1 : 对象的引用次数只有一次,即没有其他程序引用
* (value < 0 || value >= OBJ_SHARED_INTEGERS) : value 不在共享整数对象范围内,
* 实际上就是 o 没有在引用共享对象,
* 再满足了其他条件,这时我们就可以安全地直接修改 o->ptr,否则需要创建新对象
* 想了解什么是共享对象可以拉到文件最底下 */
if (o && o->refcount == 1 && o->encoding == OBJ_ENCODING_INT &&
(value < 0 || value >= OBJ_SHARED_INTEGERS) &&
value >= LONG_MIN && value <= LONG_MAX)
{
new = o;
o->ptr = (void*)((long)value);
} else {
new = createStringObjectFromLongLongForValue(value);
if (o) {
dbOverwrite(c->db,c->argv[1],new);
} else {
dbAdd(c->db,c->argv[1],new);
}
}
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrby",c->argv[1],c->db->id);
server.dirty++;
addReplyLongLong(c, value);
}
/* 处理 incr 命令的函数 */
void incrCommand(client *c) {
incrDecrCommand(c,1);
}
/* 处理 decr 命令的函数 */
void decrCommand(client *c) {
incrDecrCommand(c,-1);
}
/* 处理 incrby 命令的函数 */
void incrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
incrDecrCommand(c,incr);
}
/* 处理 decrby 命令的函数 */
void decrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
/* Overflow check: negating LLONG_MIN will cause an overflow */
/* 这里对 incr 做了个溢出判断,(不是很懂有什么必要在这里先检查,如果你知道请把括号这句删了并加上解释,谢谢!) */
if (incr == LLONG_MIN) {
addReplyError(c, "decrement would overflow");
return;
}
incrDecrCommand(c,-incr);
}
/* incrbyfloat */
/* 处理 incrbyfloat 命令的函数 */
void incrbyfloatCommand(client *c) {
long double incr, value;
robj *o, *new;
o = lookupKeyWrite(c->db,c->argv[1]);
if (checkType(c,o,OBJ_STRING)) return;
if (getLongDoubleFromObjectOrReply(c,o,&value,NULL) != C_OK ||
getLongDoubleFromObjectOrReply(c,c->argv[2],&incr,NULL) != C_OK)
return;
/* value 加上 incr 后判断 value 是否溢出 */
value += incr;
if (isnan(value) || isinf(value)) {
addReplyError(c,"increment would produce NaN or Infinity");
return;
}
/* 创建新的字符串对象 */
new = createStringObjectFromLongDouble(value,1);
/* o 存在则对该 key 对应的字符串对象用 new 进行覆盖,不存在则将 new 加入数据库 */
if (o)
dbOverwrite(c->db,c->argv[1],new);
else
dbAdd(c->db,c->argv[1],new);
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrbyfloat",c->argv[1],c->db->id);
server.dirty++;
addReplyBulk(c,new);
/* Always replicate INCRBYFLOAT as a SET command with the final value
* in order to make sure that differences in float precision or formatting
* will not create differences in replicas or after an AOF restart. */
rewriteClientCommandArgument(c,0,shared.set);
rewriteClientCommandArgument(c,2,new);
rewriteClientCommandArgument(c,3,shared.keepttl);
}
/* 处理 append 命令的函数 */
void appendCommand(client *c) {
size_t totlen;
robj *o, *append;
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Create the key */
/* key 不存在,则创建一个 */
c->argv[2] = tryObjectEncoding(c->argv[2]);
dbAdd(c->db,c->argv[1],c->argv[2]);
incrRefCount(c->argv[2]);
totlen = stringObjectLen(c->argv[2]);
} else {
/* Key exists, check type */
/* Key 存在,先检查类型 */
if (checkType(c,o,OBJ_STRING))
return;
/* "append" is an argument, so always an sds */
/* "append" 是一个输入参数,所以总是是一个 sds(redis中的字符串类型) */
append = c->argv[2];
totlen = stringObjectLen(o)+sdslen(append->ptr);
/* 检查追加字符串后的长度是否超出限制 */
if (checkStringLength(c,totlen) != C_OK)
return;
/* Append the value */
/* 执行追加操作 */
o = dbUnshareStringValue(c->db,c->argv[1],o);
o->ptr = sdscatlen(o->ptr,append->ptr,sdslen(append->ptr));
totlen = sdslen(o->ptr);
}
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"append",c->argv[1],c->db->id);
server.dirty++;
addReplyLongLong(c,totlen);
}
/* 处理 strlen 命令的函数 */
void strlenCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
/* 向客户端回复字符串对象的长度 */
addReplyLongLong(c,stringObjectLen(o));
}
/* LCS key1 key2 [LEN] [IDX] [MINMATCHLEN <len>] [WITHMATCHLEN] */
/* 处理 LCS 命令的函数(求两个字符串的最长公共子序列) */
void lcsCommand(client *c) {
uint32_t i, j;
long long minmatchlen = 0;
sds a = NULL, b = NULL;
int getlen = 0, getidx = 0, withmatchlen = 0;
robj *obja = NULL, *objb = NULL;
/* 取得 key1, key2 所对应的字符串对象 */
obja = lookupKeyRead(c->db,c->argv[1]);
objb = lookupKeyRead(c->db,c->argv[2]);
if ((obja && obja->type != OBJ_STRING) ||
(objb && objb->type != OBJ_STRING))
{
/* obja 或 objb 其中有一个对象不是 string 类型则向客户端报错 */
addReplyError(c,
"The specified keys must contain string values");
/* Don't cleanup the objects, we need to do that
* only after calling getDecodedObject(). */
/* 不要清理这些对象,我们只在调用 getDecodedObject() 之后才用做清理 */
obja = NULL;
objb = NULL;
goto cleanup;
}
/* 调用 getDecodedObject() 会把内部编码为INT类型的字符串对象转为 embstr 或 raw (用于比较字符串),
* 若字符串对象为 NULL 则创建一个空串 */
obja = obja ? getDecodedObject(obja) : createStringObject("",0);
objb = objb ? getDecodedObject(objb) : createStringObject("",0);
a = obja->ptr;
b = objb->ptr;
/* 解析可选参数 */
for (j = 3; j < (uint32_t)c->argc; j++) {
char *opt = c->argv[j]->ptr;
int moreargs = (c->argc-1) - j;
if (!strcasecmp(opt,"IDX")) {
getidx = 1;
} else if (!strcasecmp(opt,"LEN")) {
getlen = 1;
} else if (!strcasecmp(opt,"WITHMATCHLEN")) {
withmatchlen = 1;
} else if (!strcasecmp(opt,"MINMATCHLEN") && moreargs) {
if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)
!= C_OK) goto cleanup;
if (minmatchlen < 0) minmatchlen = 0;
j++;
} else {
addReplyErrorObject(c,shared.syntaxerr);
goto cleanup;
}
}
/* Complain if the user passed ambiguous parameters. */
/* 如果用户传递了不明确的参数,则通过错误回复提醒用户
* 这里指同时用了 len 和 idx 参数 */
if (getlen && getidx) {
addReplyError(c,
"If you want both the length and indexes, please just use IDX.");
goto cleanup;
}
/* Detect string truncation or later overflows. */
/* 检测字符串长度对于 LCS (最长公共子序列)是否超出长度限制 */
if (sdslen(a) >= UINT32_MAX-1 || sdslen(b) >= UINT32_MAX-1) {
addReplyError(c, "String too long for LCS");