-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcommit.c
772 lines (680 loc) · 21.8 KB
/
commit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/*----------------------------------------------------------------------------
*
* commit.c
* Replace ordinary commit with 3PC.
*
* Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*----------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/twophase.h"
#include "access/xact.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "storage/proc.h"
#include "storage/spin.h"
#include "utils/guc.h"
#include "utils/syscache.h"
#include "utils/snapmgr.h"
#include "utils/inval.h"
#include "miscadmin.h"
#include "commands/dbcommands.h"
#include "catalog/pg_subscription.h"
#include "tcop/tcopprot.h"
#include "postmaster/autovacuum.h"
#include "libpq/pqformat.h"
#include "pgstat.h"
#include "storage/ipc.h"
#include "multimaster.h"
#include "logger.h"
#include "ddl.h"
#include "state.h"
#include "syncpoint.h"
#include "commit.h"
#include "global_tx.h"
#include "messaging.h"
static bool force_in_bgworker;
static bool init_done;
static bool config_valid;
static bool inside_mtm_begin;
static MtmConfig *mtm_cfg;
MtmCurrentTrans MtmTx;
/* holds state defining cleanup actions in case of failure during commit */
static struct MtmCommitState
{
MtmGeneration gen;
char stream_name[DMQ_NAME_MAXLEN];
bool subscribed;
char gid[GIDSIZE];
GlobalTx *gtx;
bool abort_prepare; /* whether cleanup can (should) abort xact immediately */
} mtm_commit_state;
static void
pubsub_change_cb(Datum arg, int cacheid, uint32 hashvalue)
{
config_valid = false;
}
static void
proc_change_cb(Datum arg, int cacheid, uint32 hashvalue)
{
/* Force RemoteFunction reload */
MtmSetRemoteFunction(NULL, NULL);
}
static void
attach_node(int node_id, MtmConfig *new_cfg, Datum arg)
{
dmq_attach_receiver(psprintf(MTM_DMQNAME_FMT, node_id), node_id - 1);
}
static void
detach_node(int node_id, MtmConfig *new_cfg, Datum arg)
{
/* detach incoming queues from this node */
dmq_detach_receiver(psprintf(MTM_DMQNAME_FMT, node_id));
}
void
MtmXactCallback(XactEvent event, void *arg)
{
/*
* Perform distributed commit only for transactions in ordinary backends
* with multimaster enabled.
*/
if (IsAnyAutoVacuumProcess() || !IsNormalProcessingMode() ||
am_walsender || (IsBackgroundWorker && !force_in_bgworker))
{
return;
}
switch (event)
{
case XACT_EVENT_START:
MtmBeginTransaction();
break;
case XACT_EVENT_COMMIT_COMMAND:
/* Here we catching commit of single-statement transaction */
if (IsTransactionOrTransactionBlock()
&& !IsTransactionBlock()
&& !IsSubTransaction())
{
MtmTwoPhaseCommit();
}
break;
default:
break;
}
}
static void
mtm_commit_cleanup(int status, Datum arg)
{
/* 0 is ERROR, 1 is on exit hook */
bool on_exit = DatumGetInt32(arg) == 1;
ReleasePB();
if (mtm_commit_state.subscribed)
{
dmq_stream_unsubscribe(mtm_commit_state.stream_name);
mtm_commit_state.subscribed = false;
}
if (mtm_commit_state.gtx != NULL)
{
/*
* This crutchy dance matters if this is proc exit (FATAL in the
* middle of commit sequence): global_tx.c automatically releases gtx,
* and it would be really not nice to rely on the order in which the
* hooks are called. So reacquire the gtx if it was already released.
*/
Assert(GetMyGlobalTx() != NULL || on_exit);
if (GetMyGlobalTx() == NULL)
mtm_commit_state.gtx = GlobalTxAcquire(mtm_commit_state.gid,
false,
NULL);
/*
* If we managed to prepare the xact, tell resolver to deal with it
*/
if (mtm_commit_state.gtx != NULL && mtm_commit_state.gtx->prepared)
{
/*
* If there were no precommit, xact will definitely be aborted. We
* could abort it right here, but this requires very careful
* acting:
* 1) who would release gtx if we fail during
* FinishPreparedTransaction?
*
* 2) Generally FinishPreparedTransaction and
* SetPreparedTransactionState should run in xact, i.e.
* surrounded by
* StartTransactionCommand/CommitTransactionCommand.
* e.g. LockGXact will fail if I am not the owner of
* gxact. However, some hops are needed to avoid entering
* MtmTwoPhaseCommit/MtmBeginTransaction twice. In particular,
* erroring out from MtmBeginTransaction on attempt to abort
* xact after we got network error because, well, we are
* isolated after network error is really unpleasant. This
* relates to all
* StartTransactionCommand/CommitTransactionCommand in this
* file.
*
* As a sort of compromise, we could instead add the 'this is my
* orphaned prepare => directly abort it' logic to resolver.
*/
if (term_cmp(mtm_commit_state.gtx->state.accepted,
InvalidGTxTerm) == 0)
{
ereport(WARNING,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("[multimaster] exiting commit sequence of transaction %s which will be aborted",
mtm_commit_state.gid)));
}
else
{
ereport(WARNING,
(errcode(ERRCODE_TRANSACTION_RESOLUTION_UNKNOWN),
errmsg("[multimaster] exiting commit sequence of transaction %s with unknown status",
mtm_commit_state.gid),
errdetail("The transaction will be committed or aborted later.")));
}
mtm_commit_state.gtx->orphaned = true;
}
if (mtm_commit_state.gtx != NULL)
GlobalTxRelease(mtm_commit_state.gtx, false);
mtm_commit_state.gtx = NULL;
ResolverWake();
}
}
void
MtmBeginTransaction()
{
MtmNodeStatus node_status;
/* Set this on tx start, to avoid resetting in error handler */
AllowTempIn2PC = false;
/* XXX: clean MtmTx on commit and check on begin that it is clean. */
/* That should unveil probable issues with subxacts. */
if (!MtmIsEnabled())
{
MtmTx.distributed = false;
return;
}
if (!init_done)
{
/* Keep us informed about subscription changes. */
CacheRegisterSyscacheCallback(SUBSCRIPTIONOID,
pubsub_change_cb,
(Datum) 0);
CacheRegisterSyscacheCallback(PUBLICATIONOID,
pubsub_change_cb,
(Datum) 0);
CacheRegisterSyscacheCallback(PROCOID,
proc_change_cb,
(Datum) 0);
on_shmem_exit(mtm_commit_cleanup, Int32GetDatum(1));
init_done = true;
}
AcceptInvalidationMessages();
if (!config_valid)
{
mtm_cfg = MtmReloadConfig(mtm_cfg, attach_node, detach_node, (Datum) NULL);
if (mtm_cfg->my_node_id == MtmInvalidNodeId) /* mtm was dropped */
{
MtmTx.distributed = false;
return;
}
config_valid = true;
}
/* Reset MtmTx */
MtmTx.contains_ddl = false;
MtmTx.contains_dml = false;
MtmTx.distributed = true;
MtmDDLResetStatement();
node_status = MtmGetCurrentStatus(false, false);
/* Application name can be changed using PGAPPNAME environment variable */
if (node_status != MTM_ONLINE
&& strcmp(application_name, MULTIMASTER_ADMIN) != 0
&& strcmp(application_name, MULTIMASTER_BROADCAST_SERVICE) != 0)
{
/*
* Reject all user's transactions at offline cluster. Allow execution
* of transaction by bg-workers to makeit possible to perform
* recovery.
*/
if (!MtmBreakConnection)
{
mtm_log(ERROR,
"Multimaster node is not online: current status %s",
MtmNodeStatusMnem[node_status]);
}
else
{
mtm_log(FATAL,
"Multimaster node is not online: current status %s",
MtmNodeStatusMnem[node_status]);
}
}
/*
* If during previous checks we acquired snapshot we'll prevent BEGIN
* TRANSACTION ISOLATION LEVEL REPEATABLE READ from happening. So
* commit/start transaction in this case.
*/
if (FirstSnapshotSet && !inside_mtm_begin)
{
inside_mtm_begin = true;
CommitTransactionCommand();
StartTransactionCommand();
inside_mtm_begin = false;
}
}
/*
* Genenerate global transaction identifier for two-phase commit.
* It should be unique for all nodes.
* MTM-node_id-xid is part ensuring uniqueness; the rest is necessary payload.
* gen_num identifies the number of generation xact belongs to.
* configured is mask of configured nodes of this generation; it is required
* by resolver.
* (in theory we could get rid of it if we remembered generation history for
* some time, but we don't currently)
* TODO: add version and kinda backwards compatibility.
*/
void
MtmGenerateGid(char *gid, int node_id, TransactionId xid, uint64 gen_num,
nodemask_t configured)
{
sprintf(gid, "MTM-%d-" XID_FMT "-%" INT64_MODIFIER "X-%" INT64_MODIFIER "X",
node_id, xid, gen_num, configured);
return;
}
uint64
MtmGidParseGenNum(const char *gid)
{
uint64 gen_num = MtmInvalidGenNum;
TransactionId xid;
sscanf(gid, "MTM-%*d-" XID_FMT "-%" INT64_MODIFIER "X", &xid, &gen_num);
Assert(gen_num != MtmInvalidGenNum);
return gen_num;
}
int
MtmGidParseNodeId(const char *gid)
{
int node_id = -1;
sscanf(gid, "MTM-%d-%*d", &node_id);
return node_id;
}
TransactionId
MtmGidParseXid(const char *gid)
{
TransactionId xid = InvalidTransactionId;
sscanf(gid, "MTM-%*d-" XID_FMT, &xid);
Assert(xid != InvalidTransactionId);
return xid;
}
/* ensure we get the right PREPARE ack */
static bool
PrepareGatherHook(MtmMessage *anymsg, Datum arg)
{
MtmPrepareResponse *msg = (MtmPrepareResponse *) anymsg;
TransactionId xid = DatumGetTransactionId(arg);
if (anymsg->tag != T_MtmPrepareResponse)
return false;
return msg->xid == xid;
}
/* ensure we get the right 2A response */
static bool
Paxos2AGatherHook(MtmMessage *anymsg, Datum arg)
{
Mtm2AResponse *msg = (Mtm2AResponse *) anymsg;
char *gid = DatumGetPointer(arg);
if (anymsg->tag != T_Mtm2AResponse)
return false;
return strcmp(msg->gid, gid) == 0;
}
/*
* Returns false if mtm is not interested in this xact at all.
*/
bool
MtmTwoPhaseCommit(void)
{
nodemask_t cohort;
bool ret;
TransactionId xid;
MtmPrepareResponse *p_messages[MTM_MAX_NODES];
Mtm2AResponse *twoa_messages[MTM_MAX_NODES]; /* wow, great name */
int n_messages;
int i;
int nvotes;
nodemask_t success_cohort;
if (!MtmTx.contains_ddl && !MtmTx.contains_dml)
return false;
if (!MtmTx.distributed)
return false;
/*
* If this is implicit single-query xact, wrap it in block to execute
* PREPARE.
*/
if (!IsTransactionBlock())
{
BeginTransactionBlock(false);
CommitTransactionCommand();
StartTransactionCommand();
}
/* prepare for cleanup */
mtm_commit_state.subscribed = false;
mtm_commit_state.gtx = NULL;
mtm_commit_state.abort_prepare = false;
/*
* Note that we do not HOLD_INTERRUPTS; user might cancel waiting whenever
* he wants. However, probably xact status would be unclear at that
* moment; we issue a warning in this case.
* (but to be fair, bail out with unclear xact status is currently possible
* even without explicit cancellation; this ought to be fixed)
*/
PG_TRY();
{
/* Exclude concurrent gen switchers, c.f. AcquirePBByHolder call site */
AcquirePBByPreparer();
/*
* xact is allowed iff we are MTM_GEN_ONLINE in current gen, but
* MtmGetCurrentGenStatus is more useful for error reporting.
*/
if (MtmGetCurrentStatusInGen() != MTM_GEN_ONLINE)
{
ereport(MtmBreakConnection ? FATAL : ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("multimaster node is not online: current status \"%s\"",
MtmNodeStatusMnem[MtmGetCurrentStatus(true, false)])));
}
mtm_commit_state.gen = MtmGetCurrentGen(true);
xid = GetTopTransactionId();
MtmGenerateGid(mtm_commit_state.gid, mtm_cfg->my_node_id, xid,
mtm_commit_state.gen.num, mtm_commit_state.gen.configured);
sprintf(mtm_commit_state.stream_name, "xid" XID_FMT, xid);
dmq_stream_subscribe(mtm_commit_state.stream_name);
mtm_commit_state.subscribed = true;
mtm_log(MtmTxTrace, "%s subscribed for %s", mtm_commit_state.gid,
mtm_commit_state.stream_name);
/* prepare transaction on our node */
mtm_commit_state.gtx = GlobalTxAcquire(mtm_commit_state.gid, true, NULL);
Assert(mtm_commit_state.gtx->state.status == GTXInvalid);
/*
* PREPARE doesn't happen here; ret 0 just means we were already in
* aborted transaction block and we expect the callee to handle this.
*/
ret = PrepareTransactionBlock(mtm_commit_state.gid);
if (!ret)
{
Assert(false);
elog(PANIC, "unexpected PrepareTransactionBlock failure");
}
AllowTempIn2PC = true;
CommitTransactionCommand(); /* here we actually PrepareTransaction */
ReleasePB(); /* don't hold generation switch anymore */
mtm_commit_state.gtx->prepared = true;
/* end_lsn of PREPARE */
mtm_commit_state.gtx->coordinator_end_lsn = XactLastCommitEnd;
mtm_log(MtmTxFinish, "TXFINISH: %s prepared at %X/%X",
mtm_commit_state.gid,
(uint32) (mtm_commit_state.gtx->coordinator_end_lsn >> 32),
(uint32) mtm_commit_state.gtx->coordinator_end_lsn);
/*
* By definition of generations, we must collect PREPARE ack from
* *all* generation members.
* However, if generation switch has happened, we risk never getting
* response from some counterparties as e.g. they might get this
* PREPARE from some other node in recovery, so stop waiting and abort
* in this case. OTOH, if gen stays the same, we surely eventually
* will get the answer to apply attempt, regardless of transient
* problems with replication connection (if dmq connection broke
* though we abort as confirmation could have been lost).
*
* Probably we could act a bit gentler as generally not every gen
* switch requires abort of all currently preparing xacts. It is not
* clear whether related complications worth the benefits though.
*/
cohort = mtm_commit_state.gen.members;
BIT_CLEAR(cohort, mtm_cfg->my_node_id - 1);
ret = gather(cohort,
(MtmMessage **) p_messages, NULL, &n_messages,
PrepareGatherHook, TransactionIdGetDatum(xid),
NULL, mtm_commit_state.gen.num);
/*
* The goal here is to check that every gen member applied the
* transaction; paxos doesn't demand 1a/1b roundtrip for correctness
* as coordinator uses first term {1, 0} and his decree choice
* (precommit, preabort) is surely free (unbounded).
*/
if (!ret)
{
MtmGeneration new_gen = MtmGetCurrentGen(false);
mtm_commit_state.abort_prepare = true;
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("[multimaster] failed to collect prepare acks due to generation switch: was num=" UINT64_FORMAT ", members=%s, now num=" UINT64_FORMAT ", members=%s",
mtm_commit_state.gen.num,
maskToString(mtm_commit_state.gen.members),
new_gen.num,
maskToString(new_gen.members))));
}
if (n_messages != popcount(cohort))
{
nodemask_t failed_cohort = cohort;
for (i = 0; i < n_messages; i++)
BIT_CLEAR(failed_cohort, p_messages[i]->node_id - 1);
mtm_commit_state.abort_prepare = true;
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_FAILURE),
errmsg("[multimaster] failed to collect prepare acks from nodemask %s due to network error",
maskToString(failed_cohort))));
}
for (i = 0; i < n_messages; i++)
{
if (!p_messages[i]->prepared)
{
mtm_commit_state.abort_prepare = true;
/* don't print random gid, node id for regression tests output */
if (MtmVolksWagenMode)
ereport(ERROR,
(errcode(p_messages[i]->errcode),
errmsg("[multimaster] failed to prepare transaction at peer node")));
else
ereport(ERROR,
(errcode(p_messages[i]->errcode),
errmsg("[multimaster] failed to prepare transaction %s at node %d",
mtm_commit_state.gid, p_messages[i]->node_id),
errdetail("sqlstate %s (%s)",
unpack_sql_state(p_messages[i]->errcode),
p_messages[i]->errmsg)));
}
}
/* ok, we have all prepare responses, precommit */
SetPreparedTransactionState(mtm_commit_state.gid,
serialize_gtx_state(GTXPreCommitted,
InitialGTxTerm,
InitialGTxTerm),
false);
/*
* since this moment direct aborting is not allowed; others can
* receive our precommit and resolve xact to commit without us
*/
mtm_commit_state.gtx->state.status = GTXPreCommitted;
mtm_commit_state.gtx->state.accepted = (GlobalTxTerm) {1, 0};
mtm_log(MtmTxFinish, "TXFINISH: %s precommitted", mtm_commit_state.gid);
/*
* Here (paxos 2a/2b) we need only majority of acks, probably it'd be
* useful to teach gather return once quorum of good msgs collected.
*/
ret = gather(cohort,
(MtmMessage **) twoa_messages, NULL, &n_messages,
Paxos2AGatherHook, PointerGetDatum(mtm_commit_state.gid),
NULL, mtm_commit_state.gen.num);
/* check ballots in answers */
nvotes = 1; /* myself */
success_cohort = 0;
for (i = 0; i < n_messages; i++)
{
if (term_cmp(twoa_messages[i]->accepted_term,
(GlobalTxTerm) {1, 0}) == 0 &&
twoa_messages[i]->status == GTXPreCommitted)
{
nvotes++;
BIT_SET(success_cohort, twoa_messages[i]->node_id);
continue;
}
ereport(WARNING,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("[multimaster] failed to precommit transaction %s at node %d",
mtm_commit_state.gid, twoa_messages[i]->node_id),
errdetail("status=%d, accepted term=<%d, %d>",
twoa_messages[i]->status,
twoa_messages[i]->accepted_term.ballot,
twoa_messages[i]->accepted_term.node_id)));
}
if (!Quorum(popcount(mtm_commit_state.gen.configured), nvotes))
{
nodemask_t failed_cohort;
if (!ret)
{
MtmGeneration new_gen = MtmGetCurrentGen(false);
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("[multimaster] failed to collect precommit acks of transaction %s due to generation switch: was num=" UINT64_FORMAT ", members=%s, now num=" UINT64_FORMAT ", members=%s",
mtm_commit_state.gid,
mtm_commit_state.gen.num,
maskToString(mtm_commit_state.gen.members),
new_gen.num,
maskToString(new_gen.members))));
}
failed_cohort = cohort;
for (i = 0; i < MTM_MAX_NODES; i++)
if (BIT_CHECK(success_cohort, i))
BIT_CLEAR(failed_cohort, i);
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("[multimaster] failed to collect precommit acks or precommit transaction %s at nodes %s due to network error or non-first term",
mtm_commit_state.gid,
maskToString(failed_cohort))));
}
/* we have majority precommits, commit */
StartTransactionCommand();
FinishPreparedTransaction(mtm_commit_state.gid, true, false);
mtm_commit_state.gtx->state.status = GTXCommitted;
mtm_log(MtmTxFinish, "TXFINISH: %s committed", mtm_commit_state.gid);
GlobalTxRelease(mtm_commit_state.gtx, true);
mtm_commit_state.gtx = NULL;
// /* XXX: make this conditional */
// gather(participants, (MtmMessage **) messages, NULL, &n_messages, false);
dmq_stream_unsubscribe(mtm_commit_state.stream_name);
mtm_commit_state.subscribed = false;
mtm_log(MtmTxTrace, "%s unsubscribed for %s",
mtm_commit_state.gid, mtm_commit_state.stream_name);
}
PG_CATCH();
{
mtm_commit_cleanup(0, Int32GetDatum(0));
PG_RE_THROW();
}
PG_END_TRY();
MaybeLogSyncpoint();
return true;
}
/* TODO: explicit prepares are not adapted to generations yet, i.e. broken */
bool
MtmExplicitPrepare(char *gid)
{
nodemask_t participants;
bool ret;
TransactionId xid;
char stream[DMQ_NAME_MAXLEN];
MtmPrepareResponse *messages[MTM_MAX_NODES];
int n_messages;
int i;
elog(ERROR, "mtm doesn't support user 2PC");
/*
* GetTopTransactionId() will fail for aborted tx, but we still need to
* finish it, so handle that manually.
*/
if (IsAbortedTransactionBlockState())
{
ret = PrepareTransactionBlock(gid);
Assert(!ret);
return false;
}
xid = GetTopTransactionId();
sprintf(stream, "xid" XID_FMT, xid);
dmq_stream_subscribe(stream);
mtm_log(MtmTxTrace, "%s subscribed for %s", gid, stream);
participants = MtmGetEnabledNodeMask(false) &
~((nodemask_t) 1 << (mtm_cfg->my_node_id - 1));
ret = PrepareTransactionBlock(gid);
if (!ret)
return false;
CommitTransactionCommand();
mtm_log(MtmTxFinish, "TXFINISH: %s prepared", gid);
gather(participants,
(MtmMessage **) messages, NULL, &n_messages,
NULL, 0,
NULL, 0);
dmq_stream_unsubscribe(stream);
for (i = 0; i < n_messages; i++)
{
/* Assert(messages[i]->status == GTXPrepared || messages[i]->status == GTXAborted); */
if (!messages[i]->prepared)
{
StartTransactionCommand();
FinishPreparedTransaction(gid, false, false);
mtm_log(MtmTxFinish, "TXFINISH: %s aborted", gid);
if (MtmVolksWagenMode)
ereport(ERROR,
(errcode(messages[i]->errcode),
errmsg("[multimaster] failed to prepare transaction at peer node")));
else
ereport(ERROR,
(errcode(messages[i]->errcode),
errmsg("[multimaster] failed to prepare transaction %s at node %d",
gid, messages[i]->node_id),
errdetail("sqlstate %s (%s)",
unpack_sql_state(messages[i]->errcode), messages[i]->errmsg)));
}
}
StartTransactionCommand();
return true;
}
void
MtmExplicitFinishPrepared(bool isTopLevel, char *gid, bool isCommit)
{
nodemask_t participants;
Mtm2AResponse *messages[MTM_MAX_NODES];
int n_messages;
PreventInTransactionBlock(isTopLevel,
isCommit ? "COMMIT PREPARED" : "ROLLBACK PREPARED");
elog(ERROR, "mtm doesn't support user 2PC");
if (isCommit)
{
dmq_stream_subscribe(gid);
participants = MtmGetEnabledNodeMask(false) &
~((nodemask_t) 1 << (mtm_cfg->my_node_id - 1));
SetPreparedTransactionState(gid, MULTIMASTER_PRECOMMITTED, false);
mtm_log(MtmTxFinish, "TXFINISH: %s precommitted", gid);
gather(participants,
(MtmMessage **) messages, NULL, &n_messages,
NULL, 0,
NULL, 0);
FinishPreparedTransaction(gid, true, false);
/* XXX: make this conditional */
mtm_log(MtmTxFinish, "TXFINISH: %s committed", gid);
gather(participants,
(MtmMessage **) messages, NULL, &n_messages,
NULL, 0,
NULL, 0);
dmq_stream_unsubscribe(gid);
}
else
{
FinishPreparedTransaction(gid, false, false);
mtm_log(MtmTxFinish, "TXFINISH: %s abort", gid);
}
}
/*
* Allow replication in bgworker.
* Needed for scheduler.
*/
void
MtmToggleReplication(void)
{
force_in_bgworker = true;
}