PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
syncrep.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * syncrep.c
4  *
5  * Synchronous replication is new as of PostgreSQL 9.1.
6  *
7  * If requested, transaction commits wait until their commit LSN are
8  * acknowledged by the synchronous standbys.
9  *
10  * This module contains the code for waiting and release of backends.
11  * All code in this module executes on the primary. The core streaming
12  * replication transport remains within WALreceiver/WALsender modules.
13  *
14  * The essence of this design is that it isolates all logic about
15  * waiting/releasing onto the primary. The primary defines which standbys
16  * it wishes to wait for. The standbys are completely unaware of the
17  * durability requirements of transactions on the primary, reducing the
18  * complexity of the code and streamlining both standby operations and
19  * network bandwidth because there is no requirement to ship
20  * per-transaction state information.
21  *
22  * Replication is either synchronous or not synchronous (async). If it is
23  * async, we just fastpath out of here. If it is sync, then we wait for
24  * the write, flush or apply location on the standby before releasing
25  * the waiting backend. Further complexity in that interaction is
26  * expected in later releases.
27  *
28  * The best performing way to manage the waiting backends is to have a
29  * single ordered queue of waiting backends, so that we can avoid
30  * searching the through all waiters each time we receive a reply.
31  *
32  * In 9.5 or before only a single standby could be considered as
33  * synchronous. In 9.6 we support a priority-based multiple synchronous
34  * standbys. In 10.0 a quorum-based multiple synchronous standbys is also
35  * supported. The number of synchronous standbys that transactions
36  * must wait for replies from is specified in synchronous_standby_names.
37  * This parameter also specifies a list of standby names and the method
38  * (FIRST and ANY) to choose synchronous standbys from the listed ones.
39  *
40  * The method FIRST specifies a priority-based synchronous replication
41  * and makes transaction commits wait until their WAL records are
42  * replicated to the requested number of synchronous standbys chosen based
43  * on their priorities. The standbys whose names appear earlier in the list
44  * are given higher priority and will be considered as synchronous.
45  * Other standby servers appearing later in this list represent potential
46  * synchronous standbys. If any of the current synchronous standbys
47  * disconnects for whatever reason, it will be replaced immediately with
48  * the next-highest-priority standby.
49  *
50  * The method ANY specifies a quorum-based synchronous replication
51  * and makes transaction commits wait until their WAL records are
52  * replicated to at least the requested number of synchronous standbys
53  * in the list. All the standbys appearing in the list are considered as
54  * candidates for quorum synchronous standbys.
55  *
56  * If neither FIRST nor ANY is specified, FIRST is used as the method.
57  * This is for backward compatibility with 9.6 or before where only a
58  * priority-based sync replication was supported.
59  *
60  * Before the standbys chosen from synchronous_standby_names can
61  * become the synchronous standbys they must have caught up with
62  * the primary; that may take some time. Once caught up,
63  * the standbys which are considered as synchronous at that moment
64  * will release waiters from the queue.
65  *
66  * Portions Copyright (c) 2010-2017, PostgreSQL Global Development Group
67  *
68  * IDENTIFICATION
69  * src/backend/replication/syncrep.c
70  *
71  *-------------------------------------------------------------------------
72  */
73 #include "postgres.h"
74 
75 #include <unistd.h>
76 
77 #include "access/xact.h"
78 #include "miscadmin.h"
79 #include "pgstat.h"
80 #include "replication/syncrep.h"
81 #include "replication/walsender.h"
83 #include "storage/pmsignal.h"
84 #include "storage/proc.h"
85 #include "tcop/tcopprot.h"
86 #include "utils/builtins.h"
87 #include "utils/ps_status.h"
88 
89 /* User-settable parameters for sync rep */
91 
92 #define SyncStandbysDefined() \
93  (SyncRepStandbyNames != NULL && SyncRepStandbyNames[0] != '\0')
94 
95 static bool announce_next_takeover = true;
96 
99 
100 static void SyncRepQueueInsert(int mode);
101 static void SyncRepCancelWait(void);
102 static int SyncRepWakeQueue(bool all, int mode);
103 
104 static bool SyncRepGetSyncRecPtr(XLogRecPtr *writePtr,
105  XLogRecPtr *flushPtr,
106  XLogRecPtr *applyPtr,
107  bool *am_sync);
108 static void SyncRepGetOldestSyncRecPtr(XLogRecPtr *writePtr,
109  XLogRecPtr *flushPtr,
110  XLogRecPtr *applyPtr,
111  List *sync_standbys);
112 static void SyncRepGetNthLatestSyncRecPtr(XLogRecPtr *writePtr,
113  XLogRecPtr *flushPtr,
114  XLogRecPtr *applyPtr,
115  List *sync_standbys, uint8 nth);
116 static int SyncRepGetStandbyPriority(void);
117 static List *SyncRepGetSyncStandbysPriority(bool *am_sync);
118 static List *SyncRepGetSyncStandbysQuorum(bool *am_sync);
119 static int cmp_lsn(const void *a, const void *b);
120 
121 #ifdef USE_ASSERT_CHECKING
122 static bool SyncRepQueueIsOrderedByLSN(int mode);
123 #endif
124 
125 /*
126  * ===========================================================
127  * Synchronous Replication functions for normal user backends
128  * ===========================================================
129  */
130 
131 /*
132  * Wait for synchronous replication, if requested by user.
133  *
134  * Initially backends start in state SYNC_REP_NOT_WAITING and then
135  * change that state to SYNC_REP_WAITING before adding ourselves
136  * to the wait queue. During SyncRepWakeQueue() a WALSender changes
137  * the state to SYNC_REP_WAIT_COMPLETE once replication is confirmed.
138  * This backend then resets its state to SYNC_REP_NOT_WAITING.
139  *
140  * 'lsn' represents the LSN to wait for. 'commit' indicates whether this LSN
141  * represents a commit record. If it doesn't, then we wait only for the WAL
142  * to be flushed if synchronous_commit is set to the higher level of
143  * remote_apply, because only commit records provide apply feedback.
144  */
145 void
146 SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
147 {
148  char *new_status = NULL;
149  const char *old_status;
150  int mode;
151 
152  /* Cap the level for anything other than commit to remote flush only. */
153  if (commit)
154  mode = SyncRepWaitMode;
155  else
157 
158  /*
159  * Fast exit if user has not requested sync replication, or there are no
160  * sync replication standby names defined. Note that those standbys don't
161  * need to be connected.
162  */
164  return;
165 
167  Assert(WalSndCtl != NULL);
168 
169  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
171 
172  /*
173  * We don't wait for sync rep if WalSndCtl->sync_standbys_defined is not
174  * set. See SyncRepUpdateSyncStandbysDefined.
175  *
176  * Also check that the standby hasn't already replied. Unlikely race
177  * condition but we'll be fetching that cache line anyway so it's likely
178  * to be a low cost check.
179  */
181  lsn <= WalSndCtl->lsn[mode])
182  {
183  LWLockRelease(SyncRepLock);
184  return;
185  }
186 
187  /*
188  * Set our waitLSN so WALSender will know when to wake us, and add
189  * ourselves to the queue.
190  */
191  MyProc->waitLSN = lsn;
193  SyncRepQueueInsert(mode);
194  Assert(SyncRepQueueIsOrderedByLSN(mode));
195  LWLockRelease(SyncRepLock);
196 
197  /* Alter ps display to show waiting for sync rep. */
199  {
200  int len;
201 
202  old_status = get_ps_display(&len);
203  new_status = (char *) palloc(len + 32 + 1);
204  memcpy(new_status, old_status, len);
205  sprintf(new_status + len, " waiting for %X/%X",
206  (uint32) (lsn >> 32), (uint32) lsn);
207  set_ps_display(new_status, false);
208  new_status[len] = '\0'; /* truncate off " waiting ..." */
209  }
210 
211  /*
212  * Wait for specified LSN to be confirmed.
213  *
214  * Each proc has its own wait latch, so we perform a normal latch
215  * check/wait loop here.
216  */
217  for (;;)
218  {
219  /* Must reset the latch before testing state. */
221 
222  /*
223  * Acquiring the lock is not needed, the latch ensures proper
224  * barriers. If it looks like we're done, we must really be done,
225  * because once walsender changes the state to SYNC_REP_WAIT_COMPLETE,
226  * it will never update it again, so we can't be seeing a stale value
227  * in that case.
228  */
230  break;
231 
232  /*
233  * If a wait for synchronous replication is pending, we can neither
234  * acknowledge the commit nor raise ERROR or FATAL. The latter would
235  * lead the client to believe that the transaction aborted, which is
236  * not true: it's already committed locally. The former is no good
237  * either: the client has requested synchronous replication, and is
238  * entitled to assume that an acknowledged commit is also replicated,
239  * which might not be true. So in this case we issue a WARNING (which
240  * some clients may be able to interpret) and shut off further output.
241  * We do NOT reset ProcDiePending, so that the process will die after
242  * the commit is cleaned up.
243  */
244  if (ProcDiePending)
245  {
247  (errcode(ERRCODE_ADMIN_SHUTDOWN),
248  errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
249  errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
252  break;
253  }
254 
255  /*
256  * It's unclear what to do if a query cancel interrupt arrives. We
257  * can't actually abort at this point, but ignoring the interrupt
258  * altogether is not helpful, so we just terminate the wait with a
259  * suitable warning.
260  */
261  if (QueryCancelPending)
262  {
263  QueryCancelPending = false;
265  (errmsg("canceling wait for synchronous replication due to user request"),
266  errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
268  break;
269  }
270 
271  /*
272  * If the postmaster dies, we'll probably never get an
273  * acknowledgement, because all the wal sender processes will exit. So
274  * just bail out.
275  */
276  if (!PostmasterIsAlive())
277  {
278  ProcDiePending = true;
281  break;
282  }
283 
284  /*
285  * Wait on latch. Any condition that should wake us up will set the
286  * latch, so no need for timeout.
287  */
290  }
291 
292  /*
293  * WalSender has checked our LSN and has removed us from queue. Clean up
294  * state and leave. It's OK to reset these shared memory fields without
295  * holding SyncRepLock, because any walsenders will ignore us anyway when
296  * we're not on the queue.
297  */
300  MyProc->waitLSN = 0;
301 
302  if (new_status)
303  {
304  /* Reset ps display */
305  set_ps_display(new_status, false);
306  pfree(new_status);
307  }
308 }
309 
310 /*
311  * Insert MyProc into the specified SyncRepQueue, maintaining sorted invariant.
312  *
313  * Usually we will go at tail of queue, though it's possible that we arrive
314  * here out of order, so start at tail and work back to insertion point.
315  */
316 static void
318 {
319  PGPROC *proc;
320 
321  Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);
322  proc = (PGPROC *) SHMQueuePrev(&(WalSndCtl->SyncRepQueue[mode]),
323  &(WalSndCtl->SyncRepQueue[mode]),
324  offsetof(PGPROC, syncRepLinks));
325 
326  while (proc)
327  {
328  /*
329  * Stop at the queue element that we should after to ensure the queue
330  * is ordered by LSN.
331  */
332  if (proc->waitLSN < MyProc->waitLSN)
333  break;
334 
335  proc = (PGPROC *) SHMQueuePrev(&(WalSndCtl->SyncRepQueue[mode]),
336  &(proc->syncRepLinks),
337  offsetof(PGPROC, syncRepLinks));
338  }
339 
340  if (proc)
342  else
344 }
345 
346 /*
347  * Acquire SyncRepLock and cancel any wait currently in progress.
348  */
349 static void
351 {
352  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
356  LWLockRelease(SyncRepLock);
357 }
358 
359 void
361 {
363  {
364  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
366  LWLockRelease(SyncRepLock);
367  }
368 }
369 
370 /*
371  * ===========================================================
372  * Synchronous Replication functions for wal sender processes
373  * ===========================================================
374  */
375 
376 /*
377  * Take any action required to initialise sync rep state from config
378  * data. Called at WALSender startup and after each SIGHUP.
379  */
380 void
382 {
383  int priority;
384 
385  /*
386  * Determine if we are a potential sync standby and remember the result
387  * for handling replies from standby.
388  */
389  priority = SyncRepGetStandbyPriority();
390  if (MyWalSnd->sync_standby_priority != priority)
391  {
392  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
393  MyWalSnd->sync_standby_priority = priority;
394  LWLockRelease(SyncRepLock);
395  ereport(DEBUG1,
396  (errmsg("standby \"%s\" now has synchronous standby priority %u",
397  application_name, priority)));
398  }
399 }
400 
401 /*
402  * Update the LSNs on each queue based upon our latest state. This
403  * implements a simple policy of first-valid-sync-standby-releases-waiter.
404  *
405  * Other policies are possible, which would change what we do here and
406  * perhaps also which information we store as well.
407  */
408 void
410 {
411  volatile WalSndCtlData *walsndctl = WalSndCtl;
412  XLogRecPtr writePtr;
413  XLogRecPtr flushPtr;
414  XLogRecPtr applyPtr;
415  bool got_recptr;
416  bool am_sync;
417  int numwrite = 0;
418  int numflush = 0;
419  int numapply = 0;
420 
421  /*
422  * If this WALSender is serving a standby that is not on the list of
423  * potential sync standbys then we have nothing to do. If we are still
424  * starting up, still running base backup or the current flush position is
425  * still invalid, then leave quickly also.
426  */
427  if (MyWalSnd->sync_standby_priority == 0 ||
430  {
431  announce_next_takeover = true;
432  return;
433  }
434 
435  /*
436  * We're a potential sync standby. Release waiters if there are enough
437  * sync standbys and we are considered as sync.
438  */
439  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
440 
441  /*
442  * Check whether we are a sync standby or not, and calculate the synced
443  * positions among all sync standbys.
444  */
445  got_recptr = SyncRepGetSyncRecPtr(&writePtr, &flushPtr, &applyPtr, &am_sync);
446 
447  /*
448  * If we are managing a sync standby, though we weren't prior to this,
449  * then announce we are now a sync standby.
450  */
451  if (announce_next_takeover && am_sync)
452  {
453  announce_next_takeover = false;
454 
455  if (SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY)
456  ereport(LOG,
457  (errmsg("standby \"%s\" is now a synchronous standby with priority %u",
459  else
460  ereport(LOG,
461  (errmsg("standby \"%s\" is now a candidate for quorum synchronous standby",
462  application_name)));
463  }
464 
465  /*
466  * If the number of sync standbys is less than requested or we aren't
467  * managing a sync standby then just leave.
468  */
469  if (!got_recptr || !am_sync)
470  {
471  LWLockRelease(SyncRepLock);
472  announce_next_takeover = !am_sync;
473  return;
474  }
475 
476  /*
477  * Set the lsn first so that when we wake backends they will release up to
478  * this location.
479  */
480  if (walsndctl->lsn[SYNC_REP_WAIT_WRITE] < writePtr)
481  {
482  walsndctl->lsn[SYNC_REP_WAIT_WRITE] = writePtr;
483  numwrite = SyncRepWakeQueue(false, SYNC_REP_WAIT_WRITE);
484  }
485  if (walsndctl->lsn[SYNC_REP_WAIT_FLUSH] < flushPtr)
486  {
487  walsndctl->lsn[SYNC_REP_WAIT_FLUSH] = flushPtr;
488  numflush = SyncRepWakeQueue(false, SYNC_REP_WAIT_FLUSH);
489  }
490  if (walsndctl->lsn[SYNC_REP_WAIT_APPLY] < applyPtr)
491  {
492  walsndctl->lsn[SYNC_REP_WAIT_APPLY] = applyPtr;
493  numapply = SyncRepWakeQueue(false, SYNC_REP_WAIT_APPLY);
494  }
495 
496  LWLockRelease(SyncRepLock);
497 
498  elog(DEBUG3, "released %d procs up to write %X/%X, %d procs up to flush %X/%X, %d procs up to apply %X/%X",
499  numwrite, (uint32) (writePtr >> 32), (uint32) writePtr,
500  numflush, (uint32) (flushPtr >> 32), (uint32) flushPtr,
501  numapply, (uint32) (applyPtr >> 32), (uint32) applyPtr);
502 }
503 
504 /*
505  * Calculate the synced Write, Flush and Apply positions among sync standbys.
506  *
507  * Return false if the number of sync standbys is less than
508  * synchronous_standby_names specifies. Otherwise return true and
509  * store the positions into *writePtr, *flushPtr and *applyPtr.
510  *
511  * On return, *am_sync is set to true if this walsender is connecting to
512  * sync standby. Otherwise it's set to false.
513  */
514 static bool
516  XLogRecPtr *applyPtr, bool *am_sync)
517 {
518  List *sync_standbys;
519 
520  *writePtr = InvalidXLogRecPtr;
521  *flushPtr = InvalidXLogRecPtr;
522  *applyPtr = InvalidXLogRecPtr;
523  *am_sync = false;
524 
525  /* Get standbys that are considered as synchronous at this moment */
526  sync_standbys = SyncRepGetSyncStandbys(am_sync);
527 
528  /*
529  * Quick exit if we are not managing a sync standby or there are not
530  * enough synchronous standbys.
531  */
532  if (!(*am_sync) ||
533  SyncRepConfig == NULL ||
534  list_length(sync_standbys) < SyncRepConfig->num_sync)
535  {
536  list_free(sync_standbys);
537  return false;
538  }
539 
540  /*
541  * In a priority-based sync replication, the synced positions are the
542  * oldest ones among sync standbys. In a quorum-based, they are the Nth
543  * latest ones.
544  *
545  * SyncRepGetNthLatestSyncRecPtr() also can calculate the oldest
546  * positions. But we use SyncRepGetOldestSyncRecPtr() for that calculation
547  * because it's a bit more efficient.
548  *
549  * XXX If the numbers of current and requested sync standbys are the same,
550  * we can use SyncRepGetOldestSyncRecPtr() to calculate the synced
551  * positions even in a quorum-based sync replication.
552  */
553  if (SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY)
554  {
555  SyncRepGetOldestSyncRecPtr(writePtr, flushPtr, applyPtr,
556  sync_standbys);
557  }
558  else
559  {
560  SyncRepGetNthLatestSyncRecPtr(writePtr, flushPtr, applyPtr,
561  sync_standbys, SyncRepConfig->num_sync);
562  }
563 
564  list_free(sync_standbys);
565  return true;
566 }
567 
568 /*
569  * Calculate the oldest Write, Flush and Apply positions among sync standbys.
570  */
571 static void
573  XLogRecPtr *applyPtr, List *sync_standbys)
574 {
575  ListCell *cell;
576 
577  /*
578  * Scan through all sync standbys and calculate the oldest Write, Flush
579  * and Apply positions.
580  */
581  foreach(cell, sync_standbys)
582  {
583  WalSnd *walsnd = &WalSndCtl->walsnds[lfirst_int(cell)];
585  XLogRecPtr flush;
586  XLogRecPtr apply;
587 
588  SpinLockAcquire(&walsnd->mutex);
589  write = walsnd->write;
590  flush = walsnd->flush;
591  apply = walsnd->apply;
592  SpinLockRelease(&walsnd->mutex);
593 
594  if (XLogRecPtrIsInvalid(*writePtr) || *writePtr > write)
595  *writePtr = write;
596  if (XLogRecPtrIsInvalid(*flushPtr) || *flushPtr > flush)
597  *flushPtr = flush;
598  if (XLogRecPtrIsInvalid(*applyPtr) || *applyPtr > apply)
599  *applyPtr = apply;
600  }
601 }
602 
603 /*
604  * Calculate the Nth latest Write, Flush and Apply positions among sync
605  * standbys.
606  */
607 static void
609  XLogRecPtr *applyPtr, List *sync_standbys, uint8 nth)
610 {
611  ListCell *cell;
612  XLogRecPtr *write_array;
613  XLogRecPtr *flush_array;
614  XLogRecPtr *apply_array;
615  int len;
616  int i = 0;
617 
618  len = list_length(sync_standbys);
619  write_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * len);
620  flush_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * len);
621  apply_array = (XLogRecPtr *) palloc(sizeof(XLogRecPtr) * len);
622 
623  foreach(cell, sync_standbys)
624  {
625  WalSnd *walsnd = &WalSndCtl->walsnds[lfirst_int(cell)];
626 
627  SpinLockAcquire(&walsnd->mutex);
628  write_array[i] = walsnd->write;
629  flush_array[i] = walsnd->flush;
630  apply_array[i] = walsnd->apply;
631  SpinLockRelease(&walsnd->mutex);
632 
633  i++;
634  }
635 
636  /* Sort each array in descending order */
637  qsort(write_array, len, sizeof(XLogRecPtr), cmp_lsn);
638  qsort(flush_array, len, sizeof(XLogRecPtr), cmp_lsn);
639  qsort(apply_array, len, sizeof(XLogRecPtr), cmp_lsn);
640 
641  /* Get Nth latest Write, Flush, Apply positions */
642  *writePtr = write_array[nth - 1];
643  *flushPtr = flush_array[nth - 1];
644  *applyPtr = apply_array[nth - 1];
645 
646  pfree(write_array);
647  pfree(flush_array);
648  pfree(apply_array);
649 }
650 
651 /*
652  * Compare lsn in order to sort array in descending order.
653  */
654 static int
655 cmp_lsn(const void *a, const void *b)
656 {
657  XLogRecPtr lsn1 = *((const XLogRecPtr *) a);
658  XLogRecPtr lsn2 = *((const XLogRecPtr *) b);
659 
660  if (lsn1 > lsn2)
661  return -1;
662  else if (lsn1 == lsn2)
663  return 0;
664  else
665  return 1;
666 }
667 
668 /*
669  * Return the list of sync standbys, or NIL if no sync standby is connected.
670  *
671  * The caller must hold SyncRepLock.
672  *
673  * On return, *am_sync is set to true if this walsender is connecting to
674  * sync standby. Otherwise it's set to false.
675  */
676 List *
678 {
679  /* Set default result */
680  if (am_sync != NULL)
681  *am_sync = false;
682 
683  /* Quick exit if sync replication is not requested */
684  if (SyncRepConfig == NULL)
685  return NIL;
686 
687  return (SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY) ?
690 }
691 
692 /*
693  * Return the list of all the candidates for quorum sync standbys,
694  * or NIL if no such standby is connected.
695  *
696  * The caller must hold SyncRepLock. This function must be called only in
697  * a quorum-based sync replication.
698  *
699  * On return, *am_sync is set to true if this walsender is connecting to
700  * sync standby. Otherwise it's set to false.
701  */
702 static List *
704 {
705  List *result = NIL;
706  int i;
707  volatile WalSnd *walsnd; /* Use volatile pointer to prevent code
708  * rearrangement */
709 
710  Assert(SyncRepConfig->syncrep_method == SYNC_REP_QUORUM);
711 
712  for (i = 0; i < max_wal_senders; i++)
713  {
714  walsnd = &WalSndCtl->walsnds[i];
715 
716  /* Must be active */
717  if (walsnd->pid == 0)
718  continue;
719 
720  /* Must be streaming */
721  if (walsnd->state != WALSNDSTATE_STREAMING)
722  continue;
723 
724  /* Must be synchronous */
725  if (walsnd->sync_standby_priority == 0)
726  continue;
727 
728  /* Must have a valid flush position */
729  if (XLogRecPtrIsInvalid(walsnd->flush))
730  continue;
731 
732  /*
733  * Consider this standby as a candidate for quorum sync standbys and
734  * append it to the result.
735  */
736  result = lappend_int(result, i);
737  if (am_sync != NULL && walsnd == MyWalSnd)
738  *am_sync = true;
739  }
740 
741  return result;
742 }
743 
744 /*
745  * Return the list of sync standbys chosen based on their priorities,
746  * or NIL if no sync standby is connected.
747  *
748  * If there are multiple standbys with the same priority,
749  * the first one found is selected preferentially.
750  *
751  * The caller must hold SyncRepLock. This function must be called only in
752  * a priority-based sync replication.
753  *
754  * On return, *am_sync is set to true if this walsender is connecting to
755  * sync standby. Otherwise it's set to false.
756  */
757 static List *
759 {
760  List *result = NIL;
761  List *pending = NIL;
762  int lowest_priority;
763  int next_highest_priority;
764  int this_priority;
765  int priority;
766  int i;
767  bool am_in_pending = false;
768  volatile WalSnd *walsnd; /* Use volatile pointer to prevent code
769  * rearrangement */
770 
771  Assert(SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY);
772 
773  lowest_priority = SyncRepConfig->nmembers;
774  next_highest_priority = lowest_priority + 1;
775 
776  /*
777  * Find the sync standbys which have the highest priority (i.e, 1). Also
778  * store all the other potential sync standbys into the pending list, in
779  * order to scan it later and find other sync standbys from it quickly.
780  */
781  for (i = 0; i < max_wal_senders; i++)
782  {
783  walsnd = &WalSndCtl->walsnds[i];
784 
785  /* Must be active */
786  if (walsnd->pid == 0)
787  continue;
788 
789  /* Must be streaming */
790  if (walsnd->state != WALSNDSTATE_STREAMING)
791  continue;
792 
793  /* Must be synchronous */
794  this_priority = walsnd->sync_standby_priority;
795  if (this_priority == 0)
796  continue;
797 
798  /* Must have a valid flush position */
799  if (XLogRecPtrIsInvalid(walsnd->flush))
800  continue;
801 
802  /*
803  * If the priority is equal to 1, consider this standby as sync and
804  * append it to the result. Otherwise append this standby to the
805  * pending list to check if it's actually sync or not later.
806  */
807  if (this_priority == 1)
808  {
809  result = lappend_int(result, i);
810  if (am_sync != NULL && walsnd == MyWalSnd)
811  *am_sync = true;
812  if (list_length(result) == SyncRepConfig->num_sync)
813  {
814  list_free(pending);
815  return result; /* Exit if got enough sync standbys */
816  }
817  }
818  else
819  {
820  pending = lappend_int(pending, i);
821  if (am_sync != NULL && walsnd == MyWalSnd)
822  am_in_pending = true;
823 
824  /*
825  * Track the highest priority among the standbys in the pending
826  * list, in order to use it as the starting priority for later
827  * scan of the list. This is useful to find quickly the sync
828  * standbys from the pending list later because we can skip
829  * unnecessary scans for the unused priorities.
830  */
831  if (this_priority < next_highest_priority)
832  next_highest_priority = this_priority;
833  }
834  }
835 
836  /*
837  * Consider all pending standbys as sync if the number of them plus
838  * already-found sync ones is lower than the configuration requests.
839  */
840  if (list_length(result) + list_length(pending) <= SyncRepConfig->num_sync)
841  {
842  bool needfree = (result != NIL && pending != NIL);
843 
844  /*
845  * Set *am_sync to true if this walsender is in the pending list
846  * because all pending standbys are considered as sync.
847  */
848  if (am_sync != NULL && !(*am_sync))
849  *am_sync = am_in_pending;
850 
851  result = list_concat(result, pending);
852  if (needfree)
853  pfree(pending);
854  return result;
855  }
856 
857  /*
858  * Find the sync standbys from the pending list.
859  */
860  priority = next_highest_priority;
861  while (priority <= lowest_priority)
862  {
863  ListCell *cell;
864  ListCell *prev = NULL;
865  ListCell *next;
866 
867  next_highest_priority = lowest_priority + 1;
868 
869  for (cell = list_head(pending); cell != NULL; cell = next)
870  {
871  i = lfirst_int(cell);
872  walsnd = &WalSndCtl->walsnds[i];
873 
874  next = lnext(cell);
875 
876  this_priority = walsnd->sync_standby_priority;
877  if (this_priority == priority)
878  {
879  result = lappend_int(result, i);
880  if (am_sync != NULL && walsnd == MyWalSnd)
881  *am_sync = true;
882 
883  /*
884  * We should always exit here after the scan of pending list
885  * starts because we know that the list has enough elements to
886  * reach SyncRepConfig->num_sync.
887  */
888  if (list_length(result) == SyncRepConfig->num_sync)
889  {
890  list_free(pending);
891  return result; /* Exit if got enough sync standbys */
892  }
893 
894  /*
895  * Remove the entry for this sync standby from the list to
896  * prevent us from looking at the same entry again.
897  */
898  pending = list_delete_cell(pending, cell, prev);
899 
900  continue;
901  }
902 
903  if (this_priority < next_highest_priority)
904  next_highest_priority = this_priority;
905 
906  prev = cell;
907  }
908 
909  priority = next_highest_priority;
910  }
911 
912  /* never reached, but keep compiler quiet */
913  Assert(false);
914  return result;
915 }
916 
917 /*
918  * Check if we are in the list of sync standbys, and if so, determine
919  * priority sequence. Return priority if set, or zero to indicate that
920  * we are not a potential sync standby.
921  *
922  * Compare the parameter SyncRepStandbyNames against the application_name
923  * for this WALSender, or allow any name if we find a wildcard "*".
924  */
925 static int
927 {
928  const char *standby_name;
929  int priority;
930  bool found = false;
931 
932  /*
933  * Since synchronous cascade replication is not allowed, we always set the
934  * priority of cascading walsender to zero.
935  */
937  return 0;
938 
939  if (!SyncStandbysDefined() || SyncRepConfig == NULL)
940  return 0;
941 
942  standby_name = SyncRepConfig->member_names;
943  for (priority = 1; priority <= SyncRepConfig->nmembers; priority++)
944  {
945  if (pg_strcasecmp(standby_name, application_name) == 0 ||
946  strcmp(standby_name, "*") == 0)
947  {
948  found = true;
949  break;
950  }
951  standby_name += strlen(standby_name) + 1;
952  }
953 
954  if (!found)
955  return 0;
956 
957  /*
958  * In quorum-based sync replication, all the standbys in the list have the
959  * same priority, one.
960  */
961  return (SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY) ? priority : 1;
962 }
963 
964 /*
965  * Walk the specified queue from head. Set the state of any backends that
966  * need to be woken, remove them from the queue, and then wake them.
967  * Pass all = true to wake whole queue; otherwise, just wake up to
968  * the walsender's LSN.
969  *
970  * Must hold SyncRepLock.
971  */
972 static int
973 SyncRepWakeQueue(bool all, int mode)
974 {
975  volatile WalSndCtlData *walsndctl = WalSndCtl;
976  PGPROC *proc = NULL;
977  PGPROC *thisproc = NULL;
978  int numprocs = 0;
979 
980  Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);
981  Assert(SyncRepQueueIsOrderedByLSN(mode));
982 
983  proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
984  &(WalSndCtl->SyncRepQueue[mode]),
985  offsetof(PGPROC, syncRepLinks));
986 
987  while (proc)
988  {
989  /*
990  * Assume the queue is ordered by LSN
991  */
992  if (!all && walsndctl->lsn[mode] < proc->waitLSN)
993  return numprocs;
994 
995  /*
996  * Move to next proc, so we can delete thisproc from the queue.
997  * thisproc is valid, proc may be NULL after this.
998  */
999  thisproc = proc;
1000  proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
1001  &(proc->syncRepLinks),
1002  offsetof(PGPROC, syncRepLinks));
1003 
1004  /*
1005  * Set state to complete; see SyncRepWaitForLSN() for discussion of
1006  * the various states.
1007  */
1009 
1010  /*
1011  * Remove thisproc from queue.
1012  */
1013  SHMQueueDelete(&(thisproc->syncRepLinks));
1014 
1015  /*
1016  * Wake only when we have set state and removed from queue.
1017  */
1018  SetLatch(&(thisproc->procLatch));
1019 
1020  numprocs++;
1021  }
1022 
1023  return numprocs;
1024 }
1025 
1026 /*
1027  * The checkpointer calls this as needed to update the shared
1028  * sync_standbys_defined flag, so that backends don't remain permanently wedged
1029  * if synchronous_standby_names is unset. It's safe to check the current value
1030  * without the lock, because it's only ever updated by one process. But we
1031  * must take the lock to change it.
1032  */
1033 void
1035 {
1036  bool sync_standbys_defined = SyncStandbysDefined();
1037 
1038  if (sync_standbys_defined != WalSndCtl->sync_standbys_defined)
1039  {
1040  LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
1041 
1042  /*
1043  * If synchronous_standby_names has been reset to empty, it's futile
1044  * for backends to continue to waiting. Since the user no longer
1045  * wants synchronous replication, we'd better wake them up.
1046  */
1047  if (!sync_standbys_defined)
1048  {
1049  int i;
1050 
1051  for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
1052  SyncRepWakeQueue(true, i);
1053  }
1054 
1055  /*
1056  * Only allow people to join the queue when there are synchronous
1057  * standbys defined. Without this interlock, there's a race
1058  * condition: we might wake up all the current waiters; then, some
1059  * backend that hasn't yet reloaded its config might go to sleep on
1060  * the queue (and never wake up). This prevents that.
1061  */
1062  WalSndCtl->sync_standbys_defined = sync_standbys_defined;
1063 
1064  LWLockRelease(SyncRepLock);
1065  }
1066 }
1067 
1068 #ifdef USE_ASSERT_CHECKING
1069 static bool
1070 SyncRepQueueIsOrderedByLSN(int mode)
1071 {
1072  PGPROC *proc = NULL;
1073  XLogRecPtr lastLSN;
1074 
1075  Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);
1076 
1077  lastLSN = 0;
1078 
1079  proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
1080  &(WalSndCtl->SyncRepQueue[mode]),
1081  offsetof(PGPROC, syncRepLinks));
1082 
1083  while (proc)
1084  {
1085  /*
1086  * Check the queue is ordered by LSN and that multiple procs don't
1087  * have matching LSNs
1088  */
1089  if (proc->waitLSN <= lastLSN)
1090  return false;
1091 
1092  lastLSN = proc->waitLSN;
1093 
1094  proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
1095  &(proc->syncRepLinks),
1096  offsetof(PGPROC, syncRepLinks));
1097  }
1098 
1099  return true;
1100 }
1101 #endif
1102 
1103 /*
1104  * ===========================================================
1105  * Synchronous Replication functions executed by any process
1106  * ===========================================================
1107  */
1108 
1109 bool
1110 check_synchronous_standby_names(char **newval, void **extra, GucSource source)
1111 {
1112  if (*newval != NULL && (*newval)[0] != '\0')
1113  {
1114  int parse_rc;
1115  SyncRepConfigData *pconf;
1116 
1117  /* Reset communication variables to ensure a fresh start */
1120 
1121  /* Parse the synchronous_standby_names string */
1122  syncrep_scanner_init(*newval);
1123  parse_rc = syncrep_yyparse();
1125 
1126  if (parse_rc != 0 || syncrep_parse_result == NULL)
1127  {
1128  GUC_check_errcode(ERRCODE_SYNTAX_ERROR);
1131  else
1132  GUC_check_errdetail("synchronous_standby_names parser failed");
1133  return false;
1134  }
1135 
1136  if (syncrep_parse_result->num_sync <= 0)
1137  {
1138  GUC_check_errmsg("number of synchronous standbys (%d) must be greater than zero",
1140  return false;
1141  }
1142 
1143  /* GUC extra value must be malloc'd, not palloc'd */
1144  pconf = (SyncRepConfigData *)
1146  if (pconf == NULL)
1147  return false;
1149 
1150  *extra = (void *) pconf;
1151 
1152  /*
1153  * We need not explicitly clean up syncrep_parse_result. It, and any
1154  * other cruft generated during parsing, will be freed when the
1155  * current memory context is deleted. (This code is generally run in
1156  * a short-lived context used for config file processing, so that will
1157  * not be very long.)
1158  */
1159  }
1160  else
1161  *extra = NULL;
1162 
1163  return true;
1164 }
1165 
1166 void
1167 assign_synchronous_standby_names(const char *newval, void *extra)
1168 {
1169  SyncRepConfig = (SyncRepConfigData *) extra;
1170 }
1171 
1172 void
1174 {
1175  switch (newval)
1176  {
1179  break;
1182  break;
1185  break;
1186  default:
1188  break;
1189  }
1190 }
void syncrep_scanner_finish(void)
#define NIL
Definition: pg_list.h:69
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:1034
XLogRecPtr write
void assign_synchronous_standby_names(const char *newval, void *extra)
Definition: syncrep.c:1167
Pointer SHMQueuePrev(const SHM_QUEUE *queue, const SHM_QUEUE *curElem, Size linkOffset)
Definition: shmqueue.c:164
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static List * SyncRepGetSyncStandbysPriority(bool *am_sync)
Definition: syncrep.c:758
static void SyncRepCancelWait(void)
Definition: syncrep.c:350
#define DEBUG1
Definition: elog.h:25
void syncrep_scanner_init(const char *query_string)
static int32 next
Definition: blutils.c:210
static bool SyncRepGetSyncRecPtr(XLogRecPtr *writePtr, XLogRecPtr *flushPtr, XLogRecPtr *applyPtr, bool *am_sync)
Definition: syncrep.c:515
#define DEBUG3
Definition: elog.h:23
#define SYNC_REP_PRIORITY
Definition: syncrep.h:36
bool update_process_title
Definition: ps_status.c:35
#define write(a, b, c)
Definition: win32.h:14
#define GUC_check_errdetail
Definition: guc.h:407
static void SyncRepQueueInsert(int mode)
Definition: syncrep.c:317
PGPROC * MyProc
Definition: proc.c:67
char * syncrep_parse_error_msg
#define SYNC_REP_WAITING
Definition: syncrep.h:32
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
uint8 syncrep_method
Definition: syncrep.h:51
#define Min(x, y)
Definition: c.h:806
unsigned char uint8
Definition: c.h:266
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
#define SYNC_REP_NOT_WAITING
Definition: syncrep.h:31
WalSndCtlData * WalSndCtl
Definition: walsender.c:108
static void SyncRepGetNthLatestSyncRecPtr(XLogRecPtr *writePtr, XLogRecPtr *flushPtr, XLogRecPtr *applyPtr, List *sync_standbys, uint8 nth)
Definition: syncrep.c:608
int errcode(int sqlerrcode)
Definition: elog.c:575
#define GUC_check_errmsg
Definition: guc.h:403
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1633
WalSnd walsnds[FLEXIBLE_ARRAY_MEMBER]
List * SyncRepGetSyncStandbys(bool *am_sync)
Definition: syncrep.c:677
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void ResetLatch(volatile Latch *latch)
Definition: latch.c:498
#define LOG
Definition: elog.h:26
SyncRepConfigData * SyncRepConfig
Definition: syncrep.c:97
volatile bool QueryCancelPending
Definition: globals.c:30
void GUC_check_errcode(int sqlerrcode)
Definition: guc.c:9773
static int SyncRepWakeQueue(bool all, int mode)
Definition: syncrep.c:973
slock_t mutex
Latch procLatch
Definition: proc.h:103
GucSource
Definition: guc.h:105
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr flush
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
void pfree(void *pointer)
Definition: mcxt.c:950
static int cmp_lsn(const void *a, const void *b)
Definition: syncrep.c:655
#define SYNC_REP_NO_WAIT
Definition: syncrep.h:23
#define SYNC_REP_WAIT_APPLY
Definition: syncrep.h:26
#define lfirst_int(lc)
Definition: pg_list.h:107
void SHMQueueInsertAfter(SHM_QUEUE *queue, SHM_QUEUE *elem)
Definition: shmqueue.c:108
static bool announce_next_takeover
Definition: syncrep.c:95
Definition: dest.h:88
const char * get_ps_display(int *displen)
Definition: ps_status.c:405
WalSndState state
void assign_synchronous_commit(int newval, void *extra)
Definition: syncrep.c:1173
#define SyncStandbysDefined()
Definition: syncrep.c:92
bool PostmasterIsAlive(void)
Definition: pmsignal.c:272
int errdetail(const char *fmt,...)
Definition: elog.c:873
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
unsigned int uint32
Definition: c.h:268
SHM_QUEUE SyncRepQueue[NUM_SYNC_REP_WAIT_MODE]
void SyncRepInitConfig(void)
Definition: syncrep.c:381
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define SYNC_REP_WAIT_FLUSH
Definition: syncrep.h:25
List * lappend_int(List *list, int datum)
Definition: list.c:146
#define SyncRepRequested()
Definition: syncrep.h:19
int max_wal_senders
Definition: walsender.c:120
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define WARNING
Definition: elog.h:40
#define SpinLockRelease(lock)
Definition: spin.h:64
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
char * SyncRepStandbyNames
Definition: syncrep.c:90
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
Pointer SHMQueueNext(const SHM_QUEUE *queue, const SHM_QUEUE *curElem, Size linkOffset)
Definition: shmqueue.c:145
WalSnd * MyWalSnd
Definition: walsender.c:111
static List * SyncRepGetSyncStandbysQuorum(bool *am_sync)
Definition: syncrep.c:703
#define SYNC_REP_WAIT_COMPLETE
Definition: syncrep.h:33
#define SYNC_REP_QUORUM
Definition: syncrep.h:37
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
char member_names[FLEXIBLE_ARRAY_MEMBER]
Definition: syncrep.h:54
int sync_standby_priority
bool SHMQueueIsDetached(const SHM_QUEUE *queue)
Definition: shmqueue.c:47
SyncRepConfigData * syncrep_parse_result
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
bool check_synchronous_standby_names(char **newval, void **extra, GucSource source)
Definition: syncrep.c:1110
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
SHM_QUEUE syncRepLinks
Definition: proc.h:149
void SyncRepCleanupAtProcExit(void)
Definition: syncrep.c:360
XLogRecPtr lsn[NUM_SYNC_REP_WAIT_MODE]
volatile bool ProcDiePending
Definition: globals.c:31
char * application_name
Definition: guc.c:469
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
int i
static void SyncRepGetOldestSyncRecPtr(XLogRecPtr *writePtr, XLogRecPtr *flushPtr, XLogRecPtr *applyPtr, List *sync_standbys)
Definition: syncrep.c:572
void SHMQueueDelete(SHM_QUEUE *queue)
Definition: shmqueue.c:68
struct Latch * MyLatch
Definition: globals.c:52
int syncrep_yyparse(void)
#define elog
Definition: elog.h:219
#define NUM_SYNC_REP_WAIT_MODE
Definition: syncrep.h:28
#define qsort(a, b, c, d)
Definition: port.h:440
int syncRepState
Definition: proc.h:148
CommandDest whereToSendOutput
Definition: postgres.c:88
XLogRecPtr apply
Definition: proc.h:94
Definition: pg_list.h:45
static int SyncRepWaitMode
Definition: syncrep.c:98
#define WL_LATCH_SET
Definition: latch.h:124
void SyncRepReleaseWaiters(void)
Definition: syncrep.c:409
XLogRecPtr waitLSN
Definition: proc.h:147
#define offsetof(type, field)
Definition: c.h:555
bool am_cascading_walsender
Definition: walsender.c:115
#define SYNC_REP_WAIT_WRITE
Definition: syncrep.h:24
static int SyncRepGetStandbyPriority(void)
Definition: syncrep.c:926