forked from tarantool/tarantool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
box.cc
5785 lines (5278 loc) · 155 KB
/
box.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 "box/box.h"
#include "trivia/config.h"
#include <sys/utsname.h>
#include <spawn.h>
#include "lua/utils.h" /* lua_hash() */
#include "fiber_pool.h"
#include <say.h>
#include <scoped_guard.h>
#include "identifier.h"
#include "iproto.h"
#include "iproto_constants.h"
#include "recovery.h"
#include "wal.h"
#include "relay.h"
#include "applier.h"
#include <rmean.h>
#include "main.h"
#include "tuple.h"
#include "tuple_format.h"
#include "session.h"
#include "schema.h"
#include "engine.h"
#include "memtx_engine.h"
#include "memtx_space.h"
#include "sysview.h"
#include "blackhole.h"
#include "service_engine.h"
#include "vinyl.h"
#include "space.h"
#include "index.h"
#include "result.h"
#include "port.h"
#include "txn.h"
#include "txn_limbo.h"
#include "user.h"
#include "cfg.h"
#include "coio.h"
#include "replication.h" /* replica */
#include "title.h"
#include "xrow.h"
#include "xrow_io.h"
#include "xstream.h"
#include "authentication.h"
#include "security.h"
#include "path_lock.h"
#include "gc.h"
#include "sql.h"
#include "systemd.h"
#include "call.h"
#include "crash.h"
#include "func.h"
#include "sequence.h"
#include "sql_stmt_cache.h"
#include "msgpack.h"
#include "raft.h"
#include "watcher.h"
#include "audit.h"
#include "trivia/util.h"
#include "version.h"
#include "mp_uuid.h"
#include "flightrec.h"
#include "wal_ext.h"
#include "mp_util.h"
#include "small/static.h"
#include "memory.h"
#include "node_name.h"
static char status[64] = "unconfigured";
/** box.stat rmean */
struct rmean *rmean_box;
double on_shutdown_trigger_timeout = 3.0;
double txn_timeout_default;
struct rlist box_on_shutdown_trigger_list =
RLIST_HEAD_INITIALIZER(box_on_shutdown_trigger_list);
const struct vclock *box_vclock = &replicaset.vclock;
const char *box_auth_type;
const char *box_ballot_event_key = "internal.ballot";
struct tt_uuid bootstrap_leader_uuid;
bool box_is_force_recovery = false;
/**
* Set if backup is in progress, i.e. box_backup_start() was
* called but box_backup_stop() hasn't been yet.
*/
static bool backup_is_in_progress;
/**
* If backup is in progress, this points to the gc reference
* object that prevents the garbage collector from deleting
* the checkpoint files that are currently being backed up.
*/
static struct gc_checkpoint_ref backup_gc;
bool box_read_ffi_is_disabled;
/**
* Counter behind box_read_ffi_is_disabled: FFI is re-enabled
* when it hits zero.
*/
static int box_read_ffi_disable_count;
/**
* The instance is in read-write mode: the local checkpoint
* and all write ahead logs are processed. For a replica,
* it also means we've successfully connected to the master
* and began receiving updates from it.
*/
static bool is_box_configured = false;
static bool is_storage_initialized = false;
static bool is_ro = true;
static fiber_cond ro_cond;
/**
* The following flag is set if the instance failed to
* synchronize to a sufficient number of replicas to form
* a quorum and so was forced to switch to read-only mode.
*/
static bool is_orphan;
/**
* Summary flag incorporating all the instance attributes,
* affecting ability to write. Currently these are:
* - is_ro;
* - is_orphan;
*/
static bool is_ro_summary = true;
/**
* The pool of fibers in the transaction processor thread
* working on incoming messages from net, wal and other
* threads.
*/
static struct fiber_pool tx_fiber_pool;
/**
* A separate endpoint for WAL wakeup messages, to
* ensure that WAL messages are delivered even
* if all fibers in tx_fiber_pool are used. Without
* this endpoint, tx thread could deadlock when there
* are too many messages in flight (gh-1892).
*/
static struct cbus_endpoint tx_prio_endpoint;
RLIST_HEAD(box_on_recovery_state);
/**
* Recovery states supported by on_recovery_state triggers.
* Are positioned in the order of appearance during initial box.cfg().
* The only exception are WAL_RECOVERED and INDEXES_BUILT, which might come in
* any order, since the moment when secondary indexes are built depends on
* box.cfg.force_recovery and box.cfg.memtx_use_mvcc_engine.
*/
enum box_recovery_state {
/**
* The node has either recovered the snapshot from the disk, received
* the snapshot from the remote master as part of initial join stage or
* has bootstrapped the cluster.
*/
RECOVERY_STATE_SNAPSHOT_RECOVERED,
/**
* The node has either recovered the local WAL files, received the WALs
* from the remote master as part of final join or has bootstrapped the
* cluster.
*/
RECOVERY_STATE_WAL_RECOVERED,
/**
* The node has built secondary indexes for memtx spaces.
*/
RECOVERY_STATE_INDEXES_BUILT,
/**
* The node has synced with remote peers. IOW, it has transitioned from
* "orphan" to "running".
*/
RECOVERY_STATE_SYNCED,
box_recovery_state_MAX,
};
static const char *box_recovery_state_strs[box_recovery_state_MAX] = {
/* [RECOVERY_STATE_SNAPSHOT_RECOVERED] = */
"snapshot_recovered",
/* [RECOVERY_STATE_WAL_RECOVERED] = */
"wal_recovered",
/* [RECOVERY_STATE_INDEXES_BUILT] = */
"indexes_built",
/* [RECOVERY_STATE_SYNCED] = */
"synced",
};
/** Whether the triggers for "synced" recovery stage have already run. */
static bool recovery_state_synced_is_reached;
/** PATH_MAX is too big and 2K is recommended limit for web address. */
#define BOX_FEEDBACK_HOST_MAX 2048
/** Feedback host URL to send crash info to. */
static char box_feedback_host[BOX_FEEDBACK_HOST_MAX];
/** Whether sending crash info to feedback URL is enabled. */
static bool box_feedback_crash_enabled;
static int
box_run_on_recovery_state(enum box_recovery_state state)
{
assert(state >= 0 && state < box_recovery_state_MAX);
return trigger_run(&box_on_recovery_state,
(char *)box_recovery_state_strs[state]);
}
static void
box_storage_init(void);
/**
* Broadcast the current instance status
*/
static void
box_broadcast_status(void);
/**
* A timer to broadcast the updated vclock. Doing this on each vclock update
* would be too expensive.
*/
static ev_timer box_broadcast_ballot_timer;
/** Set a new interval for vclock updates in ballot. */
static void
box_update_broadcast_ballot_interval(double interval)
{
static double ballot_broadcast_interval;
/* Do the broadcast at least once a second. */
interval = MIN(interval, 1.0);
if (interval == ballot_broadcast_interval)
return;
double timeout = ev_timer_remaining(loop(),
&box_broadcast_ballot_timer);
timeout -= ballot_broadcast_interval;
timeout += interval;
ev_timer_stop(loop(), &box_broadcast_ballot_timer);
ev_timer_set(&box_broadcast_ballot_timer, timeout, interval);
ev_timer_start(loop(), &box_broadcast_ballot_timer);
ballot_broadcast_interval = interval;
}
/** A callback to broadcast updated vclock in ballot by timeout. */
static void
box_broadcast_ballot_on_timeout(ev_loop *loop, ev_timer *timer, int events)
{
(void)loop;
(void)timer;
(void)events;
static struct vclock broadcast_vclock;
if (vclock_compare_ignore0(&broadcast_vclock, &replicaset.vclock) == 0)
return;
box_broadcast_ballot();
vclock_copy(&broadcast_vclock, &replicaset.vclock);
}
/**
* Generate and update the instance status title
*/
static void
title(const char *new_status)
{
snprintf(status, sizeof(status), "%s", new_status);
title_set_status(new_status);
title_update();
systemd_snotify("STATUS=%s", status);
box_broadcast_status();
}
void
box_update_ro_summary(void)
{
bool old_is_ro_summary = is_ro_summary;
is_ro_summary = is_ro || is_orphan || raft_is_ro(box_raft()) ||
txn_limbo_is_ro(&txn_limbo);
/* In 99% nothing changes. Filter this out first. */
if (is_ro_summary == old_is_ro_summary)
return;
if (is_ro_summary)
engine_switch_to_ro();
fiber_cond_broadcast(&ro_cond);
box_broadcast_status();
box_broadcast_election();
box_broadcast_ballot();
}
const char *
box_ro_reason(void)
{
if (raft_is_ro(box_raft()))
return "election";
if (txn_limbo_is_ro(&txn_limbo))
return "synchro";
if (is_ro)
return "config";
if (is_orphan)
return "orphan";
return NULL;
}
int
box_check_slice_slow(void)
{
return fiber_check_slice();
}
static int
box_check_writable(void)
{
if (!is_ro_summary)
return 0;
struct error *e = diag_set(ClientError, ER_READONLY);
struct raft *raft = box_raft();
error_append_msg(e, " - ");
error_set_str(e, "reason", box_ro_reason());
/*
* In case of multiple reasons at the same time only one is reported.
* But the order is important. For example, if the instance has election
* enabled, for the client it is better to see that it is a 'follower'
* and who is the leader than just see cfg 'read_only' is true.
*/
if (raft_is_ro(raft)) {
const char *state = raft_state_str(raft->state);
uint64_t term = raft->volatile_term;
error_set_str(e, "state", state);
error_set_uint(e, "term", term);
error_append_msg(e, "state is election %s with term %llu",
state, (unsigned long long)term);
uint32_t id = raft->leader;
if (id != REPLICA_ID_NIL) {
error_set_uint(e, "leader_id", id);
error_append_msg(e, ", leader is %u", id);
struct replica *r = replica_by_id(id);
/*
* XXX: when the leader is dropped from _cluster, it
* is not reported to Raft.
*/
if (r != NULL) {
error_set_uuid(e, "leader_uuid", &r->uuid);
error_append_msg(e, " (%s)",
tt_uuid_str(&r->uuid));
}
}
} else if (txn_limbo_is_ro(&txn_limbo)) {
uint32_t id = txn_limbo.owner_id;
uint64_t term = txn_limbo.promote_greatest_term;
error_set_uint(e, "queue_owner_id", id);
error_set_uint(e, "term", term);
error_append_msg(e, "synchro queue with term %llu belongs "
"to %u", (unsigned long long)term,
(unsigned)id);
struct replica *r = replica_by_id(id);
/*
* XXX: when an instance is deleted from _cluster, its limbo's
* ownership is not cleared.
*/
if (r != NULL) {
error_set_uuid(e, "queue_owner_uuid", &r->uuid);
error_append_msg(e, " (%s)", tt_uuid_str(&r->uuid));
}
if (txn_limbo.owner_id == instance_id) {
if (txn_limbo.is_frozen_due_to_fencing) {
error_append_msg(e, " and is frozen due to "
"fencing");
} else if (txn_limbo.is_frozen_until_promotion) {
error_append_msg(e, " and is frozen until "
"promotion");
}
}
} else {
if (is_ro)
error_append_msg(e, "box.cfg.read_only is true");
else if (is_orphan)
error_append_msg(e, "it is an orphan");
else
assert(false);
}
diag_log();
return -1;
}
static void
box_check_writable_xc(void)
{
if (box_check_writable() != 0)
diag_raise();
}
static void
box_check_memtx_min_tuple_size(ssize_t memtx_min_tuple_size)
{
if (memtx_min_tuple_size < 8 || memtx_min_tuple_size > 1048280)
tnt_raise(ClientError, ER_CFG, "memtx_min_tuple_size",
"specified value is out of bounds");
}
int
box_process_rw(struct request *request, struct space *space,
struct tuple **result)
{
struct tuple *tuple = NULL;
bool return_tuple = false;
struct txn *txn = in_txn();
bool is_autocommit = txn == NULL;
if (is_autocommit && (txn = txn_begin()) == NULL)
return -1;
assert(iproto_type_is_dml(request->type));
rmean_collect(rmean_box, request->type, 1);
if (access_check_space(space, PRIV_W) != 0)
goto rollback;
if (txn_begin_stmt(txn, space, request->type) != 0)
goto rollback;
if (space_execute_dml(space, txn, request, &tuple) != 0) {
txn_rollback_stmt(txn);
goto rollback;
}
if (result != NULL)
*result = tuple;
return_tuple = result != NULL && tuple != NULL;
if (return_tuple) {
/*
* Pin the tuple locally before the commit,
* otherwise it may go away during yield in
* when WAL is written in autocommit mode.
*/
tuple_ref(tuple);
}
if (txn_commit_stmt(txn, request))
goto rollback;
if (is_autocommit && txn_commit(txn) < 0)
goto error;
if (return_tuple) {
tuple_bless(tuple);
tuple_unref(tuple);
}
return 0;
rollback:
if (is_autocommit)
txn_abort(txn);
error:
if (return_tuple)
tuple_unref(tuple);
return -1;
}
static bool
box_check_ro(void);
void
box_set_ro(void)
{
is_ro = box_check_ro();
box_update_ro_summary();
}
bool
box_is_ro(void)
{
return is_ro_summary;
}
bool
box_is_orphan(void)
{
return is_orphan;
}
bool
box_is_anon(void)
{
return instance_id == REPLICA_ID_NIL;
}
int
box_wait_ro(bool ro, double timeout)
{
double deadline = ev_monotonic_now(loop()) + timeout;
while (is_box_configured == false || box_is_ro() != ro) {
if (fiber_cond_wait_deadline(&ro_cond, deadline) != 0)
return -1;
}
return 0;
}
void
box_do_set_orphan(bool orphan)
{
is_orphan = orphan;
box_update_ro_summary();
if (!is_orphan && !recovery_state_synced_is_reached) {
box_run_on_recovery_state(RECOVERY_STATE_SYNCED);
recovery_state_synced_is_reached = true;
}
}
void
box_set_orphan(bool orphan)
{
box_do_set_orphan(orphan);
/* Update the title to reflect the new status. */
if (is_orphan) {
say_info("entering orphan mode");
title("orphan");
} else {
say_info("leaving orphan mode");
title("running");
}
}
struct wal_stream {
/** Base class. */
struct xstream base;
/** The lsregion for allocating rows. */
struct lsregion lsr;
/** The array of lists keeping rows from xlog. */
struct rlist nodes_rows[VCLOCK_MAX];
/** Current transaction ID. 0 when no transaction. */
int64_t tsn;
/**
* LSN of the first row saved to check TSN and LSN match in case all
* rows of the tx appeared to be local.
*/
int64_t first_row_lsn;
/**
* Flag whether there is a pending yield to do when the current
* transaction is finished. It can't always be done right away because
* would abort the current transaction if it is memtx.
*/
bool has_yield;
/**
* True if any row in the transaction was global. Saved to check if TSN
* matches LSN of a first global row.
*/
bool has_global_row;
};
/**
* A stub used in txn_commit() during local recovery. We "replay"
* transactions during local recovery, with WAL turned off.
* Since each transaction attempts to write itself to WAL at
* commit, we need an implementation which would fake WAL write.
*/
struct recovery_journal {
struct journal base;
struct vclock *vclock;
};
/**
* Use the current row LSN as commit LSN - vinyl needs to see the
* exact same signature during local recovery to properly mark
* min/max LSN of created LSM levels.
*/
static int
recovery_journal_write(struct journal *base,
struct journal_entry *entry)
{
struct recovery_journal *journal = (struct recovery_journal *) base;
entry->res = vclock_sum(journal->vclock);
/*
* Since there're no actual writes, fire a
* journal_async_complete callback right away.
*/
journal_async_complete(entry);
return 0;
}
static void
recovery_journal_create(struct vclock *v)
{
static struct recovery_journal journal;
journal_create(&journal.base, recovery_journal_write,
recovery_journal_write);
journal.vclock = v;
journal_set(&journal.base);
}
/**
* Drop the stream to the initial state. It is supposed to be done when an error
* happens. Because in case of force recovery the stream will continue getting
* tuples. For that it must stay in a valid state and must handle them somehow.
*
* Now the stream simply drops the current transaction like it never happened,
* even if its commit-row wasn't met yet. Should be good enough for
* force-recovery when the consistency is already out of the game.
*/
static void
wal_stream_abort(struct wal_stream *stream)
{
struct txn *tx = in_txn();
if (tx != NULL)
txn_abort(tx);
stream->tsn = 0;
}
/**
* The wrapper exists only for the debug purposes, to ensure tsn being non-0 is
* in sync with the fiber's txn being non-NULL. It has nothing to do with the
* journal content, and therefore can use assertions instead of rigorous error
* checking even in release.
*/
static bool
wal_stream_has_tx_in_progress(const struct wal_stream *stream)
{
bool has = stream->tsn != 0;
assert(has == (in_txn() != NULL));
return has;
}
/**
* The wrapper exists only for the debug purposes, to ensure tsn being non-0 is
* in sync with the fiber's txn being non-NULL. In addition, there is a check
* for the completion of the transaction.It has nothing to do with the journal
* content, and therefore can use assertions instead of rigorous error checking
* even in release.
*/
static bool
wal_stream_has_unfinished_tx(const struct wal_stream *stream)
{
bool has = stream->tsn != 0;
assert(has == (in_txn() != NULL));
bool unfinished = false;
const struct rlist *nodes_rows = stream->nodes_rows;
for (int i = 0; i < VCLOCK_MAX; i++) {
if (!rlist_empty((struct rlist *)&nodes_rows[i])) {
unfinished = true;
break;
}
}
return has || unfinished;
}
static int
wal_stream_apply_synchro_row(struct wal_stream *stream, struct xrow_header *row)
{
assert(iproto_type_is_synchro_request(row->type));
if (wal_stream_has_tx_in_progress(stream)) {
diag_set(XlogError, "found synchro request in a transaction");
return -1;
}
struct synchro_request syn_req;
if (xrow_decode_synchro(row, &syn_req) != 0) {
say_error("couldn't decode a synchro request");
return -1;
}
return txn_limbo_process(&txn_limbo, &syn_req);
}
static int
wal_stream_apply_raft_row(struct wal_stream *stream, struct xrow_header *row)
{
assert(iproto_type_is_raft_request(row->type));
if (wal_stream_has_tx_in_progress(stream)) {
diag_set(XlogError, "found raft request in a transaction");
return -1;
}
struct raft_request raft_req;
/* Vclock is never persisted in WAL by Raft. */
if (xrow_decode_raft(row, &raft_req, NULL) != 0) {
say_error("couldn't decode a raft request");
return -1;
}
box_raft_recover(&raft_req);
return 0;
}
/**
* Rows of the same transaction are wrapped into begin/commit. Mostly for the
* sake of synchronous replication, when the log can contain rolled back
* transactions, which must be entirely reverted during recovery when ROLLBACK
* records are met. Row-by-row recovery wouldn't work for multi-statement
* synchronous transactions.
*/
static int
wal_stream_apply_dml_row(struct wal_stream *stream, struct xrow_header *row)
{
struct request request;
uint64_t req_type = dml_request_key_map(row->type);
if (xrow_decode_dml(row, &request, req_type) != 0) {
say_error("couldn't decode a DML request");
return -1;
}
/*
* Note that all the information which came from the log is validated
* and the errors are handled. Not asserted or paniced. That is for the
* sake of force recovery, which must be able to recover just everything
* what possible instead of terminating the instance.
*/
struct txn *txn;
if (stream->tsn == 0) {
if (row->tsn == 0) {
diag_set(XlogError, "found a row without TSN");
goto end_diag_request;
}
stream->tsn = row->tsn;
stream->first_row_lsn = row->lsn;
stream->has_global_row = false;
/*
* Rows are not stacked into a list like during replication,
* because recovery does not yield while reading the rows. All
* the yields are controlled by the stream, and therefore no
* need to wait for all the rows to start a transaction. Can
* start now, apply the rows, and make a yield after commit if
* necessary. Helps to avoid a lot of copying.
*/
txn = txn_begin();
if (txn == NULL) {
say_error("couldn't begin a recovery transaction");
return -1;
}
} else if (row->tsn != stream->tsn) {
diag_set(XlogError, "found a next transaction with the "
"previous one not yet committed");
goto end_diag_request;
} else {
txn = in_txn();
}
/* Ensure TSN is equal to LSN of the first global row. */
if (!stream->has_global_row && row->group_id != GROUP_LOCAL) {
if (row->tsn != row->lsn) {
diag_set(XlogError, "found a first global row in a "
"transaction with LSN/TSN mismatch");
goto end_diag_request;
}
stream->has_global_row = true;
}
assert(wal_stream_has_tx_in_progress(stream));
/* Nops might appear at least after before_replace skipping rows. */
if (request.type != IPROTO_NOP) {
struct space *space = space_cache_find(request.space_id);
if (space == NULL) {
say_error("couldn't find space by ID");
goto end_diag_request;
}
if (box_process_rw(&request, space, NULL) != 0) {
say_error("couldn't apply the request");
goto end_diag_request;
}
}
assert(txn != NULL);
if (!row->is_commit)
return 0;
/*
* For fully local transactions the TSN check won't work like for global
* transactions, because it is not known if there are global rows until
* commit arrives.
*/
if (!stream->has_global_row && stream->tsn != stream->first_row_lsn) {
diag_set(XlogError, "fully local transaction's TSN does not "
"match LSN of the first row");
return -1;
}
stream->tsn = 0;
/*
* During local recovery the commit procedure should be async, otherwise
* the only fiber processing recovery will get stuck on the first
* synchronous tx it meets until confirm timeout is reached and the tx
* is rolled back, yielding an error.
* Moreover, txn_commit_try_async() doesn't hurt at all during local
* recovery, since journal_write is faked at this stage and returns
* immediately.
*/
if (txn_commit_try_async(txn) != 0) {
/* Commit fail automatically leads to rollback. */
assert(in_txn() == NULL);
say_error("couldn't commit a recovery transaction");
return -1;
}
assert(in_txn() == NULL);
return 0;
end_diag_request:
/*
* The label must be used only for the errors related directly to the
* request. Errors like txn_begin() fail has nothing to do with it, and
* therefore don't log the request as the fault reason.
*/
say_error("error at request: %s", request_str(&request));
return -1;
}
/* Storage, adding rows to a rlist to separate mixed transactions. */
struct wal_row {
/* Base class. */
struct xrow_header row;
/* A link on the list of rows stacked in the nodes_rows array. */
struct rlist in_row_list;
/* A growing identifier to track lsregion allocations. */
int64_t lsr_id;
};
/*
* Callback to stash row and row bodies upon receipt, used to recover
* mixed transactions.
*/
static struct wal_row *
wal_stream_save_row(struct wal_stream *stream, struct xrow_header *row)
{
static int64_t lsr_id = 0;
struct lsregion *lsr = &stream->lsr;
struct wal_row *new_row =
(struct wal_row *)xlsregion_alloc(lsr, sizeof(struct wal_row),
++lsr_id);
new_row->lsr_id = lsr_id;
memcpy(new_row, row, sizeof(struct xrow_header));
assert(new_row->row.bodycnt <= 1);
if (new_row->row.bodycnt == 1) {
size_t len = new_row->row.body[0].iov_len;
char *new_base = (char *)xlsregion_alloc(lsr, len, lsr_id);
memcpy(new_base, new_row->row.body[0].iov_base, len);
/* Adjust row body pointers. */
new_row->row.body[0].iov_base = new_base;
}
return new_row;
}
/*
* Find the min lsr_id that is still needed.
*/
static int64_t
find_min_lsr_id(struct wal_stream *stream)
{
int64_t min_lsr_id = stream->base.row_count;
struct rlist *nodes_rows = stream->nodes_rows;
struct wal_row *item;
/*
* For each new row, lsr_id is incremented by 1. Only row from
* different replica_id can get mixed, so for each replica_id,
* the very first row has the smallest lsr_id of all row with that
* replica_id. Thus, for each transaction read to the end, to
* iterate through the nodes_rows array of lists and see which of
* the first `row` for each `replica_id` has the lowest lsr_id.
* This lsr_id is still needed, but anything less than this is not.
* So can free everything up to this lsr_id.
*/
for (uint32_t i = 0; i < VCLOCK_MAX; i++) {
if (!rlist_empty(&nodes_rows[i])) {
item = rlist_first_entry(&nodes_rows[i], wal_row,
in_row_list);
if (item->lsr_id < min_lsr_id)
min_lsr_id = item->lsr_id - 1;
}
}
return min_lsr_id;
}
/*
* Deallocating memory for the wal_row
*/
static void
wal_stream_gc(struct wal_stream *stream)
{
struct lsregion *lsr = &stream->lsr;
int64_t lsr_id = find_min_lsr_id(stream);
lsregion_gc(lsr, lsr_id);
}
/*
* When restoring the log is read row-by-row. However, it is necessary
* to store the rows for correct further recovery. For example, with
* mixed transactions. The following function saves the newly arrived
* row to the rlist, which is stored in array is nodes_rows in cell is
* replica_id. As soon as a row arrives with the is_commit flag set, the
* corresponding transaction tries to apply. If an error occurs the
* transaction is rolled back. And we continue to work with the next
* transaction.
*/
static int
wal_stream_apply_mixed_dml_row(struct wal_stream *stream,
struct xrow_header *row)
{
int rc = 0;
uint32_t id = row->replica_id;
struct rlist *nodes_rows = stream->nodes_rows;
/*
* When a new row arrives, it has the same address. Because the
* row is on the stack. Therefore, it needs to allocate memory on
* the heap. We do with row->body[0].iov_base analogically.
*/
struct wal_row *save_row = wal_stream_save_row(stream, row);
rlist_add_tail_entry(&nodes_rows[id], save_row, in_row_list);
if (!row->is_commit) {
return rc;
} else {
struct wal_row *item, *next_row;
rlist_foreach_entry_safe(item, &nodes_rows[id],
in_row_list, next_row) {
rlist_del_entry(item, in_row_list);
if (rc != 0)
continue;
rc = wal_stream_apply_dml_row(stream, &item->row);
}
/* deallocating the memory */
wal_stream_gc(stream);
assert(rlist_empty(&nodes_rows[id]));
return rc;
}
}
/**
* Yield once in a while, but not too often, mostly to allow signal handling to
* take place.
*/
static void
wal_stream_try_yield(struct wal_stream *stream)
{
if (wal_stream_has_tx_in_progress(stream) || !stream->has_yield)
return;
stream->has_yield = false;
fiber_sleep(0);
}
static void
wal_stream_apply_row(struct xstream *base, struct xrow_header *row)
{
struct wal_stream *stream =
container_of(base, struct wal_stream, base);
if (iproto_type_is_synchro_request(row->type)) {
if (wal_stream_apply_synchro_row(stream, row) != 0)
goto end_error;
} else if (iproto_type_is_raft_request(row->type)) {
if (wal_stream_apply_raft_row(stream, row) != 0)
goto end_error;
} else if (box_is_force_recovery) {
if (wal_stream_apply_mixed_dml_row(stream, row) != 0)
goto end_error;
} else if (wal_stream_apply_dml_row(stream, row) != 0) {
goto end_error;
}
wal_stream_try_yield(stream);
return;
end_error:
wal_stream_abort(stream);
wal_stream_try_yield(stream);
diag_raise();
}
/**
* Plan a yield in recovery stream. Wal stream will execute it as soon as it's
* ready.
*/
static void
wal_stream_schedule_yield(struct xstream *base)
{
struct wal_stream *stream = container_of(base, struct wal_stream, base);
stream->has_yield = true;
wal_stream_try_yield(stream);