PostgreSQL Source Code  git master
syncrep.h File Reference
#include "access/xlogdefs.h"
#include "utils/guc.h"
Include dependency graph for syncrep.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  SyncRepStandbyData
 
struct  SyncRepConfigData
 

Macros

#define SyncRepRequested()   (max_wal_senders > 0 && synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
 
#define SYNC_REP_NO_WAIT   (-1)
 
#define SYNC_REP_WAIT_WRITE   0
 
#define SYNC_REP_WAIT_FLUSH   1
 
#define SYNC_REP_WAIT_APPLY   2
 
#define NUM_SYNC_REP_WAIT_MODE   3
 
#define SYNC_REP_NOT_WAITING   0
 
#define SYNC_REP_WAITING   1
 
#define SYNC_REP_WAIT_COMPLETE   2
 
#define SYNC_REP_PRIORITY   0
 
#define SYNC_REP_QUORUM   1
 

Typedefs

typedef struct SyncRepStandbyData SyncRepStandbyData
 
typedef struct SyncRepConfigData SyncRepConfigData
 

Functions

void SyncRepWaitForLSN (XLogRecPtr lsn, bool commit)
 
void SyncRepCleanupAtProcExit (void)
 
void SyncRepInitConfig (void)
 
void SyncRepReleaseWaiters (void)
 
int SyncRepGetCandidateStandbys (SyncRepStandbyData **standbys)
 
void SyncRepUpdateSyncStandbysDefined (void)
 
bool check_synchronous_standby_names (char **newval, void **extra, GucSource source)
 
void assign_synchronous_standby_names (const char *newval, void *extra)
 
void assign_synchronous_commit (int newval, void *extra)
 
int syncrep_yyparse (void)
 
int syncrep_yylex (void)
 
void syncrep_yyerror (const char *str)
 
void syncrep_scanner_init (const char *query_string)
 
void syncrep_scanner_finish (void)
 

Variables

SyncRepConfigDataSyncRepConfig
 
SyncRepConfigDatasyncrep_parse_result
 
char * syncrep_parse_error_msg
 
char * SyncRepStandbyNames
 

Macro Definition Documentation

◆ NUM_SYNC_REP_WAIT_MODE

#define NUM_SYNC_REP_WAIT_MODE   3

◆ SYNC_REP_NO_WAIT

#define SYNC_REP_NO_WAIT   (-1)

Definition at line 23 of file syncrep.h.

Referenced by assign_synchronous_commit().

◆ SYNC_REP_NOT_WAITING

#define SYNC_REP_NOT_WAITING   0

Definition at line 31 of file syncrep.h.

Referenced by InitProcess(), SyncRepCancelWait(), and SyncRepWaitForLSN().

◆ SYNC_REP_PRIORITY

#define SYNC_REP_PRIORITY   0

◆ SYNC_REP_QUORUM

#define SYNC_REP_QUORUM   1

Definition at line 37 of file syncrep.h.

◆ SYNC_REP_WAIT_APPLY

#define SYNC_REP_WAIT_APPLY   2

◆ SYNC_REP_WAIT_COMPLETE

#define SYNC_REP_WAIT_COMPLETE   2

Definition at line 33 of file syncrep.h.

Referenced by SyncRepWaitForLSN(), and SyncRepWakeQueue().

◆ SYNC_REP_WAIT_FLUSH

#define SYNC_REP_WAIT_FLUSH   1

◆ SYNC_REP_WAIT_WRITE

#define SYNC_REP_WAIT_WRITE   0

◆ SYNC_REP_WAITING

#define SYNC_REP_WAITING   1

Definition at line 32 of file syncrep.h.

Referenced by SyncRepWaitForLSN().

◆ SyncRepRequested

#define SyncRepRequested ( )    (max_wal_senders > 0 && synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)

Definition at line 19 of file syncrep.h.

Referenced by SyncRepWaitForLSN().

Typedef Documentation

◆ SyncRepConfigData

◆ SyncRepStandbyData

Function Documentation

◆ assign_synchronous_commit()

