forked from agentic-review-benchmarks/redis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster_asm.c
More file actions
3477 lines (2998 loc) · 133 KB
/
cluster_asm.c
File metadata and controls
3477 lines (2998 loc) · 133 KB
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
/* cluster_asm.c -- Atomic slot migration implementation for cluster
*
* Copyright (c) 2025-Present, Redis Ltd.
* All rights reserved.
*
* Licensed under your choice of (a) the Redis Source Available License 2.0
* (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
* GNU Affero General Public License v3 (AGPLv3).
*/
#include "server.h"
#include "cluster.h"
#include "functions.h"
#include "cluster_asm.h"
#include "cluster_slot_stats.h"
#define ASM_IMPORT (1 << 1)
#define ASM_MIGRATE (1 << 2)
#define ASM_DEBUG_TRIM_DEFAULT 0
#define ASM_DEBUG_TRIM_NONE 1
#define ASM_DEBUG_TRIM_BG 2
#define ASM_DEBUG_TRIM_ACTIVE 3
#define ASM_AOF_MIN_ITEMS_PER_KEY 512 /* Minimum number of items per key to use AOF format encoding */
typedef struct asmTask {
sds id; /* Task ID */
int operation; /* Either ASM_IMPORT or ASM_MIGRATE */
slotRangeArray *slots; /* List of slot ranges for this migration task */
int state; /* Current state of the task */
int dest_state; /* Destination node's main state (approximate) */
char source[CLUSTER_NAMELEN]; /* Source node name */
char dest[CLUSTER_NAMELEN]; /* Destination node name */
clusterNode *source_node; /* Source node */
connection *main_channel_conn; /* Main channel connection */
connection *rdb_channel_conn; /* RDB channel connection */
int rdb_channel_state; /* State of the RDB channel */
unsigned long long dest_offset; /* Destination offset */
unsigned long long source_offset; /* Source offset */
int cross_slot_during_propagating; /* If cross-slot commands are encountered during propagating */
int stream_eof_during_streaming; /* If STREAM-EOF is received during streaming buffer */
replDataBuf sync_buffer; /* Buffer for the stream */
client *main_channel_client; /* Client for the main channel on the source side */
client *rdb_channel_client; /* Client for the RDB channel on the source side */
long long retry_count; /* Number of retries for this task */
mstime_t create_time; /* Task creation time */
mstime_t start_time; /* Task start time */
mstime_t end_time; /* Task end time */
mstime_t paused_time; /* The time when the slot writes were paused */
mstime_t dest_slots_snapshot_time; /* The time when the destination starts applying the slot snapshot */
mstime_t dest_accum_applied_time; /* The time when the destination finishes applying the accumulated buffer */
sds error; /* Error message for this task */
redisOpArray *pre_snapshot_module_cmds; /* Module commands to be propagated at the beginning of slot migration */
} asmTask;
struct asmManager {
list *tasks; /* List of asmTask to be processed */
list *archived_tasks; /* List of archived asmTask */
list *pending_trim_jobs; /* List of pending trim jobs (due to write pause) */
list *active_trim_jobs; /* List of active trim jobs */
slotRangeArrayIter *active_trim_it; /* Iterator of the current active trim job */
size_t sync_buffer_peak; /* Peak size of sync buffer */
asmTask *master_task; /* The task that is currently active on the master */
/* Fail point injection for debugging */
int debug_failed_channel; /* Channel where the task failed */
int debug_failed_state; /* State where the task failed */
int debug_trim_method; /* Method to trim the buffer */
int debug_active_trim_delay; /* Sleep before trimming each key */
/* Active trim stats */
unsigned long long active_trim_started; /* Number of times active trim was started */
unsigned long long active_trim_completed; /* Number of times active trim was completed */
unsigned long long active_trim_cancelled; /* Number of times active trim was cancelled */
unsigned long long active_trim_current_job_keys; /* Total number of keys to trim in the current job */
unsigned long long active_trim_current_job_trimmed; /* Number of keys trimmed in the current job */
};
enum asmState {
/* Common state */
ASM_NONE = 0,
ASM_CONNECTING,
ASM_AUTH_REPLY,
ASM_CANCELED,
ASM_FAILED,
ASM_COMPLETED,
/* Import state */
ASM_SEND_HANDSHAKE,
ASM_HANDSHAKE_REPLY,
ASM_SEND_SYNCSLOTS,
ASM_SYNCSLOTS_REPLY,
ASM_INIT_RDBCHANNEL,
ASM_ACCUMULATE_BUF,
ASM_READY_TO_STREAM,
ASM_STREAMING_BUF,
ASM_WAIT_STREAM_EOF,
ASM_TAKEOVER,
/* Migrate state */
ASM_WAIT_RDBCHANNEL,
ASM_WAIT_BGSAVE_START,
ASM_SEND_BULK_AND_STREAM,
ASM_SEND_STREAM,
ASM_HANDOFF_PREP,
ASM_HANDOFF,
ASM_STREAM_EOF,
/* RDB channel state */
ASM_RDBCHANNEL_REQUEST,
ASM_RDBCHANNEL_REPLY,
ASM_RDBCHANNEL_TRANSFER,
};
enum asmChannel {
ASM_IMPORT_MAIN_CHANNEL = 1, /* Main channel for the import task */
ASM_IMPORT_RDB_CHANNEL, /* RDB channel for the import task */
ASM_MIGRATE_MAIN_CHANNEL, /* Main channel for the migrate task */
ASM_MIGRATE_RDB_CHANNEL /* RDB channel for the migrate task */
};
/* Global ASM manager */
struct asmManager *asmManager = NULL;
/* replication.c */
char *sendCommand(connection *conn, ...);
char *sendCommandArgv(connection *conn, int argc, char **argv, size_t *argv_lens);
char *receiveSynchronousResponse(connection *conn);
ConnectionType *connTypeOfReplication(void);
int startBgsaveForReplication(int mincapa, int req);
void createReplicationBacklogIfNeeded(void);
/* cluster.c */
void createDumpPayload(rio *payload, robj *o, robj *key, int dbid, int skip_checksum);
/* cluster_asm.c */
static void asmStartImportTask(asmTask *task);
static void asmTaskCancel(asmTask *task, const char *reason);
static void asmSyncBufferReadFromConn(connection *conn);
static void propagateTrimSlots(slotRangeArray *slots);
void asmTrimJobSchedule(slotRangeArray *slots);
void asmTrimJobProcessPending(void);
void asmTriggerActiveTrim(slotRangeArray *slots);
void asmActiveTrimEnd(void);
int asmIsAnyTrimJobOverlaps(slotRangeArray *slots);
void asmTrimSlotsIfNotOwned(slotRangeArray *slots);
void asmNotifyStateChange(asmTask *task, int event);
void asmInit(void) {
asmManager = zcalloc(sizeof(*asmManager));
asmManager->tasks = listCreate();
asmManager->archived_tasks = listCreate();
asmManager->pending_trim_jobs = listCreate();
asmManager->sync_buffer_peak = 0;
asmManager->master_task = NULL;
asmManager->debug_failed_channel = 0;
asmManager->debug_failed_state = 0;
asmManager->debug_trim_method = ASM_DEBUG_TRIM_DEFAULT;
asmManager->debug_active_trim_delay = 0;
asmManager->active_trim_jobs = listCreate();
asmManager->active_trim_started = 0;
asmManager->active_trim_completed = 0;
asmManager->active_trim_cancelled = 0;
listSetFreeMethod(asmManager->active_trim_jobs, slotRangeArrayFreeGeneric);
}
char *asmTaskStateToString(int state) {
switch (state) {
case ASM_NONE: return "none";
case ASM_CONNECTING: return "connecting";
case ASM_AUTH_REPLY: return "auth-reply";
case ASM_CANCELED: return "canceled";
case ASM_FAILED: return "failed";
case ASM_COMPLETED: return "completed";
/* Import state */
case ASM_SEND_HANDSHAKE: return "send-handshake";
case ASM_HANDSHAKE_REPLY: return "handshake-reply";
case ASM_SEND_SYNCSLOTS: return "send-syncslots";
case ASM_SYNCSLOTS_REPLY: return "syncslots-reply";
case ASM_INIT_RDBCHANNEL: return "init-rdbchannel";
case ASM_ACCUMULATE_BUF: return "accumulate-buffer";
case ASM_READY_TO_STREAM: return "ready-to-stream";
case ASM_STREAMING_BUF: return "streaming-buffer";
case ASM_WAIT_STREAM_EOF: return "wait-stream-eof";
case ASM_TAKEOVER: return "takeover";
/* Migrate state */
case ASM_WAIT_RDBCHANNEL: return "wait-rdbchannel";
case ASM_WAIT_BGSAVE_START: return "wait-bgsave-start";
case ASM_SEND_BULK_AND_STREAM: return "send-bulk-and-stream";
case ASM_SEND_STREAM: return "send-stream";
case ASM_HANDOFF_PREP: return "handoff-prep";
case ASM_HANDOFF: return "handoff";
case ASM_STREAM_EOF: return "stream-eof";
/* RDB channel state */
case ASM_RDBCHANNEL_REQUEST: return "rdbchannel-request";
case ASM_RDBCHANNEL_REPLY: return "rdbchannel-reply";
case ASM_RDBCHANNEL_TRANSFER: return "rdbchannel-transfer";
default: return "unknown";
}
serverAssert(0); /* Unreachable */
}
const char *asmChannelToString(int channel) {
switch (channel) {
case ASM_IMPORT_MAIN_CHANNEL: return "import-main-channel";
case ASM_IMPORT_RDB_CHANNEL: return "import-rdb-channel";
case ASM_MIGRATE_MAIN_CHANNEL: return "migrate-main-channel";
case ASM_MIGRATE_RDB_CHANNEL: return "migrate-rdb-channel";
default: return "unknown";
}
}
int asmDebugSetFailPoint(char * channel, char *state) {
if (!asmManager) {
serverLog(LL_WARNING, "ASM manager is not initialized");
return C_ERR;
}
asmManager->debug_failed_channel = 0;
asmManager->debug_failed_state = 0;
if (!channel && !state) return C_ERR;
if (sdslen(channel) == 0 && sdslen(state) == 0) {
serverLog(LL_WARNING, "ASM fail point is cleared");
return C_OK;
}
for (int i = ASM_IMPORT_MAIN_CHANNEL; i <= ASM_MIGRATE_RDB_CHANNEL; i++) {
if (!strcasecmp(channel, asmChannelToString(i))) {
asmManager->debug_failed_channel = i;
break;
}
}
if (asmManager->debug_failed_channel == 0) return C_ERR;
for (int i = ASM_NONE; i <= ASM_RDBCHANNEL_TRANSFER; i++) {
if (!strcasecmp(state, asmTaskStateToString(i))) {
asmManager->debug_failed_state = i;
break;
}
}
if (asmManager->debug_failed_state == 0) return C_ERR;
serverLog(LL_NOTICE, "ASM fail point set: channel=%s, state=%s", channel, state);
return C_OK;
}
int asmDebugSetTrimMethod(const char *method, int active_trim_delay) {
if (!asmManager) {
serverLog(LL_WARNING, "ASM manager is not initialized");
return C_ERR;
}
int prev = asmManager->debug_trim_method;
if (!strcasecmp(method, "default")) asmManager->debug_trim_method = ASM_DEBUG_TRIM_DEFAULT;
else if (!strcasecmp(method, "none")) asmManager->debug_trim_method = ASM_DEBUG_TRIM_NONE;
else if (!strcasecmp(method, "bg")) asmManager->debug_trim_method = ASM_DEBUG_TRIM_BG;
else if (!strcasecmp(method, "active")) asmManager->debug_trim_method = ASM_DEBUG_TRIM_ACTIVE;
else return C_ERR;
/* If we are switching from none to default, delete all the keys in the
* slots we don't own */
if (prev == ASM_DEBUG_TRIM_NONE && asmManager->debug_trim_method != ASM_DEBUG_TRIM_NONE) {
for (int i = 0; i < CLUSTER_SLOTS; i++)
if (!clusterIsMySlot(i))
clusterDelKeysInSlot(i, 0);
}
asmManager->debug_active_trim_delay = active_trim_delay;
serverLog(LL_NOTICE, "ASM trim method was set=%s, active_trim_delay=%d", method, active_trim_delay);
return C_OK;
}
int asmDebugIsFailPointActive(int channel, int state) {
if (!asmManager) return 0; /* ASM manager not initialized */
if (asmManager->debug_failed_channel == channel && asmManager->debug_failed_state == state) {
serverLog(LL_NOTICE, "ASM fail point active: channel=%s, state=%s",
asmChannelToString(channel), asmTaskStateToString(state));
return 1;
}
return 0;
}
sds asmCatInfoString(sds info) {
int active_tasks = 0;
listIter li;
listNode *ln;
listRewind(asmManager->tasks, &li);
while ((ln = listNext(&li)) != NULL) {
asmTask *task = listNodeValue(ln);
if (task->operation == ASM_IMPORT ||
(task->operation == ASM_MIGRATE && task->state != ASM_FAILED))
{
active_tasks++;
}
}
return sdscatprintf(info ? info : sdsempty(),
"cluster_slot_migration_active_tasks:%d\r\n"
"cluster_slot_migration_active_trim_running:%lu\r\n"
"cluster_slot_migration_active_trim_current_job_keys:%llu\r\n"
"cluster_slot_migration_active_trim_current_job_trimmed:%llu\r\n"
"cluster_slot_migration_stats_active_trim_started:%llu\r\n"
"cluster_slot_migration_stats_active_trim_completed:%llu\r\n"
"cluster_slot_migration_stats_active_trim_cancelled:%llu\r\n",
active_tasks,
listLength(asmManager->active_trim_jobs),
asmManager->active_trim_current_job_keys,
asmManager->active_trim_current_job_trimmed,
asmManager->active_trim_started,
asmManager->active_trim_completed,
asmManager->active_trim_cancelled);
}
void asmTaskReset(asmTask *task) {
task->state = ASM_NONE;
task->dest_state = ASM_NONE;
task->rdb_channel_state = ASM_NONE;
task->main_channel_conn = NULL;
task->rdb_channel_conn = NULL;
task->dest_offset = 0;
task->source_offset = 0;
task->stream_eof_during_streaming = 0;
task->cross_slot_during_propagating = 0;
replDataBufInit(&task->sync_buffer);
task->main_channel_client = NULL;
task->rdb_channel_client = NULL;
task->paused_time = 0;
task->dest_slots_snapshot_time = 0;
task->dest_accum_applied_time = 0;
task->pre_snapshot_module_cmds = NULL;
}
asmTask *asmTaskCreate(const char *task_id) {
asmTask *task = zcalloc(sizeof(*task));
task->error = sdsempty();
asmTaskReset(task);
task->slots = NULL;
task->source_node = NULL;
task->retry_count = 0;
task->create_time = server.mstime;
task->start_time = -1;
task->end_time = -1;
if (task_id) {
task->id = sdsnew(task_id);
} else {
task->id = sdsnewlen(NULL, CLUSTER_NAMELEN);
getRandomHexChars(task->id, CLUSTER_NAMELEN);
}
return task;
}
void asmTaskFree(asmTask *task) {
replDataBufClear(&task->sync_buffer);
sdsfree(task->id);
slotRangeArrayFree(task->slots);
sdsfree(task->error);
zfree(task);
}
/* Convert the task state to the corresponding event. */
int asmTaskStateToEvent(asmTask *task) {
if (task->operation == ASM_IMPORT) {
if (task->state == ASM_COMPLETED) return ASM_EVENT_IMPORT_COMPLETED;
else if (task->state == ASM_FAILED) return ASM_EVENT_IMPORT_FAILED;
else return ASM_EVENT_IMPORT_STARTED;
} else {
if (task->state == ASM_COMPLETED) return ASM_EVENT_MIGRATE_COMPLETED;
else if (task->state == ASM_FAILED) return ASM_EVENT_MIGRATE_FAILED;
else return ASM_EVENT_MIGRATE_STARTED;
}
}
/* Serialize ASM task information into a string for transmission to replicas.
* Format: "task_id:source_node:dest_node:operation:state:slot_ranges"
* Where slot_ranges is in the format "1000-2000 3000-4000 ..." */
sds asmTaskSerialize(asmTask *task) {
sds serialized = sdsempty();
/* Add task ID */
serialized = sdscatprintf(serialized, "%s:", task->id);
/* Add source node ID (40 chars) */
serialized = sdscatlen(serialized, task->source, CLUSTER_NAMELEN);
serialized = sdscat(serialized, ":");
/* Add destination node ID (40 chars) */
serialized = sdscatlen(serialized, task->dest, CLUSTER_NAMELEN);
serialized = sdscat(serialized, ":");
/* Add operation type */
serialized = sdscatprintf(serialized, "%s:", task->operation == ASM_IMPORT ?
"import" : "migrate");
/* Add current state */
serialized = sdscatprintf(serialized, "%s:", asmTaskStateToString(task->state));
/* Add slot ranges sds */
sds slots_str = slotRangeArrayToString(task->slots);
serialized = sdscatprintf(serialized, "%s", slots_str);
sdsfree(slots_str);
return serialized;
}
/* Deserialize ASM task information from a string and create a complete asmTask.
* Format: "task_id:source_node:dest_node:operation:state:slot_ranges"
* Returns a new asmTask on success, NULL on failure. */
asmTask *asmTaskDeserialize(sds data) {
int count, idx = 0;
asmTask *task = NULL;
if (!data || sdslen(data) == 0) return NULL;
sds *parts = sdssplitlen(data, sdslen(data), ":", 1, &count);
if (count < 6) goto err;
/* Parse task ID */
if (sdslen(parts[idx]) == 0) goto err;
task = asmTaskCreate(parts[idx]);
if (!task) goto err;
idx++;
/* Parse source node ID */
if (sdslen(parts[idx]) != CLUSTER_NAMELEN) goto err;
memcpy(task->source, parts[idx], CLUSTER_NAMELEN);
idx++;
/* Parse destination node ID */
if (sdslen(parts[idx]) != CLUSTER_NAMELEN) goto err;
memcpy(task->dest, parts[idx], CLUSTER_NAMELEN);
idx++;
/* Parse operation type */
if (!strcasecmp(parts[idx], "import")) {
task->operation = ASM_IMPORT;
} else if (!strcasecmp(parts[idx], "migrate")) {
task->operation = ASM_MIGRATE;
} else {
goto err;
}
idx++;
/* Parse state */
task->state = ASM_NONE; /* Default state */
for (int state = ASM_NONE; state <= ASM_RDBCHANNEL_TRANSFER; state++) {
if (!strcasecmp(parts[idx], asmTaskStateToString(state))) {
task->state = state;
break;
}
}
idx++;
/* Parse slot ranges */
task->slots = slotRangeArrayFromString(parts[idx]);
if (!task->slots) goto err;
idx++;
/* Ignore any extra fields for future compatibility */
sdsfreesplitres(parts, count);
return task;
err:
if (task) asmTaskFree(task);
sdsfreesplitres(parts, count);
return NULL;
}
/* Notify replicas about ASM task information to maintain consistency during
* slot migration. This function sends a CLUSTER SYNCSLOTS CONF ASM-TASK command
* to all connected replicas with the serialized task information. */
void asmNotifyReplicasStateChange(struct asmTask *task) {
if (!server.cluster_enabled || !clusterNodeIsMaster(getMyClusterNode())) return;
/* Do not propagate migrate task to replicas, as replicas never migrate data. */
if (task->operation == ASM_MIGRATE) return;
/* Create command arguments for CLUSTER SYNCSLOTS CONF ASM-TASK */
robj *argv[5];
argv[0] = createStringObject("CLUSTER", 7);
argv[1] = createStringObject("SYNCSLOTS", 9);
argv[2] = createStringObject("CONF", 4);
argv[3] = createStringObject("ASM-TASK", 8);
argv[4] = createObject(OBJ_STRING, asmTaskSerialize(task));
/* Send the command to all replicas */
replicationFeedSlaves(server.slaves, -1, argv, 5);
/* Clean up command objects */
for (int i = 0; i < 5; i++) {
decrRefCount(argv[i]);
}
}
/* Dump the active import ASM task information. */
sds asmDumpActiveImportTask(void) {
if (!server.cluster_enabled) return NULL;
/* For replica, dump the master active task. */
if (clusterNodeIsSlave(getMyClusterNode()) &&
asmManager->master_task &&
asmManager->master_task->state != ASM_FAILED &&
asmManager->master_task->state != ASM_COMPLETED)
{
return asmTaskSerialize(asmManager->master_task);
}
/* For master, dump the first active task. */
if (!asmManager || listLength(asmManager->tasks) == 0) return NULL;
asmTask *task = listNodeValue(listFirst(asmManager->tasks));
if (task->operation == ASM_MIGRATE) return NULL;
if (task->state == ASM_NONE || task->state == ASM_FAILED ||
task->state == ASM_COMPLETED) return NULL;
return asmTaskSerialize(task);
}
size_t asmGetPeakSyncBufferSize(void) {
if (!asmManager) return 0;
/* Compute peak sync buffer usage. The current task's peak may not
* reflect in asmManager->sync_buffer_peak immediately. */
size_t peak = asmManager->sync_buffer_peak;
asmTask *task = listFirst(asmManager->tasks) ?
listNodeValue(listFirst(asmManager->tasks)) : NULL;
if (task && task->operation == ASM_IMPORT)
peak = max(task->sync_buffer.peak, asmManager->sync_buffer_peak);
return peak;
}
size_t asmGetImportInputBufferSize(void) {
if (!asmManager || listLength(asmManager->tasks) == 0) return 0;
asmTask *task = listNodeValue(listFirst(asmManager->tasks));
if (task->operation == ASM_IMPORT)
return task->sync_buffer.mem_used;
return 0;
}
size_t asmGetMigrateOutputBufferSize(void) {
if (!asmManager || listLength(asmManager->tasks) == 0) return 0;
asmTask *task = listNodeValue(listFirst(asmManager->tasks));
if (task->operation == ASM_MIGRATE && task->main_channel_client)
return getClientOutputBufferMemoryUsage(task->main_channel_client);
return 0;
}
/* Returns the ASM task with the given ID, or NULL if no such task exists. */
static asmTask *asmLookupTaskAt(list *tasks, const char *id) {
listIter li;
listNode *ln;
listRewind(tasks, &li);
while ((ln = listNext(&li)) != NULL) {
asmTask *task = listNodeValue(ln);
if (!strcmp(task->id, id)) return task;
}
return NULL;
}
/* Returns the ASM task with the given ID, or NULL if no such task exists. */
asmTask *asmLookupTaskById(const char *id) {
return asmLookupTaskAt(asmManager->tasks, id);
}
/* Returns the ASM task that is identical to the given slot range array, or NULL
* if no such task exists. */
asmTask *asmLookupTaskBySlotRangeArray(slotRangeArray *slots) {
listIter li;
listNode *ln;
listRewind(asmManager->tasks, &li);
while ((ln = listNext(&li)) != NULL) {
asmTask *task = listNodeValue(ln);
if (slotRangeArrayIsEqual(task->slots, slots))
return task;
}
return NULL;
}
/* Returns the slot range array for the given task ID */
slotRangeArray *asmTaskGetSlotRanges(const char *task_id) {
asmTask *task = NULL;
if (!task_id || (task = asmLookupTaskById(task_id)) == NULL) return NULL;
return task->slots;
}
/* Returns 1 if the slot range array overlaps with the given slot range. */
static int slotRangeArrayOverlaps(slotRangeArray *slots, slotRange *req) {
for (int i = 0; i < slots->num_ranges; i++) {
slotRange *sr = &slots->ranges[i];
if (sr->start <= req->end && sr->end >= req->start)
return 1;
}
return 0;
}
/* Returns 1 if the two slot range arrays overlap, 0 otherwise. */
static int slotRangeArraysOverlap(slotRangeArray *slots1, slotRangeArray *slots2) {
for (int i = 0; i < slots1->num_ranges; i++) {
slotRange *sr1 = &slots1->ranges[i];
if (slotRangeArrayOverlaps(slots2, sr1)) return 1;
}
return 0;
}
/* Returns the ASM task that overlaps with the given slot range, or NULL if
* no such task exists. */
static asmTask *lookupAsmTaskBySlotRange(slotRange *req) {
listIter li;
listNode *ln;
listRewind(asmManager->tasks, &li);
while ((ln = listNext(&li)) != NULL) {
asmTask *task = listNodeValue(ln);
if (slotRangeArrayOverlaps(task->slots, req))
return task;
}
return NULL;
}
/* Validates the given slot ranges for a migration task:
* - Ensures the current node is a master.
* - Verifies all slots are in a STABLE state.
* - Checks that slot ranges are well-formed and non-overlapping.
* - Confirms all slots belong to a single source node.
* - Confirms no ongoing import task that overlaps with the slot ranges.
*
* Returns the source node if validation succeeds.
* Otherwise, returns NULL and sets 'err' variable. */
static clusterNode *validateImportSlotRanges(slotRangeArray *slots, sds *err, asmTask *current) {
clusterNode *source = NULL;
*err = NULL;
/* Ensure this is a master node */
if (!clusterNodeIsMaster(getMyClusterNode())) {
*err = sdsnew("slot migration not allowed on replica.");
goto out;
}
/* Ensure no manual migration is in progress. */
for (int i = 0; i < CLUSTER_SLOTS; i++) {
if (getImportingSlotSource(i) != NULL ||
getMigratingSlotDest(i) != NULL)
{
*err = sdsnew("all slot states must be STABLE to start a slot migration task.");
goto out;
}
}
for (int i = 0; i < slots->num_ranges; i++) {
slotRange *sr = &slots->ranges[i];
/* Ensure no import task overlaps with this slot range.
* Skip check current task that is running for this slot range. */
asmTask *task = lookupAsmTaskBySlotRange(sr);
if (task && task != current && task->operation == ASM_IMPORT) {
*err = sdscatprintf(sdsempty(),
"overlapping import exists for slot range: %d-%d",
sr->start, sr->end);
goto out;
}
/* Validate if we can start migration task for this slot range. */
for (int j = sr->start; j <= sr->end; j++) {
clusterNode *node = getNodeBySlot(j);
if (node == NULL) {
*err = sdscatprintf(sdsempty(), "slot has no owner: %d", j);
goto out;
}
if (!source) {
source = node;
} else if (source != node) {
*err = sdsnew("slots belong to different source nodes");
goto out;
}
}
}
out:
return *err ? NULL : source;
}
/* Returns 1 if a task with the specified operation is in progress, 0 otherwise. */
static int asmTaskInProgress(int operation) {
listIter li;
listNode *ln;
if (!asmManager || listLength(asmManager->tasks) == 0) return 0;
listRewind(asmManager->tasks, &li);
while ((ln = listNext(&li)) != NULL) {
asmTask *task = listNodeValue(ln);
if (task->operation == operation) return 1;
}
return 0;
}
/* Returns 1 if a migrate task is in progress, 0 otherwise. */
int asmMigrateInProgress(void) {
return asmTaskInProgress(ASM_MIGRATE);
}
/* Returns 1 if an import task is in progress, 0 otherwise. */
int asmImportInProgress(void) {
return asmTaskInProgress(ASM_IMPORT);
}
/* Returns 1 if the task is in a state where it can receive replication stream
* for the slot range, 0 otherwise. */
inline static int asmCanFeedMigrationClient(asmTask *task) {
return task->operation == ASM_MIGRATE &&
!task->cross_slot_during_propagating &&
(task->state == ASM_SEND_BULK_AND_STREAM ||
task->state == ASM_SEND_STREAM ||
task->state == ASM_HANDOFF_PREP);
}
/* Feed the migration client with the replication stream for the slot range. */
void asmFeedMigrationClient(robj **argv, int argc) {
asmTask *task = NULL;
if (server.cluster_enabled == 0 || listLength(asmManager->tasks) == 0)
return;
/* Check if there is a migrate task that can receive replication stream. */
task = listNodeValue(listFirst(asmManager->tasks));
if (!asmCanFeedMigrationClient(task)) return;
/* Ensure all arguments are converted to string encoding if necessary,
* since getSlotFromCommand expects them to be string-encoded.
* Generally the arguments are string-encoded, but we may rewrite
* the command arguments to integer encoding. */
for (int i = 0; i < argc; i++) {
if (!sdsEncodedObject(argv[i])) {
serverAssert(argv[i]->encoding == OBJ_ENCODING_INT);
robj *old = argv[i];
argv[i] = createStringObjectFromLongLongWithSds((long)old->ptr);
decrRefCount(old);
}
}
/* Check if the command belongs to the slot range. */
struct redisCommand *cmd = lookupCommand(argv, argc);
serverAssert(cmd);
int slot = getSlotFromCommand(cmd, argv, argc);
/* If the command does not have keys, skip it now.
* SELECT is not propagated, since we only support a single db in cluster mode.
* MULTI/EXEC is not needed, since transaction semantics are unnecessary
* before the slot handoff.
* FUNCTION subcommands should be executed on all nodes, so here we skip it,
* and even propagating them may cause an error when executing.
*
* NOTICE: if some keyless commands should be propagated to the destination,
* we should identify them here and send. */
if (slot == INVALID_CLUSTER_SLOT) return;
/* Generally we reject cross-slot commands before executing, but module may
* replicate this kind of command, so we check again. To guarantee data
* consistency, we cancel the task if we encounter a cross-slot command. */
if (slot == CLUSTER_CROSSSLOT) {
/* We cannot cancel the task directly here, since it may lead to a recursive
* call: asmTaskCancel() --> moduleFireServerEvent() --> moduleFreeContext()
* --> postExecutionUnitOperations() --> propagateNow(). Even worse, this
* could result in propagating pending commands to the replication stream twice.
* To avoid this, we simply set a flag here, cancel the task in beforeSleep. */
task->cross_slot_during_propagating = 1;
return;
}
/* Check if the slot belongs to the task's slot range. */
slotRange sr = {slot, slot};
if (!slotRangeArrayOverlaps(task->slots, &sr)) return;
if (unlikely(asmDebugIsFailPointActive(ASM_MIGRATE_MAIN_CHANNEL, task->state)))
freeClientAsync(task->main_channel_client);
/* Feed main channel with the command. */
client *c = task->main_channel_client;
size_t prev_bytes = getNormalClientPendingReplyBytes(c);
addReplyArrayLen(c, argc);
for (int i = 0; i < argc; i++)
addReplyBulk(c, argv[i]);
/* Update the task's source offset to reflect the bytes sent. */
task->source_offset += (getNormalClientPendingReplyBytes(c) - prev_bytes);
}
asmTask *asmCreateImportTask(const char *task_id, slotRangeArray *slots, sds *err) {
clusterNode *source;
*err = NULL;
/* Validate that the slot ranges are valid and that migration can be
* initiated for them. */
source = validateImportSlotRanges(slots, err, NULL);
if (!source)
return NULL;
if (source == getMyClusterNode()) {
*err = sdsnew("this node is already the owner of the slot range");
return NULL;
}
/* Only support a single task at a time now. */
if (listLength(asmManager->tasks) != 0) {
asmTask *current = listNodeValue(listFirst(asmManager->tasks));
if (current->state == ASM_FAILED) {
/* We can create a new import task only if the current one is failed,
* cancel the failed task to create a new one. */
asmTaskCancel(current, "new import requested");
} else {
*err = sdsnew("another ASM task is already in progress");
return NULL;
}
}
/* There should be no task in progress. */
serverAssert(listLength(asmManager->tasks) == 0);
/* Create a slot migration task */
asmTask *task = asmTaskCreate(task_id);
task->slots = slotRangeArrayDup(slots);
task->state = ASM_NONE;
task->operation = ASM_IMPORT;
task->source_node = source;
memcpy(task->source, clusterNodeGetName(source), CLUSTER_NAMELEN);
memcpy(task->dest, getMyClusterId(), CLUSTER_NAMELEN);
listAddNodeTail(asmManager->tasks, task);
sds slots_str = slotRangeArrayToString(slots);
serverLog(LL_NOTICE, "Import task %s created: src=%.40s, dest=%.40s, slots=%s",
task->id, task->source, task->dest, slots_str);
sdsfree(slots_str);
return task;
}
/* CLUSTER MIGRATION IMPORT <start-slot end-slot [start-slot end-slot ...]>
*
* Sent by operator to the destination node to start the migration. */
static void clusterMigrationCommandImport(client *c) {
/* Validate slot range arg count */
int remaining = c->argc - 3;
if (remaining == 0 || remaining % 2 != 0) {
addReplyErrorArity(c);
return;
}
slotRangeArray *slots = parseSlotRangesOrReply(c, c->argc, 3);
if (!slots) return;
sds err = NULL;
asmTask *task = asmCreateImportTask(NULL, slots, &err);
slotRangeArrayFree(slots);
if (!task) {
addReplyErrorSds(c, err);
return;
}
addReplyBulkCString(c, task->id);
}
/* CLUSTER MIGRATION CANCEL [ID <task-id> | ALL]
* - Reply: Number of cancelled tasks
*
* Cancels import tasks that overlap with the specified slot ranges.
* Multiple tasks may be cancelled. */
static void clusterMigrationCommandCancel(client *c) {
sds task_id = NULL;
int num_cancelled = 0;
/* Validate slot range arg count */
if (c->argc != 4 && c->argc != 5) {
addReplyErrorArity(c);
return;
}
if (!strcasecmp(c->argv[3]->ptr, "id")) {
if (c->argc != 5) {
addReplyErrorArity(c);
return;
}
task_id = c->argv[4]->ptr;
} else if (!strcasecmp(c->argv[3]->ptr, "all")) {
if (c->argc != 4) {
addReplyErrorArity(c);
return;
}
} else {
addReplyError(c, "unknown argument");
return;
}
num_cancelled = clusterAsmCancel(task_id, "user request");
addReplyLongLong(c, num_cancelled);
}
/* Reply with the status of the task. */
static void replyTaskStatus(client *c, asmTask *task) {
mstime_t p = 0;
addReplyMapLen(c, 12);
addReplyBulkCString(c, "id");
addReplyBulkCString(c, task->id);
addReplyBulkCString(c, "slots");
addReplyBulkSds(c, slotRangeArrayToString(task->slots));
addReplyBulkCString(c, "source");
addReplyBulkCBuffer(c, task->source, CLUSTER_NAMELEN);
addReplyBulkCString(c, "dest");
addReplyBulkCBuffer(c, task->dest, CLUSTER_NAMELEN);
addReplyBulkCString(c, "operation");
addReplyBulkCString(c, task->operation == ASM_IMPORT ? "import" : "migrate");
addReplyBulkCString(c, "state");
addReplyBulkCString(c, asmTaskStateToString(task->state));
addReplyBulkCString(c, "last_error");
addReplyBulkCBuffer(c, task->error, sdslen(task->error));
addReplyBulkCString(c, "retries");
addReplyLongLong(c, task->retry_count);
addReplyBulkCString(c, "create_time");
addReplyLongLong(c, task->create_time);
addReplyBulkCString(c, "start_time");
addReplyLongLong(c, task->start_time);
addReplyBulkCString(c, "end_time");
addReplyLongLong(c, task->end_time);
if (task->operation == ASM_MIGRATE && task->state == ASM_COMPLETED)
p = task->end_time - task->paused_time;
addReplyBulkCString(c, "write_pause_ms");
addReplyLongLong(c, p);
}
/* CLUSTER MIGRATION STATUS [ID <task-id> | ALL]
* - Reply: Array of atomic slot migration tasks */
static void clusterMigrationCommandStatus(client *c) {
listIter li;
listNode *ln;
if (c->argc != 4 && c->argc != 5) {
addReplyErrorArity(c);
return;
}
if (!strcasecmp(c->argv[3]->ptr, "id")) {
if (c->argc != 5) {
addReplyErrorArity(c);
return;
}
sds id = c->argv[4]->ptr;
asmTask *task = asmLookupTaskAt(asmManager->tasks, id);
if (!task) task = asmLookupTaskAt(asmManager->archived_tasks, id);
if (!task) {
addReplyArrayLen(c, 0);
return;
}
addReplyArrayLen(c, 1);
replyTaskStatus(c, task);
} else if (!strcasecmp(c->argv[3]->ptr, "all")) {
if (c->argc != 4) {
addReplyErrorArity(c);
return;
}
addReplyArrayLen(c, listLength(asmManager->tasks) +
listLength(asmManager->archived_tasks));
listRewind(asmManager->tasks, &li);
while ((ln = listNext(&li)) != NULL)
replyTaskStatus(c, listNodeValue(ln));
listRewind(asmManager->archived_tasks, &li);
while ((ln = listNext(&li)) != NULL)
replyTaskStatus(c, listNodeValue(ln));
} else {
addReplyError(c, "unknown argument");
return;
}
}
/* CLUSTER MIGRATION
* <IMPORT <start-slot end-slot [start-slot end-slot ...]> |
* STATUS [ID <task-id> | ALL] |
* CANCEL [ID <task-id> | ALL]>
*/
void clusterMigrationCommand(client *c) {
if (c->argc < 4) {
addReplyErrorArity(c);
return;
}
if (strcasecmp(c->argv[2]->ptr, "import") == 0) {
clusterMigrationCommandImport(c);
} else if (strcasecmp(c->argv[2]->ptr, "status") == 0) {