/
applier.cc
1210 lines (1111 loc) · 33.3 KB
/
applier.cc
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 2010-2016, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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
* <COPYRIGHT HOLDER> 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 "applier.h"
#include <msgpuck.h>
#include "xlog.h"
#include "fiber.h"
#include "fiber_cond.h"
#include "coio.h"
#include "coio_buf.h"
#include "wal.h"
#include "xrow.h"
#include "replication.h"
#include "iproto_constants.h"
#include "version.h"
#include "trigger.h"
#include "xrow_io.h"
#include "error.h"
#include "session.h"
#include "cfg.h"
#include "schema.h"
#include "txn.h"
#include "box.h"
#include "scoped_guard.h"
STRS(applier_state, applier_STATE);
static inline void
applier_set_state(struct applier *applier, enum applier_state state)
{
applier->state = state;
say_debug("=> %s", applier_state_strs[state] +
strlen("APPLIER_"));
trigger_run_xc(&applier->on_state, applier);
}
/**
* Write a nice error message to log file on SocketError or ClientError
* in applier_f().
*/
static inline void
applier_log_error(struct applier *applier, struct error *e)
{
uint32_t errcode = box_error_code(e);
if (applier->last_logged_errcode == errcode)
return;
switch (applier->state) {
case APPLIER_CONNECT:
say_info("can't connect to master");
break;
case APPLIER_CONNECTED:
case APPLIER_READY:
say_info("can't join/subscribe");
break;
case APPLIER_AUTH:
say_info("failed to authenticate");
break;
case APPLIER_SYNC:
case APPLIER_FOLLOW:
case APPLIER_INITIAL_JOIN:
case APPLIER_FINAL_JOIN:
say_info("can't read row");
break;
default:
break;
}
error_log(e);
switch (errcode) {
case ER_LOADING:
case ER_CFG:
case ER_ACCESS_DENIED:
case ER_NO_SUCH_USER:
case ER_SYSTEM:
case ER_UNKNOWN_REPLICA:
case ER_PASSWORD_MISMATCH:
say_info("will retry every %.2lf second",
replication_reconnect_interval());
break;
default:
break;
}
applier->last_logged_errcode = errcode;
}
/**
* A helper function which switches the applier to FOLLOW state
* if it has synchronized with its master.
*/
static inline void
applier_check_sync(struct applier *applier)
{
/*
* Stay 'orphan' until appliers catch up with
* the remote vclock at the time of SUBSCRIBE
* and the lag is less than configured.
*/
if (applier->state == APPLIER_SYNC &&
applier->lag <= replication_sync_lag &&
vclock_compare(&applier->remote_vclock_at_subscribe,
&replicaset.vclock) <= 0) {
/* Applier is synced, switch to "follow". */
applier_set_state(applier, APPLIER_FOLLOW);
}
}
/*
* Fiber function to write vclock to replication master.
* To track connection status, replica answers master
* with encoded vclock. In addition to DML requests,
* master also sends heartbeat messages every
* replication_timeout seconds (introduced in 1.7.7).
* On such requests replica also responds with vclock.
*/
static int
applier_writer_f(va_list ap)
{
struct applier *applier = va_arg(ap, struct applier *);
struct ev_io io;
coio_create(&io, applier->io.fd);
while (!fiber_is_cancelled()) {
/*
* Tarantool >= 1.7.7 sends periodic heartbeat
* messages so we don't need to send ACKs every
* replication_timeout seconds any more.
*/
if (applier->version_id >= version_id(1, 7, 7))
fiber_cond_wait_timeout(&applier->writer_cond,
TIMEOUT_INFINITY);
else
fiber_cond_wait_timeout(&applier->writer_cond,
replication_timeout);
/*
* A writer fiber is going to be awaken after a commit or
* a heartbeat message. So this is an appropriate place to
* update an applier status because the applier state could
* yield and doesn't fit into a commit trigger.
*/
applier_check_sync(applier);
/* Send ACKs only when in FOLLOW mode ,*/
if (applier->state != APPLIER_SYNC &&
applier->state != APPLIER_FOLLOW)
continue;
try {
struct xrow_header xrow;
xrow_encode_vclock(&xrow, &replicaset.vclock);
coio_write_xrow(&io, &xrow);
} catch (SocketError *e) {
/*
* There is no point trying to send ACKs if
* the master closed its end - we would only
* spam the log - so exit immediately.
*/
if (e->get_errno() == EPIPE)
break;
/*
* Do not exit, if there is a network error,
* the reader fiber will reconnect for us
* and signal our cond afterwards.
*/
e->log();
} catch (Exception *e) {
/*
* Out of memory encoding the message, ignore
* and try again after an interval.
*/
e->log();
}
fiber_gc();
}
return 0;
}
static int
apply_initial_join_row(struct xrow_header *row)
{
struct txn *txn = txn_begin();
if (txn == NULL)
return -1;
struct request request;
xrow_decode_dml(row, &request, dml_request_key_map(row->type));
struct space *space = space_cache_find(request.space_id);
if (space == NULL)
goto rollback;
/* no access checks here - applier always works with admin privs */
if (space_apply_initial_join_row(space, &request))
goto rollback;
int rc;
rc = txn_commit(txn);
if (rc < 0)
return -1;
fiber_gc();
return rc;
rollback:
txn_rollback(txn);
fiber_gc();
return -1;
}
/**
* Process a no-op request.
*
* A no-op request does not affect any space, but it
* promotes vclock and is written to WAL.
*/
static int
process_nop(struct request *request)
{
assert(request->type == IPROTO_NOP);
struct txn *txn = in_txn();
if (txn_begin_stmt(txn, NULL) != 0)
return -1;
return txn_commit_stmt(txn, request);
}
static int
apply_row(struct xrow_header *row)
{
struct request request;
if (xrow_decode_dml(row, &request, dml_request_key_map(row->type)) != 0)
return -1;
if (request.type == IPROTO_NOP)
return process_nop(&request);
struct space *space = space_cache_find(request.space_id);
if (space == NULL)
return -1;
if (box_process_rw(&request, space, NULL) != 0) {
say_error("error applying row: %s", request_str(&request));
return -1;
}
return 0;
}
static int
apply_final_join_row(struct xrow_header *row)
{
struct txn *txn = txn_begin();
if (txn == NULL)
return -1;
if (apply_row(row) != 0) {
txn_rollback(txn);
fiber_gc();
return -1;
}
if (txn_commit(txn) != 0)
return -1;
fiber_gc();
return 0;
}
/**
* Connect to a remote host and authenticate the client.
*/
void
applier_connect(struct applier *applier)
{
struct ev_io *coio = &applier->io;
struct ibuf *ibuf = &applier->ibuf;
if (coio->fd >= 0)
return;
char greetingbuf[IPROTO_GREETING_SIZE];
struct xrow_header row;
struct uri *uri = &applier->uri;
/*
* coio_connect() stores resolved address to \a &applier->addr
* on success. &applier->addr_len is a value-result argument which
* must be initialized to the size of associated buffer (addrstorage)
* before calling coio_connect(). Since coio_connect() performs
* DNS resolution under the hood it is theoretically possible that
* applier->addr_len will be different even for same uri.
*/
applier->addr_len = sizeof(applier->addrstorage);
applier_set_state(applier, APPLIER_CONNECT);
coio_connect(coio, uri, &applier->addr, &applier->addr_len);
assert(coio->fd >= 0);
coio_readn(coio, greetingbuf, IPROTO_GREETING_SIZE);
applier->last_row_time = ev_monotonic_now(loop());
/* Decode instance version and name from greeting */
struct greeting greeting;
if (greeting_decode(greetingbuf, &greeting) != 0)
tnt_raise(LoggedError, ER_PROTOCOL, "Invalid greeting");
if (strcmp(greeting.protocol, "Binary") != 0) {
tnt_raise(LoggedError, ER_PROTOCOL,
"Unsupported protocol for replication");
}
if (applier->version_id != greeting.version_id) {
say_info("remote master %s at %s running Tarantool %u.%u.%u",
tt_uuid_str(&greeting.uuid),
sio_strfaddr(&applier->addr, applier->addr_len),
version_id_major(greeting.version_id),
version_id_minor(greeting.version_id),
version_id_patch(greeting.version_id));
}
/* Save the remote instance version and UUID on connect. */
applier->uuid = greeting.uuid;
applier->version_id = greeting.version_id;
/* Don't display previous error messages in box.info.replication */
diag_clear(&fiber()->diag);
/*
* Send an IPROTO_VOTE request to fetch the master's ballot
* before proceeding to "join". It will be used for leader
* election on bootstrap.
*/
xrow_encode_vote(&row);
coio_write_xrow(coio, &row);
coio_read_xrow(coio, ibuf, &row);
if (row.type == IPROTO_OK) {
xrow_decode_ballot_xc(&row, &applier->ballot);
} else try {
xrow_decode_error_xc(&row);
} catch (ClientError *e) {
if (e->errcode() != ER_UNKNOWN_REQUEST_TYPE)
e->raise();
/*
* Master isn't aware of IPROTO_VOTE request.
* It's OK - we can proceed without it.
*/
}
applier_set_state(applier, APPLIER_CONNECTED);
/* Detect connection to itself */
if (tt_uuid_is_equal(&applier->uuid, &INSTANCE_UUID))
tnt_raise(ClientError, ER_CONNECTION_TO_SELF);
/* Perform authentication if user provided at least login */
if (!uri->login)
goto done;
/* Authenticate */
applier_set_state(applier, APPLIER_AUTH);
xrow_encode_auth_xc(&row, greeting.salt, greeting.salt_len, uri->login,
uri->login_len,
uri->password != NULL ? uri->password : "",
uri->password_len);
coio_write_xrow(coio, &row);
coio_read_xrow(coio, ibuf, &row);
applier->last_row_time = ev_monotonic_now(loop());
if (row.type != IPROTO_OK)
xrow_decode_error_xc(&row); /* auth failed */
/* auth succeeded */
say_info("authenticated");
done:
applier_set_state(applier, APPLIER_READY);
}
/**
* Execute and process JOIN request (bootstrap the instance).
*/
static void
applier_join(struct applier *applier)
{
/* Send JOIN request */
struct ev_io *coio = &applier->io;
struct ibuf *ibuf = &applier->ibuf;
struct xrow_header row;
xrow_encode_join_xc(&row, &INSTANCE_UUID);
coio_write_xrow(coio, &row);
/**
* Tarantool < 1.7.0: if JOIN is successful, there is no "OK"
* response, but a stream of rows from checkpoint.
*/
if (applier->version_id >= version_id(1, 7, 0)) {
/* Decode JOIN response */
coio_read_xrow(coio, ibuf, &row);
if (iproto_type_is_error(row.type)) {
xrow_decode_error_xc(&row); /* re-throw error */
} else if (row.type != IPROTO_OK) {
tnt_raise(ClientError, ER_UNKNOWN_REQUEST_TYPE,
(uint32_t) row.type);
}
/*
* Start vclock. The vclock of the checkpoint
* the master is sending to the replica.
* Used to initialize the replica's initial
* vclock in bootstrap_from_master()
*/
xrow_decode_vclock_xc(&row, &replicaset.vclock);
}
applier_set_state(applier, APPLIER_INITIAL_JOIN);
/*
* Receive initial data.
*/
uint64_t row_count = 0;
while (true) {
coio_read_xrow(coio, ibuf, &row);
applier->last_row_time = ev_monotonic_now(loop());
if (iproto_type_is_dml(row.type)) {
if (apply_initial_join_row(&row) != 0)
diag_raise();
if (++row_count % 100000 == 0)
say_info("%.1fM rows received", row_count / 1e6);
} else if (row.type == IPROTO_OK) {
if (applier->version_id < version_id(1, 7, 0)) {
/*
* This is the start vclock if the
* server is 1.6. Since we have
* not initialized replication
* vclock yet, do it now. In 1.7+
* this vclock is not used.
*/
xrow_decode_vclock_xc(&row, &replicaset.vclock);
}
break; /* end of stream */
} else if (iproto_type_is_error(row.type)) {
xrow_decode_error_xc(&row); /* rethrow error */
} else {
tnt_raise(ClientError, ER_UNKNOWN_REQUEST_TYPE,
(uint32_t) row.type);
}
}
say_info("initial data received");
applier_set_state(applier, APPLIER_FINAL_JOIN);
/*
* Tarantool < 1.7.0: there is no "final join" stage.
* Proceed to "subscribe" and do not finish bootstrap
* until replica id is received.
*/
if (applier->version_id < version_id(1, 7, 0))
return;
/*
* Receive final data.
*/
while (true) {
coio_read_xrow(coio, ibuf, &row);
applier->last_row_time = ev_monotonic_now(loop());
if (iproto_type_is_dml(row.type)) {
vclock_follow_xrow(&replicaset.vclock, &row);
if (apply_final_join_row(&row) != 0)
diag_raise();
if (++row_count % 100000 == 0)
say_info("%.1fM rows received", row_count / 1e6);
} else if (row.type == IPROTO_OK) {
/*
* Current vclock. This is not used now,
* ignore.
*/
break; /* end of stream */
} else if (iproto_type_is_error(row.type)) {
xrow_decode_error_xc(&row); /* rethrow error */
} else {
tnt_raise(ClientError, ER_UNKNOWN_REQUEST_TYPE,
(uint32_t) row.type);
}
}
say_info("final data received");
applier_set_state(applier, APPLIER_JOINED);
applier_set_state(applier, APPLIER_READY);
}
/**
* A helper struct to link xrow objects in a list.
*/
struct applier_tx_row {
/* Next transaction row. */
struct stailq_entry next;
/* xrow_header struct for the current transaction row. */
struct xrow_header row;
};
static struct applier_tx_row *
applier_read_tx_row(struct applier *applier)
{
struct ev_io *coio = &applier->io;
struct ibuf *ibuf = &applier->ibuf;
struct applier_tx_row *tx_row = (struct applier_tx_row *)
region_alloc(&fiber()->gc, sizeof(struct applier_tx_row));
if (tx_row == NULL)
tnt_raise(OutOfMemory, sizeof(struct applier_tx_row),
"region", "struct applier_tx_row");
struct xrow_header *row = &tx_row->row;
double timeout = replication_disconnect_timeout();
/*
* Tarantool < 1.7.7 does not send periodic heartbeat
* messages so we can't assume that if we haven't heard
* from the master for quite a while the connection is
* broken - the master might just be idle.
*/
if (applier->version_id < version_id(1, 7, 7))
coio_read_xrow(coio, ibuf, row);
else
coio_read_xrow_timeout_xc(coio, ibuf, row, timeout);
applier->lag = ev_now(loop()) - row->tm;
applier->last_row_time = ev_monotonic_now(loop());
return tx_row;
}
/**
* Read one transaction from network using applier's input buffer.
* Transaction rows are placed onto fiber gc region.
* We could not use applier input buffer to store rows because
* rpos is adjusted as xrow is decoded and the corresponding
* network input space is reused for the next xrow.
*/
static void
applier_read_tx(struct applier *applier, struct stailq *rows)
{
int64_t tsn = 0;
stailq_create(rows);
do {
struct applier_tx_row *tx_row = applier_read_tx_row(applier);
struct xrow_header *row = &tx_row->row;
if (iproto_type_is_error(row->type))
xrow_decode_error_xc(row);
/* Replication request. */
if (row->replica_id == REPLICA_ID_NIL ||
row->replica_id >= VCLOCK_MAX) {
/*
* A safety net, this can only occur
* if we're fed a strangely broken xlog.
*/
tnt_raise(ClientError, ER_UNKNOWN_REPLICA,
int2str(row->replica_id),
tt_uuid_str(&REPLICASET_UUID));
}
if (tsn == 0) {
/*
* Transaction id must be derived from the log sequence
* number of the first row in the transaction.
*/
tsn = row->tsn;
if (row->lsn != tsn)
tnt_raise(ClientError, ER_PROTOCOL,
"Transaction id must be equal to "
"LSN of the first row in the "
"transaction.");
}
if (tsn != row->tsn)
tnt_raise(ClientError, ER_UNSUPPORTED,
"replication",
"interleaving transactions");
assert(row->bodycnt <= 1);
if (row->bodycnt == 1 && !row->is_commit) {
/*
* Save row body to gc region.
* Not done for single-statement
* transactions knowing that the input
* buffer will not be used while the
* transaction is applied.
*/
void *new_base = region_alloc(&fiber()->gc,
row->body->iov_len);
if (new_base == NULL)
tnt_raise(OutOfMemory, row->body->iov_len,
"region", "xrow body");
memcpy(new_base, row->body->iov_base,
row->body->iov_len);
/* Adjust row body pointers. */
row->body->iov_base = new_base;
}
stailq_add_tail(rows, &tx_row->next);
} while (!stailq_last_entry(rows, struct applier_tx_row,
next)->row.is_commit);
}
static void
applier_txn_rollback_cb(struct trigger *trigger, void *event)
{
(void) trigger;
/* Setup shared applier diagnostic area. */
diag_set(ClientError, ER_WAL_IO);
diag_move(&fiber()->diag, &replicaset.applier.diag);
/* Broadcast the rollback event across all appliers. */
trigger_run(&replicaset.applier.on_rollback, event);
/* Rollback applier vclock to the committed one. */
vclock_copy(&replicaset.applier.vclock, &replicaset.vclock);
}
static void
applier_txn_commit_cb(struct trigger *trigger, void *event)
{
(void) trigger;
/* Broadcast the commit event across all appliers. */
trigger_run(&replicaset.applier.on_commit, event);
}
/**
* Apply all rows in the rows queue as a single transaction.
*
* Return 0 for success or -1 in case of an error.
*/
static int
applier_apply_tx(struct stailq *rows)
{
struct xrow_header *first_row = &stailq_first_entry(rows,
struct applier_tx_row, next)->row;
struct replica *replica = replica_by_id(first_row->replica_id);
/*
* In a full mesh topology, the same set of changes
* may arrive via two concurrently running appliers.
* Hence we need a latch to strictly order all changes
* that belong to the same server id.
*/
struct latch *latch = (replica ? &replica->order_latch :
&replicaset.applier.order_latch);
latch_lock(latch);
if (vclock_get(&replicaset.applier.vclock,
first_row->replica_id) >= first_row->lsn) {
latch_unlock(latch);
return 0;
}
/**
* Explicitly begin the transaction so that we can
* control fiber->gc life cycle and, in case of apply
* conflict safely access failed xrow object and allocate
* IPROTO_NOP on gc.
*/
struct txn *txn = txn_begin();
struct applier_tx_row *item;
if (txn == NULL) {
latch_unlock(latch);
return -1;
}
stailq_foreach_entry(item, rows, next) {
struct xrow_header *row = &item->row;
int res = apply_row(row);
if (res != 0) {
struct error *e = diag_last_error(diag_get());
/*
* In case of ER_TUPLE_FOUND error and enabled
* replication_skip_conflict configuration
* option, skip applying the foreign row and
* replace it with NOP in the local write ahead
* log.
*/
if (e->type == &type_ClientError &&
box_error_code(e) == ER_TUPLE_FOUND &&
replication_skip_conflict) {
diag_clear(diag_get());
row->type = IPROTO_NOP;
row->bodycnt = 0;
res = apply_row(row);
}
}
if (res != 0)
goto rollback;
}
/*
* We are going to commit so it's a high time to check if
* the current transaction has non-local effects.
*/
if (txn_is_distributed(txn)) {
/*
* A transaction mixes remote and local rows.
* Local rows must be replicated back, which
* doesn't make sense since the master likely has
* new changes which local rows may overwrite.
* Raise an error.
*/
diag_set(ClientError, ER_UNSUPPORTED,
"Replication", "distributed transactions");
goto rollback;
}
/* We are ready to submit txn to wal. */
struct trigger *on_rollback, *on_commit;
on_rollback = (struct trigger *)region_alloc(&txn->region,
sizeof(struct trigger));
on_commit = (struct trigger *)region_alloc(&txn->region,
sizeof(struct trigger));
if (on_rollback == NULL || on_commit == NULL)
goto rollback;
trigger_create(on_rollback, applier_txn_rollback_cb, NULL, NULL);
txn_on_rollback(txn, on_rollback);
trigger_create(on_commit, applier_txn_commit_cb, NULL, NULL);
txn_on_commit(txn, on_commit);
if (txn_write(txn) < 0)
goto fail;
/* Transaction was sent to journal so promote vclock. */
vclock_follow(&replicaset.applier.vclock,
first_row->replica_id, first_row->lsn);
latch_unlock(latch);
return 0;
rollback:
txn_rollback(txn);
fail:
latch_unlock(latch);
fiber_gc();
return -1;
}
/*
* A trigger to update an applier state after a replication commit.
*/
static void
applier_on_commit(struct trigger *trigger, void *event)
{
(void) event;
struct applier *applier = (struct applier *)trigger->data;
fiber_cond_signal(&applier->writer_cond);
}
/*
* A trigger to update an applier state after a replication rollback.
*/
static void
applier_on_rollback(struct trigger *trigger, void *event)
{
(void) event;
struct applier *applier = (struct applier *)trigger->data;
/* Setup a shared error. */
if (!diag_is_empty(&replicaset.applier.diag)) {
diag_add_error(&applier->diag,
diag_last_error(&replicaset.applier.diag));
}
/* Stop the applier fiber. */
fiber_cancel(applier->reader);
}
/**
* Execute and process SUBSCRIBE request (follow updates from a master).
*/
static void
applier_subscribe(struct applier *applier)
{
/* Send SUBSCRIBE request */
struct ev_io *coio = &applier->io;
struct ibuf *ibuf = &applier->ibuf;
struct xrow_header row;
struct tt_uuid cluster_id = uuid_nil;
struct vclock vclock;
vclock_create(&vclock);
vclock_copy(&vclock, &replicaset.vclock);
/*
* Stop accepting local rows coming from a remote
* instance as soon as local WAL starts accepting writes.
*/
uint32_t id_filter = box_is_orphan() ? 0 : 1 << instance_id;
xrow_encode_subscribe_xc(&row, &REPLICASET_UUID, &INSTANCE_UUID,
&vclock, id_filter);
coio_write_xrow(coio, &row);
/* Read SUBSCRIBE response */
if (applier->version_id >= version_id(1, 6, 7)) {
coio_read_xrow(coio, ibuf, &row);
if (iproto_type_is_error(row.type)) {
xrow_decode_error_xc(&row); /* error */
} else if (row.type != IPROTO_OK) {
tnt_raise(ClientError, ER_PROTOCOL,
"Invalid response to SUBSCRIBE");
}
/*
* In case of successful subscribe, the server
* responds with its current vclock.
*
* Tarantool > 2.1.1 also sends its cluster id to
* the replica, and replica has to check whether
* its and master's cluster ids match.
*/
vclock_create(&applier->remote_vclock_at_subscribe);
xrow_decode_subscribe_response_xc(&row, &cluster_id,
&applier->remote_vclock_at_subscribe);
/*
* If master didn't send us its cluster id
* assume that it has done all the checks.
* In this case cluster_id will remain zero.
*/
if (!tt_uuid_is_nil(&cluster_id) &&
!tt_uuid_is_equal(&cluster_id, &REPLICASET_UUID)) {
tnt_raise(ClientError, ER_REPLICASET_UUID_MISMATCH,
tt_uuid_str(&cluster_id),
tt_uuid_str(&REPLICASET_UUID));
}
say_info("subscribed");
say_info("remote vclock %s local vclock %s",
vclock_to_string(&applier->remote_vclock_at_subscribe),
vclock_to_string(&vclock));
}
/*
* Tarantool < 1.6.7:
* If there is an error in subscribe, it's sent directly
* in response to subscribe. If subscribe is successful,
* there is no "OK" response, but a stream of rows from
* the binary log.
*/
if (applier->state == APPLIER_READY) {
/*
* Tarantool < 1.7.7 does not send periodic heartbeat
* messages so we cannot enable applier synchronization
* for it without risking getting stuck in the 'orphan'
* mode until a DML operation happens on the master.
*/
if (applier->version_id >= version_id(1, 7, 7))
applier_set_state(applier, APPLIER_SYNC);
else
applier_set_state(applier, APPLIER_FOLLOW);
} else {
/*
* Tarantool < 1.7.0 sends replica id during
* "subscribe" stage. We can't finish bootstrap
* until it is received.
*/
assert(applier->state == APPLIER_FINAL_JOIN);
assert(applier->version_id < version_id(1, 7, 0));
}
/* Re-enable warnings after successful execution of SUBSCRIBE */
applier->last_logged_errcode = 0;
if (applier->version_id >= version_id(1, 7, 4)) {
/* Enable replication ACKs for newer servers */
assert(applier->writer == NULL);
char name[FIBER_NAME_MAX];
int pos = snprintf(name, sizeof(name), "applierw/");
uri_format(name + pos, sizeof(name) - pos, &applier->uri, false);
applier->writer = fiber_new_xc(name, applier_writer_f);
fiber_set_joinable(applier->writer, true);
fiber_start(applier->writer, applier);
}
applier->lag = TIMEOUT_INFINITY;
/* Register triggers to handle replication commits and rollbacks. */
struct trigger on_commit;
trigger_create(&on_commit, applier_on_commit, applier, NULL);
trigger_add(&replicaset.applier.on_commit, &on_commit);
struct trigger on_rollback;
trigger_create(&on_rollback, applier_on_rollback, applier, NULL);
trigger_add(&replicaset.applier.on_rollback, &on_rollback);
auto trigger_guard = make_scoped_guard([&] {
trigger_clear(&on_commit);
trigger_clear(&on_rollback);
});
/*
* Process a stream of rows from the binary log.
*/
while (true) {
if (applier->state == APPLIER_FINAL_JOIN &&
instance_id != REPLICA_ID_NIL) {
say_info("final data received");
applier_set_state(applier, APPLIER_JOINED);
applier_set_state(applier, APPLIER_READY);
applier_set_state(applier, APPLIER_FOLLOW);
}
struct stailq rows;
applier_read_tx(applier, &rows);
applier->last_row_time = ev_monotonic_now(loop());
/*
* In case of an heartbeat message wake a writer up
* and check applier state.
*/
if (stailq_first_entry(&rows, struct applier_tx_row,
next)->row.lsn == 0)
fiber_cond_signal(&applier->writer_cond);
else if (applier_apply_tx(&rows) != 0)
diag_raise();
if (ibuf_used(ibuf) == 0)
ibuf_reset(ibuf);
fiber_gc();
}
}
static inline void
applier_disconnect(struct applier *applier, enum applier_state state)
{
applier_set_state(applier, state);
if (applier->writer != NULL) {
fiber_cancel(applier->writer);
fiber_join(applier->writer);
applier->writer = NULL;
}
coio_close(loop(), &applier->io);
/* Clear all unparsed input. */
ibuf_reinit(&applier->ibuf);
fiber_gc();
}
static int
applier_f(va_list ap)
{
struct applier *applier = va_arg(ap, struct applier *);
/*
* Set correct session type for use in on_replace()
* triggers.
*/
struct session *session = session_create_on_demand();
if (session == NULL)
return -1;
session_set_type(session, SESSION_TYPE_APPLIER);
/* Re-connect loop */
while (!fiber_is_cancelled()) {
try {
applier_connect(applier);
if (tt_uuid_is_nil(&REPLICASET_UUID)) {
/*
* Execute JOIN if this is a bootstrap.
* The join will pause the applier
* until WAL is created.
*/
applier_join(applier);
}
applier_subscribe(applier);
/*
* subscribe() has an infinite loop which
* is stoppable only with fiber_cancel().
*/
unreachable();
return 0;
} catch (ClientError *e) {
if (e->errcode() == ER_CONNECTION_TO_SELF &&
tt_uuid_is_equal(&applier->uuid, &INSTANCE_UUID)) {
/* Connection to itself, stop applier */
applier_disconnect(applier, APPLIER_OFF);
return 0;
} else if (e->errcode() == ER_LOADING) {
/* Autobootstrap */
applier_log_error(applier, e);
applier_disconnect(applier, APPLIER_LOADING);
goto reconnect;
} else if (e->errcode() == ER_CFG ||
e->errcode() == ER_ACCESS_DENIED ||
e->errcode() == ER_NO_SUCH_USER ||
e->errcode() == ER_PASSWORD_MISMATCH) {
/* Invalid configuration */
applier_log_error(applier, e);
applier_disconnect(applier, APPLIER_LOADING);
goto reconnect;
} else if (e->errcode() == ER_SYSTEM) {
/* System error from master instance. */
applier_log_error(applier, e);
applier_disconnect(applier, APPLIER_DISCONNECTED);
goto reconnect;
} else {
/* Unrecoverable errors */
applier_log_error(applier, e);
applier_disconnect(applier, APPLIER_STOPPED);
return -1;
}