void assign_synchronous_commit ( int  newval,
void *  extra 
)

Definition at line 1087 of file syncrep.c.

References SYNC_REP_NO_WAIT, SYNC_REP_WAIT_APPLY, SYNC_REP_WAIT_FLUSH, SYNC_REP_WAIT_WRITE, SYNCHRONOUS_COMMIT_REMOTE_APPLY, SYNCHRONOUS_COMMIT_REMOTE_FLUSH, SYNCHRONOUS_COMMIT_REMOTE_WRITE, and SyncRepWaitMode.

1088 {
1089  switch (newval)
1090  {
1093  break;
1096  break;
1099  break;
1100  default:
1102  break;
1103  }
1104 }
#define SYNC_REP_NO_WAIT
Definition: syncrep.h:23
#define SYNC_REP_WAIT_APPLY
Definition: syncrep.h:26
#define SYNC_REP_WAIT_FLUSH
Definition: syncrep.h:25
#define newval
static int SyncRepWaitMode
Definition: syncrep.c:98
#define SYNC_REP_WAIT_WRITE
Definition: syncrep.h:24

◆ assign_synchronous_standby_names()

void assign_synchronous_standby_names ( const char *  newval,
void *  extra 
)

Definition at line 1081 of file syncrep.c.

1082 {
1083  SyncRepConfig = (SyncRepConfigData *) extra;
1084 }
SyncRepConfigData * SyncRepConfig
Definition: syncrep.c:97

◆ check_synchronous_standby_names()

bool check_synchronous_standby_names ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 1024 of file syncrep.c.

References SyncRepConfigData::config_size, GUC_check_errcode(), GUC_check_errdetail, GUC_check_errmsg, malloc, SyncRepConfigData::num_sync, syncrep_parse_error_msg, syncrep_parse_result, syncrep_scanner_finish(), syncrep_scanner_init(), and syncrep_yyparse().

1025 {
1026  if (*newval != NULL && (*newval)[0] != '\0')
1027  {
1028  int parse_rc;
1029  SyncRepConfigData *pconf;
1030 
1031  /* Reset communication variables to ensure a fresh start */
1032  syncrep_parse_result = NULL;
1033  syncrep_parse_error_msg = NULL;
1034 
1035  /* Parse the synchronous_standby_names string */
1037  parse_rc = syncrep_yyparse();
1039 
1040  if (parse_rc != 0 || syncrep_parse_result == NULL)
1041  {
1042  GUC_check_errcode(ERRCODE_SYNTAX_ERROR);
1045  else
1046  GUC_check_errdetail("synchronous_standby_names parser failed");
1047  return false;
1048  }
1049 
1050  if (syncrep_parse_result->num_sync <= 0)
1051  {
1052  GUC_check_errmsg("number of synchronous standbys (%d) must be greater than zero",
1054  return false;
1055  }
1056 
1057  /* GUC extra value must be malloc'd, not palloc'd */
1058  pconf = (SyncRepConfigData *)
1060  if (pconf == NULL)
1061  return false;
1063 
1064  *extra = (void *) pconf;
1065 
1066  /*
1067  * We need not explicitly clean up syncrep_parse_result. It, and any
1068  * other cruft generated during parsing, will be freed when the
1069  * current memory context is deleted. (This code is generally run in
1070  * a short-lived context used for config file processing, so that will
1071  * not be very long.)
1072  */
1073  }
1074  else
1075  *extra = NULL;
1076 
1077  return true;
1078 }
void syncrep_scanner_finish(void)
void syncrep_scanner_init(const char *query_string)
#define GUC_check_errdetail
Definition: guc.h:417
char * syncrep_parse_error_msg
#define GUC_check_errmsg
Definition: guc.h:413
void GUC_check_errcode(int sqlerrcode)
Definition: guc.c:11022
#define malloc(a)
Definition: header.h:50
SyncRepConfigData * syncrep_parse_result
#define newval
int syncrep_yyparse(void)

◆ syncrep_scanner_finish()

void syncrep_scanner_finish ( void  )

◆ syncrep_scanner_init()

void syncrep_scanner_init ( const char *  query_string)

◆ syncrep_yyerror()

void syncrep_yyerror ( const char *  str)

◆ syncrep_yylex()

int syncrep_yylex ( void  )

◆ syncrep_yyparse()

int syncrep_yyparse ( void  )

◆ SyncRepCleanupAtProcExit()

void SyncRepCleanupAtProcExit ( void  )

Definition at line 383 of file syncrep.c.

References LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProc, SHMQueueDelete(), SHMQueueIsDetached(), and PGPROC::syncRepLinks.

Referenced by ProcKill().

384 {
385  /*
386  * First check if we are removed from the queue without the lock to not
387  * slow down backend exit.
388  */
390  {
391  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
392 
393  /* maybe we have just been removed, so recheck */
396 
397  LWLockRelease(SyncRepLock);
398  }
399 }
PGPROC * MyProc
Definition: proc.c:67
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
bool SHMQueueIsDetached(const SHM_QUEUE *queue)
Definition: shmqueue.c:47
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
SHM_QUEUE syncRepLinks
Definition: proc.h:198
void SHMQueueDelete(SHM_QUEUE *queue)
Definition: shmqueue.c:68

◆ SyncRepGetCandidateStandbys()

int SyncRepGetCandidateStandbys ( SyncRepStandbyData **  standbys)

Definition at line 726 of file syncrep.c.

References SyncRepStandbyData::apply, WalSnd::apply, SyncRepStandbyData::flush, WalSnd::flush, i, SyncRepStandbyData::is_me, max_wal_senders, WalSnd::mutex, MyWalSnd, SyncRepConfigData::num_sync, palloc(), WalSnd::pid, SyncRepStandbyData::pid, qsort, SpinLockAcquire, SpinLockRelease, standby_priority_comparator(), WalSnd::state, SYNC_REP_PRIORITY, SyncRepStandbyData::sync_standby_priority, WalSnd::sync_standby_priority, SyncRepConfigData::syncrep_method, SyncRepStandbyData::walsnd_index, WalSndCtl, WalSndCtlData::walsnds, WALSNDSTATE_STOPPING, WALSNDSTATE_STREAMING, SyncRepStandbyData::write, WalSnd::write, and XLogRecPtrIsInvalid.

Referenced by pg_stat_get_wal_senders(), and SyncRepGetSyncRecPtr().

727 {
728  int i;
729  int n;
730 
731  /* Create result array */
732  *standbys = (SyncRepStandbyData *)
734 
735  /* Quick exit if sync replication is not requested */
736  if (SyncRepConfig == NULL)
737  return 0;
738 
739  /* Collect raw data from shared memory */
740  n = 0;
741  for (i = 0; i < max_wal_senders; i++)
742  {
743  volatile WalSnd *walsnd; /* Use volatile pointer to prevent code
744  * rearrangement */
745  SyncRepStandbyData *stby;
746  WalSndState state; /* not included in SyncRepStandbyData */
747 
748  walsnd = &WalSndCtl->walsnds[i];
749  stby = *standbys + n;
750 
751  SpinLockAcquire(&walsnd->mutex);
752  stby->pid = walsnd->pid;
753  state = walsnd->state;
754  stby->write = walsnd->write;
755  stby->flush = walsnd->flush;
756  stby->apply = walsnd->apply;
758  SpinLockRelease(&walsnd->mutex);
759 
760  /* Must be active */
761  if (stby->pid == 0)
762  continue;
763 
764  /* Must be streaming or stopping */
765  if (state != WALSNDSTATE_STREAMING &&
766  state != WALSNDSTATE_STOPPING)
767  continue;
768 
769  /* Must be synchronous */
770  if (stby->sync_standby_priority == 0)
771  continue;
772 
773  /* Must have a valid flush position */
774  if (XLogRecPtrIsInvalid(stby->flush))
775  continue;
776 
777  /* OK, it's a candidate */
778  stby->walsnd_index = i;
779  stby->is_me = (walsnd == MyWalSnd);
780  n++;
781  }
782 
783  /*
784  * In quorum mode, we return all the candidates. In priority mode, if we
785  * have too many candidates then return only the num_sync ones of highest
786  * priority.
787  */
789  n > SyncRepConfig->num_sync)
790  {
791  /* Sort by priority ... */
792  qsort(*standbys, n, sizeof(SyncRepStandbyData),
794  /* ... then report just the first num_sync ones */
795  n = SyncRepConfig->num_sync;
796  }
797 
798  return n;
799 }
XLogRecPtr write
#define SYNC_REP_PRIORITY
Definition: syncrep.h:36
uint8 syncrep_method
Definition: syncrep.h:69
WalSndCtlData * WalSndCtl
Definition: walsender.c:109
WalSnd walsnds[FLEXIBLE_ARRAY_MEMBER]
SyncRepConfigData * SyncRepConfig
Definition: syncrep.c:97
int sync_standby_priority
Definition: syncrep.h:50
slock_t mutex
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr flush
static int standby_priority_comparator(const void *a, const void *b)
Definition: syncrep.c:805
XLogRecPtr flush
Definition: syncrep.h:48
XLogRecPtr write
Definition: syncrep.h:47
WalSndState state
XLogRecPtr apply
Definition: syncrep.h:49
int max_wal_senders
Definition: walsender.c:121
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
WalSnd * MyWalSnd
Definition: walsender.c:112
int sync_standby_priority
Definition: regguts.h:298
WalSndState
void * palloc(Size size)
Definition: mcxt.c:950
int i
#define qsort(a, b, c, d)
Definition: port.h:497
XLogRecPtr apply

◆ SyncRepInitConfig()

void SyncRepInitConfig ( void  )

Definition at line 412 of file syncrep.c.

References application_name, DEBUG1, ereport, errmsg(), WalSnd::mutex, MyWalSnd, SpinLockAcquire, SpinLockRelease, WalSnd::sync_standby_priority, and SyncRepGetStandbyPriority().

Referenced by StartLogicalReplication(), StartReplication(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

413 {
414  int priority;
415 
416  /*
417  * Determine if we are a potential sync standby and remember the result
418  * for handling replies from standby.
419  */
420  priority = SyncRepGetStandbyPriority();
421  if (MyWalSnd->sync_standby_priority != priority)
422  {
424  MyWalSnd->sync_standby_priority = priority;
426 
427  ereport(DEBUG1,
428  (errmsg("standby \"%s\" now has synchronous standby priority %u",
429  application_name, priority)));
430  }
431 }
#define DEBUG1
Definition: elog.h:25
slock_t mutex
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
WalSnd * MyWalSnd
Definition: walsender.c:112
#define ereport(elevel,...)
Definition: elog.h:155
int sync_standby_priority
char * application_name
Definition: guc.c:563
int errmsg(const char *fmt,...)
Definition: elog.c:902
static int SyncRepGetStandbyPriority(void)
Definition: syncrep.c:832

◆ SyncRepReleaseWaiters()

void SyncRepReleaseWaiters ( void  )

Definition at line 441 of file syncrep.c.

References announce_next_takeover, application_name, DEBUG3, elog, ereport, errmsg(), WalSnd::flush, LOG, WalSndCtlData::lsn, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyWalSnd, WalSnd::state, SYNC_REP_PRIORITY, SYNC_REP_WAIT_APPLY, SYNC_REP_WAIT_FLUSH, SYNC_REP_WAIT_WRITE, WalSnd::sync_standby_priority, SyncRepConfigData::syncrep_method, SyncRepGetSyncRecPtr(), SyncRepWakeQueue(), WalSndCtl, WALSNDSTATE_STOPPING, WALSNDSTATE_STREAMING, and XLogRecPtrIsInvalid.

Referenced by ProcessStandbyReplyMessage().

442 {
443  volatile WalSndCtlData *walsndctl = WalSndCtl;
444  XLogRecPtr writePtr;
445  XLogRecPtr flushPtr;
446  XLogRecPtr applyPtr;
447  bool got_recptr;
448  bool am_sync;
449  int numwrite = 0;
450  int numflush = 0;
451  int numapply = 0;
452 
453  /*
454  * If this WALSender is serving a standby that is not on the list of
455  * potential sync standbys then we have nothing to do. If we are still
456  * starting up, still running base backup or the current flush position is
457  * still invalid, then leave quickly also. Streaming or stopping WAL
458  * senders are allowed to release waiters.
459  */
460  if (MyWalSnd->sync_standby_priority == 0 ||
464  {
465  announce_next_takeover = true;
466  return;
467  }
468 
469  /*
470  * We're a potential sync standby. Release waiters if there are enough
471  * sync standbys and we are considered as sync.
472  */
473  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
474 
475  /*
476  * Check whether we are a sync standby or not, and calculate the synced
477  * positions among all sync standbys. (Note: although this step does not
478  * of itself require holding SyncRepLock, it seems like a good idea to do
479  * it after acquiring the lock. This ensures that the WAL pointers we use
480  * to release waiters are newer than any previous execution of this
481  * routine used.)
482  */
483  got_recptr = SyncRepGetSyncRecPtr(&writePtr, &flushPtr, &applyPtr, &am_sync);
484 
485  /*
486  * If we are managing a sync standby, though we weren't prior to this,
487  * then announce we are now a sync standby.
488  */
489  if (announce_next_takeover && am_sync)
490  {
491  announce_next_takeover = false;
492 
494  ereport(LOG,
495  (errmsg("standby \"%s\" is now a synchronous standby with priority %u",
497  else
498  ereport(LOG,
499  (errmsg("standby \"%s\" is now a candidate for quorum synchronous standby",
500  application_name)));
501  }
502 
503  /*
504  * If the number of sync standbys is less than requested or we aren't
505  * managing a sync standby then just leave.
506  */
507  if (!got_recptr || !am_sync)
508  {
509  LWLockRelease(SyncRepLock);
510  announce_next_takeover = !am_sync;
511  return;
512  }
513 
514  /*
515  * Set the lsn first so that when we wake backends they will release up to
516  * this location.
517  */
518  if (walsndctl->lsn[SYNC_REP_WAIT_WRITE] < writePtr)
519  {
520  walsndctl->lsn[SYNC_REP_WAIT_WRITE] = writePtr;
521  numwrite = SyncRepWakeQueue(false, SYNC_REP_WAIT_WRITE);
522  }
523  if (walsndctl->lsn[SYNC_REP_WAIT_FLUSH] < flushPtr)
524  {
525  walsndctl->lsn[SYNC_REP_WAIT_FLUSH] = flushPtr;
526  numflush = SyncRepWakeQueue(false, SYNC_REP_WAIT_FLUSH);
527  }
528  if (walsndctl->lsn[SYNC_REP_WAIT_APPLY] < applyPtr)
529  {
530  walsndctl->lsn[SYNC_REP_WAIT_APPLY] = applyPtr;
531  numapply = SyncRepWakeQueue(false, SYNC_REP_WAIT_APPLY);
532  }
533 
534  LWLockRelease(SyncRepLock);
535 
536  elog(DEBUG3, "released %d procs up to write %X/%X, %d procs up to flush %X/%X, %d procs up to apply %X/%X",
537  numwrite, (uint32) (writePtr >> 32), (uint32) writePtr,
538  numflush, (uint32) (flushPtr >> 32), (uint32) flushPtr,
539  numapply, (uint32) (applyPtr >> 32), (uint32) applyPtr);
540 }
static bool SyncRepGetSyncRecPtr(XLogRecPtr *writePtr, XLogRecPtr *flushPtr, XLogRecPtr *applyPtr, bool *am_sync)
Definition: syncrep.c:553
#define DEBUG3
Definition: elog.h:23
#define SYNC_REP_PRIORITY
Definition: syncrep.h:36
uint8 syncrep_method
Definition: syncrep.h:69
WalSndCtlData * WalSndCtl
Definition: walsender.c:109
#define LOG
Definition: elog.h:26
SyncRepConfigData * SyncRepConfig
Definition: syncrep.c:97
static int SyncRepWakeQueue(bool all, int mode)
Definition: syncrep.c:879
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
XLogRecPtr flush
#define SYNC_REP_WAIT_APPLY
Definition: syncrep.h:26
static bool announce_next_takeover
Definition: syncrep.c:95
WalSndState state
unsigned int uint32
Definition: c.h:429
#define SYNC_REP_WAIT_FLUSH
Definition: syncrep.h:25
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
WalSnd * MyWalSnd
Definition: walsender.c:112
#define ereport(elevel,...)
Definition: elog.h:155
uint64 XLogRecPtr
Definition: xlogdefs.h:21
int sync_standby_priority
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
XLogRecPtr lsn[NUM_SYNC_REP_WAIT_MODE]
char * application_name
Definition: guc.c:563
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
#define SYNC_REP_WAIT_WRITE
Definition: syncrep.h:24

◆ SyncRepUpdateSyncStandbysDefined()

void SyncRepUpdateSyncStandbysDefined ( void  )

Definition at line 948 of file syncrep.c.

References Assert, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), mode, NUM_SYNC_REP_WAIT_MODE, offsetof, SHMQueueNext(), WalSndCtlData::sync_standbys_defined, PGPROC::syncRepLinks, WalSndCtlData::SyncRepQueue, SyncRepWakeQueue(), SyncStandbysDefined, PGPROC::waitLSN, and WalSndCtl.

Referenced by UpdateSharedMemoryConfig().

949 {
950  bool sync_standbys_defined = SyncStandbysDefined();
951 
952  if (sync_standbys_defined != WalSndCtl->sync_standbys_defined)
953  {
954  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
955 
956  /*
957  * If synchronous_standby_names has been reset to empty, it's futile
958  * for backends to continue waiting. Since the user no longer wants
959  * synchronous replication, we'd better wake them up.
960  */
961  if (!sync_standbys_defined)
962  {
963  int i;
964 
965  for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
966  SyncRepWakeQueue(true, i);
967  }
968 
969  /*
970  * Only allow people to join the queue when there are synchronous
971  * standbys defined. Without this interlock, there's a race
972  * condition: we might wake up all the current waiters; then, some
973  * backend that hasn't yet reloaded its config might go to sleep on
974  * the queue (and never wake up). This prevents that.
975  */
976  WalSndCtl->sync_standbys_defined = sync_standbys_defined;
977 
978  LWLockRelease(SyncRepLock);
979  }
980 }
WalSndCtlData * WalSndCtl
Definition: walsender.c:109
static int SyncRepWakeQueue(bool all, int mode)
Definition: syncrep.c:879
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
#define SyncStandbysDefined()
Definition: syncrep.c:92
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
int i
#define NUM_SYNC_REP_WAIT_MODE
Definition: syncrep.h:28

◆ SyncRepWaitForLSN()

void SyncRepWaitForLSN ( XLogRecPtr  lsn,
bool  commit 
)

Definition at line 148 of file syncrep.c.

References Assert, DestNone, ereport, errcode(), errdetail(), errmsg(), get_ps_display(), InterruptHoldoffCount, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), Min, mode, MyLatch, MyProc, palloc(), pfree(), pg_read_barrier, ProcDiePending, QueryCancelPending, ResetLatch(), set_ps_display(), SHMQueueIsDetached(), sprintf, SYNC_REP_NOT_WAITING, SYNC_REP_WAIT_COMPLETE, SYNC_REP_WAIT_FLUSH, SYNC_REP_WAITING, WalSndCtlData::sync_standbys_defined, SyncRepCancelWait(), PGPROC::syncRepLinks, SyncRepQueueInsert(), SyncRepRequested, PGPROC::syncRepState, SyncRepWaitMode, update_process_title, WAIT_EVENT_SYNC_REP, WaitLatch(), PGPROC::waitLSN, WalSndCtl, WARNING, whereToSendOutput, WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by EndPrepare(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), and RecordTransactionCommitPrepared().

149 {
150  char *new_status = NULL;
151  const char *old_status;
152  int mode;
153 
154  /*
155  * This should be called while holding interrupts during a transaction
156  * commit to prevent the follow-up shared memory queue cleanups to be
157  * influenced by external interruptions.
158  */
160 
161  /*
162  * Fast exit if user has not requested sync replication, or there are no
163  * sync replication standby names defined.
164  *
165  * Since this routine gets called every commit time, it's important to
166  * exit quickly if sync replication is not requested. So we check
167  * WalSndCtl->sync_standbys_defined flag without the lock and exit
168  * immediately if it's false. If it's true, we need to check it again later
169  * while holding the lock, to check the flag and operate the sync rep
170  * queue atomically. This is necessary to avoid the race condition
171  * described in SyncRepUpdateSyncStandbysDefined(). On the other
172  * hand, if it's false, the lock is not necessary because we don't touch
173  * the queue.
174  */
175  if (!SyncRepRequested() ||
176  !((volatile WalSndCtlData *) WalSndCtl)->sync_standbys_defined)
177  return;
178 
179  /* Cap the level for anything other than commit to remote flush only. */
180  if (commit)
181  mode = SyncRepWaitMode;
182  else
184 
186  Assert(WalSndCtl != NULL);
187 
188  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
190 
191  /*
192  * We don't wait for sync rep if WalSndCtl->sync_standbys_defined is not
193  * set. See SyncRepUpdateSyncStandbysDefined.
194  *
195  * Also check that the standby hasn't already replied. Unlikely race
196  * condition but we'll be fetching that cache line anyway so it's likely
197  * to be a low cost check.
198  */
199  if (!WalSndCtl->sync_standbys_defined ||
200  lsn <= WalSndCtl->lsn[mode])
201  {
202  LWLockRelease(SyncRepLock);
203  return;
204  }
205 
206  /*
207  * Set our waitLSN so WALSender will know when to wake us, and add
208  * ourselves to the queue.
209  */
210  MyProc->waitLSN = lsn;
212  SyncRepQueueInsert(mode);
213  Assert(SyncRepQueueIsOrderedByLSN(mode));
214  LWLockRelease(SyncRepLock);
215 
216  /* Alter ps display to show waiting for sync rep. */
218  {
219  int len;
220 
221  old_status = get_ps_display(&len);
222  new_status = (char *) palloc(len + 32 + 1);
223  memcpy(new_status, old_status, len);
224  sprintf(new_status + len, " waiting for %X/%X",
225  (uint32) (lsn >> 32), (uint32) lsn);
226  set_ps_display(new_status);
227  new_status[len] = '\0'; /* truncate off " waiting ..." */
228  }
229 
230  /*
231  * Wait for specified LSN to be confirmed.
232  *
233  * Each proc has its own wait latch, so we perform a normal latch
234  * check/wait loop here.
235  */
236  for (;;)
237  {
238  int rc;
239 
240  /* Must reset the latch before testing state. */
242 
243  /*
244  * Acquiring the lock is not needed, the latch ensures proper
245  * barriers. If it looks like we're done, we must really be done,
246  * because once walsender changes the state to SYNC_REP_WAIT_COMPLETE,
247  * it will never update it again, so we can't be seeing a stale value
248  * in that case.
249  */
251  break;
252 
253  /*
254  * If a wait for synchronous replication is pending, we can neither
255  * acknowledge the commit nor raise ERROR or FATAL. The latter would
256  * lead the client to believe that the transaction aborted, which is
257  * not true: it's already committed locally. The former is no good
258  * either: the client has requested synchronous replication, and is
259  * entitled to assume that an acknowledged commit is also replicated,
260  * which might not be true. So in this case we issue a WARNING (which
261  * some clients may be able to interpret) and shut off further output.
262  * We do NOT reset ProcDiePending, so that the process will die after
263  * the commit is cleaned up.
264  */
265  if (ProcDiePending)
266  {
268  (errcode(ERRCODE_ADMIN_SHUTDOWN),
269  errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
270  errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
273  break;
274  }
275 
276  /*
277  * It's unclear what to do if a query cancel interrupt arrives. We
278  * can't actually abort at this point, but ignoring the interrupt
279  * altogether is not helpful, so we just terminate the wait with a
280  * suitable warning.
281  */
282  if (QueryCancelPending)
283  {
284  QueryCancelPending = false;
286  (errmsg("canceling wait for synchronous replication due to user request"),
287  errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
289  break;
290  }
291 
292  /*
293  * Wait on latch. Any condition that should wake us up will set the
294  * latch, so no need for timeout.
295  */
298 
299  /*
300  * If the postmaster dies, we'll probably never get an acknowledgment,
301  * because all the wal sender processes will exit. So just bail out.
302  */
303  if (rc & WL_POSTMASTER_DEATH)
304  {
305  ProcDiePending = true;
308  break;
309  }
310  }
311 
312  /*
313  * WalSender has checked our LSN and has removed us from queue. Clean up
314  * state and leave. It's OK to reset these shared memory fields without
315  * holding SyncRepLock, because any walsenders will ignore us anyway when
316  * we're not on the queue. We need a read barrier to make sure we see the
317  * changes to the queue link (this might be unnecessary without
318  * assertions, but better safe than sorry).
319  */
320  pg_read_barrier();
323  MyProc->waitLSN = 0;
324 
325  if (new_status)
326  {
327  /* Reset ps display */
328  set_ps_display(new_status);
329  pfree(new_status);
330  }
331 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
static void SyncRepCancelWait(void)
Definition: syncrep.c:373
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
bool update_process_title
Definition: ps_status.c:36
static void SyncRepQueueInsert(int mode)
Definition: syncrep.c:340
PGPROC * MyProc
Definition: proc.c:67
#define SYNC_REP_WAITING
Definition: syncrep.h:32
#define Min(x, y)
Definition: c.h:982
#define SYNC_REP_NOT_WAITING
Definition: syncrep.h:31
WalSndCtlData * WalSndCtl
Definition: walsender.c:109
int errcode(int sqlerrcode)
Definition: elog.c:691
void ResetLatch(Latch *latch)
Definition: latch.c:588
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
void set_ps_display(const char *activity)
Definition: ps_status.c:349
#define sprintf
Definition: port.h:217
void pfree(void *pointer)
Definition: mcxt.c:1057
Definition: dest.h:89
const char * get_ps_display(int *displen)
Definition: ps_status.c:430
int errdetail(const char *fmt,...)
Definition: elog.c:1035
unsigned int uint32
Definition: c.h:429
#define SYNC_REP_WAIT_FLUSH
Definition: syncrep.h:25
#define SyncRepRequested()
Definition: syncrep.h:19
#define WARNING
Definition: elog.h:40
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define ereport(elevel,...)
Definition: elog.h:155
#define SYNC_REP_WAIT_COMPLETE
Definition: syncrep.h:33
#define Assert(condition)
Definition: c.h:800
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
#define pg_read_barrier()
Definition: atomics.h:158
bool SHMQueueIsDetached(const SHM_QUEUE *queue)
Definition: shmqueue.c:47
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
SHM_QUEUE syncRepLinks
Definition: proc.h:198
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
struct Latch * MyLatch
Definition: globals.c:54
int syncRepState
Definition: proc.h:197
CommandDest whereToSendOutput
Definition: postgres.c:91
static int SyncRepWaitMode
Definition: syncrep.c:98
#define WL_LATCH_SET
Definition: latch.h:124
XLogRecPtr waitLSN
Definition: proc.h:196

Variable Documentation

◆ syncrep_parse_error_msg

char* syncrep_parse_error_msg

◆ syncrep_parse_result

SyncRepConfigData* syncrep_parse_result

◆ SyncRepConfig

SyncRepConfigData* SyncRepConfig

Definition at line 97 of file syncrep.c.

Referenced by pg_stat_get_wal_senders().

◆ SyncRepStandbyNames

char* SyncRepStandbyNames

Definition at line 90 of file syncrep.c.