PostgreSQL Source Code  git master
walsender.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * walsender.c
4  *
5  * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
6  * care of sending XLOG from the primary server to a single recipient.
7  * (Note that there can be more than one walsender process concurrently.)
8  * It is started by the postmaster when the walreceiver of a standby server
9  * connects to the primary server and requests XLOG streaming replication.
10  *
11  * A walsender is similar to a regular backend, ie. there is a one-to-one
12  * relationship between a connection and a walsender process, but instead
13  * of processing SQL queries, it understands a small set of special
14  * replication-mode commands. The START_REPLICATION command begins streaming
15  * WAL to the client. While streaming, the walsender keeps reading XLOG
16  * records from the disk and sends them to the standby server over the
17  * COPY protocol, until either side ends the replication by exiting COPY
18  * mode (or until the connection is closed).
19  *
20  * Normal termination is by SIGTERM, which instructs the walsender to
21  * close the connection and exit(0) at the next convenient moment. Emergency
22  * termination is by SIGQUIT; like any backend, the walsender will simply
23  * abort and exit on SIGQUIT. A close of the connection and a FATAL error
24  * are treated as not a crash but approximately normal termination;
25  * the walsender will exit quickly without sending any more XLOG records.
26  *
27  * If the server is shut down, checkpointer sends us
28  * PROCSIG_WALSND_INIT_STOPPING after all regular backends have exited. If
29  * the backend is idle or runs an SQL query this causes the backend to
30  * shutdown, if logical replication is in progress all existing WAL records
31  * are processed followed by a shutdown. Otherwise this causes the walsender
32  * to switch to the "stopping" state. In this state, the walsender will reject
33  * any further replication commands. The checkpointer begins the shutdown
34  * checkpoint once all walsenders are confirmed as stopping. When the shutdown
35  * checkpoint finishes, the postmaster sends us SIGUSR2. This instructs
36  * walsender to send any outstanding WAL, including the shutdown checkpoint
37  * record, wait for it to be replicated to the standby, and then exit.
38  *
39  *
40  * Portions Copyright (c) 2010-2021, PostgreSQL Global Development Group
41  *
42  * IDENTIFICATION
43  * src/backend/replication/walsender.c
44  *
45  *-------------------------------------------------------------------------
46  */
47 #include "postgres.h"
48 
49 #include <signal.h>
50 #include <unistd.h>
51 
52 #include "access/printtup.h"
53 #include "access/timeline.h"
54 #include "access/transam.h"
55 #include "access/xact.h"
56 #include "access/xlog_internal.h"
57 #include "access/xlogreader.h"
58 #include "access/xlogutils.h"
59 #include "catalog/pg_authid.h"
60 #include "catalog/pg_type.h"
61 #include "commands/dbcommands.h"
62 #include "commands/defrem.h"
63 #include "funcapi.h"
64 #include "libpq/libpq.h"
65 #include "libpq/pqformat.h"
66 #include "miscadmin.h"
67 #include "nodes/replnodes.h"
68 #include "pgstat.h"
69 #include "postmaster/interrupt.h"
70 #include "replication/basebackup.h"
71 #include "replication/decode.h"
72 #include "replication/logical.h"
73 #include "replication/slot.h"
74 #include "replication/snapbuild.h"
75 #include "replication/syncrep.h"
77 #include "replication/walsender.h"
80 #include "storage/fd.h"
81 #include "storage/ipc.h"
82 #include "storage/pmsignal.h"
83 #include "storage/proc.h"
84 #include "storage/procarray.h"
85 #include "tcop/dest.h"
86 #include "tcop/tcopprot.h"
87 #include "utils/acl.h"
88 #include "utils/builtins.h"
89 #include "utils/guc.h"
90 #include "utils/memutils.h"
91 #include "utils/pg_lsn.h"
92 #include "utils/portal.h"
93 #include "utils/ps_status.h"
94 #include "utils/timeout.h"
95 #include "utils/timestamp.h"
96 
97 /*
98  * Maximum data payload in a WAL data message. Must be >= XLOG_BLCKSZ.
99  *
100  * We don't have a good idea of what a good value would be; there's some
101  * overhead per message in both walsender and walreceiver, but on the other
102  * hand sending large batches makes walsender less responsive to signals
103  * because signals are checked only between messages. 128kB (with
104  * default 8k blocks) seems like a reasonable guess for now.
105  */
106 #define MAX_SEND_SIZE (XLOG_BLCKSZ * 16)
107 
108 /* Array of WalSnds in shared memory */
110 
111 /* My slot in the shared memory array */
112 WalSnd *MyWalSnd = NULL;
113 
114 /* Global state */
115 bool am_walsender = false; /* Am I a walsender process? */
116 bool am_cascading_walsender = false; /* Am I cascading WAL to another
117  * standby? */
118 bool am_db_walsender = false; /* Connected to a database? */
119 
120 /* User-settable parameters for walsender */
121 int max_wal_senders = 0; /* the maximum number of concurrent
122  * walsenders */
123 int wal_sender_timeout = 60 * 1000; /* maximum time to send one WAL
124  * data message */
126 
127 /*
128  * State for WalSndWakeupRequest
129  */
130 bool wake_wal_senders = false;
131 
132 /*
133  * xlogreader used for replication. Note that a WAL sender doing physical
134  * replication does not need xlogreader to read WAL, but it needs one to
135  * keep a state of its work.
136  */
138 
139 /*
140  * These variables keep track of the state of the timeline we're currently
141  * sending. sendTimeLine identifies the timeline. If sendTimeLineIsHistoric,
142  * the timeline is not the latest timeline on this server, and the server's
143  * history forked off from that timeline at sendTimeLineValidUpto.
144  */
147 static bool sendTimeLineIsHistoric = false;
149 
150 /*
151  * How far have we sent WAL already? This is also advertised in
152  * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
153  */
155 
156 /* Buffers for constructing outgoing messages and processing reply messages. */
160 
161 /* Timestamp of last ProcessRepliesIfAny(). */
163 
164 /*
165  * Timestamp of last ProcessRepliesIfAny() that saw a reply from the
166  * standby. Set to 0 if wal_sender_timeout doesn't need to be active.
167  */
169 
170 /* Have we sent a heartbeat message asking for reply, since last reply? */
171 static bool waiting_for_ping_response = false;
172 
173 /*
174  * While streaming WAL in Copy mode, streamingDoneSending is set to true
175  * after we have sent CopyDone. We should not send any more CopyData messages
176  * after that. streamingDoneReceiving is set to true when we receive CopyDone
177  * from the other end. When both become true, it's time to exit Copy mode.
178  */
181 
182 /* Are we there yet? */
183 static bool WalSndCaughtUp = false;
184 
185 /* Flags set by signal handlers for later service in main loop */
186 static volatile sig_atomic_t got_SIGUSR2 = false;
187 static volatile sig_atomic_t got_STOPPING = false;
188 
189 /*
190  * This is set while we are streaming. When not set
191  * PROCSIG_WALSND_INIT_STOPPING signal will be handled like SIGTERM. When set,
192  * the main loop is responsible for checking got_STOPPING and terminating when
193  * it's set (after streaming any remaining WAL).
194  */
195 static volatile sig_atomic_t replication_active = false;
196 
198 
199 /* A sample associating a WAL location with the time it was written. */
200 typedef struct
201 {
204 } WalTimeSample;
205 
206 /* The size of our buffer of time samples. */
207 #define LAG_TRACKER_BUFFER_SIZE 8192
208 
209 /* A mechanism for tracking replication lag. */
210 typedef struct
211 {
215  int read_heads[NUM_SYNC_REP_WAIT_MODE];
217 } LagTracker;
218 
220 
221 /* Signal handlers */
223 
224 /* Prototypes for private functions */
225 typedef void (*WalSndSendDataCallback) (void);
226 static void WalSndLoop(WalSndSendDataCallback send_data);
227 static void InitWalSenderSlot(void);
228 static void WalSndKill(int code, Datum arg);
230 static void XLogSendPhysical(void);
231 static void XLogSendLogical(void);
232 static void WalSndDone(WalSndSendDataCallback send_data);
233 static XLogRecPtr GetStandbyFlushRecPtr(void);
234 static void IdentifySystem(void);
237 static void StartReplication(StartReplicationCmd *cmd);
239 static void ProcessStandbyMessage(void);
240 static void ProcessStandbyReplyMessage(void);
241 static void ProcessStandbyHSFeedbackMessage(void);
242 static void ProcessRepliesIfAny(void);
243 static void WalSndKeepalive(bool requestReply);
244 static void WalSndKeepaliveIfNecessary(void);
245 static void WalSndCheckTimeOut(void);
247 static void WalSndWait(uint32 socket_events, long timeout, uint32 wait_event);
248 static void WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
249 static void WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
252 static void LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time);
253 static TimeOffset LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now);
255 
256 static void WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
257  TimeLineID *tli_p);
258 
259 
260 /* Initialize walsender process before entering the main command loop */
261 void
262 InitWalSender(void)
263 {
265 
266  /* Create a per-walsender data structure in shared memory */
268 
269  /*
270  * We don't currently need any ResourceOwner in a walsender process, but
271  * if we did, we could call CreateAuxProcessResourceOwner here.
272  */
273 
274  /*
275  * Let postmaster know that we're a WAL sender. Once we've declared us as
276  * a WAL sender process, postmaster will let us outlive the bgwriter and
277  * kill us last in the shutdown sequence, so we get a chance to stream all
278  * remaining WAL at shutdown, including the shutdown checkpoint. Note that
279  * there's no going back, and we mustn't write any WAL records after this.
280  */
283 
284  /* Initialize empty timestamp buffer for lag tracking. */
285  lag_tracker = MemoryContextAllocZero(TopMemoryContext, sizeof(LagTracker));
286 }
287 
288 /*
289  * Clean up after an error.
290  *
291  * WAL sender processes don't use transactions like regular backends do.
292  * This function does any cleanup required after an error in a WAL sender
293  * process, similar to what transaction abort does in a regular backend.
294  */
295 void
297 {
301 
302  if (xlogreader != NULL && xlogreader->seg.ws_file >= 0)
303  wal_segment_close(xlogreader);
304 
305  if (MyReplicationSlot != NULL)
307 
309 
310  replication_active = false;
311 
312  /*
313  * If there is a transaction in progress, it will clean up our
314  * ResourceOwner, but if a replication command set up a resource owner
315  * without a transaction, we've got to clean that up now.
316  */
318  WalSndResourceCleanup(false);
319 
320  if (got_STOPPING || got_SIGUSR2)
321  proc_exit(0);
322 
323  /* Revert back to startup state */
325 }
326 
327 /*
328  * Clean up any ResourceOwner we created.
329  */
330 void
331 WalSndResourceCleanup(bool isCommit)
332 {
333  ResourceOwner resowner;
334 
335  if (CurrentResourceOwner == NULL)
336  return;
337 
338  /*
339  * Deleting CurrentResourceOwner is not allowed, so we must save a pointer
340  * in a local variable and clear it first.
341  */
342  resowner = CurrentResourceOwner;
343  CurrentResourceOwner = NULL;
344 
345  /* Now we can release resources and delete it. */
346  ResourceOwnerRelease(resowner,
347  RESOURCE_RELEASE_BEFORE_LOCKS, isCommit, true);
348  ResourceOwnerRelease(resowner,
349  RESOURCE_RELEASE_LOCKS, isCommit, true);
350  ResourceOwnerRelease(resowner,
351  RESOURCE_RELEASE_AFTER_LOCKS, isCommit, true);
352  ResourceOwnerDelete(resowner);
353 }
354 
355 /*
356  * Handle a client's connection abort in an orderly manner.
357  */
358 static void
359 WalSndShutdown(void)
360 {
361  /*
362  * Reset whereToSendOutput to prevent ereport from attempting to send any
363  * more messages to the standby.
364  */
367 
368  proc_exit(0);
369  abort(); /* keep the compiler quiet */
370 }
371 
372 /*
373  * Handle the IDENTIFY_SYSTEM command.
374  */
375 static void
377 {
378  char sysid[32];
379  char xloc[MAXFNAMELEN];
380  XLogRecPtr logptr;
381  char *dbname = NULL;
383  TupOutputState *tstate;
384  TupleDesc tupdesc;
385  Datum values[4];
386  bool nulls[4];
387 
388  /*
389  * Reply with a result set with one row, four columns. First col is system
390  * ID, second is timeline ID, third is current xlog location and the
391  * fourth contains the database name if we are connected to one.
392  */
393 
394  snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
396 
399  {
400  /* this also updates ThisTimeLineID */
401  logptr = GetStandbyFlushRecPtr();
402  }
403  else
404  logptr = GetFlushRecPtr();
405 
406  snprintf(xloc, sizeof(xloc), "%X/%X", LSN_FORMAT_ARGS(logptr));
407 
408  if (MyDatabaseId != InvalidOid)
409  {
411 
412  /* syscache access needs a transaction env. */
414  /* make dbname live outside TX context */
418  /* CommitTransactionCommand switches to TopMemoryContext */
420  }
421 
423  MemSet(nulls, false, sizeof(nulls));
424 
425  /* need a tuple descriptor representing four columns */
426  tupdesc = CreateTemplateTupleDesc(4);
427  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "systemid",
428  TEXTOID, -1, 0);
429  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "timeline",
430  INT4OID, -1, 0);
431  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "xlogpos",
432  TEXTOID, -1, 0);
433  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "dbname",
434  TEXTOID, -1, 0);
435 
436  /* prepare for projection of tuples */
437  tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
438 
439  /* column 1: system identifier */
440  values[0] = CStringGetTextDatum(sysid);
441 
442  /* column 2: timeline */
443  values[1] = Int32GetDatum(ThisTimeLineID);
444 
445  /* column 3: wal location */
446  values[2] = CStringGetTextDatum(xloc);
447 
448  /* column 4: database name, or NULL if none */
449  if (dbname)
450  values[3] = CStringGetTextDatum(dbname);
451  else
452  nulls[3] = true;
453 
454  /* send it to dest */
455  do_tup_output(tstate, values, nulls);
456 
457  end_tup_output(tstate);
458 }
459 
460 
461 /*
462  * Handle TIMELINE_HISTORY command.
463  */
464 static void
466 {
468  char histfname[MAXFNAMELEN];
469  char path[MAXPGPATH];
470  int fd;
471  off_t histfilelen;
472  off_t bytesleft;
473  Size len;
474 
475  /*
476  * Reply with a result set with one row, and two columns. The first col is
477  * the name of the history file, 2nd is the contents.
478  */
479 
480  TLHistoryFileName(histfname, cmd->timeline);
481  TLHistoryFilePath(path, cmd->timeline);
482 
483  /* Send a RowDescription message */
484  pq_beginmessage(&buf, 'T');
485  pq_sendint16(&buf, 2); /* 2 fields */
486 
487  /* first field */
488  pq_sendstring(&buf, "filename"); /* col name */
489  pq_sendint32(&buf, 0); /* table oid */
490  pq_sendint16(&buf, 0); /* attnum */
491  pq_sendint32(&buf, TEXTOID); /* type oid */
492  pq_sendint16(&buf, -1); /* typlen */
493  pq_sendint32(&buf, 0); /* typmod */
494  pq_sendint16(&buf, 0); /* format code */
495 
496  /* second field */
497  pq_sendstring(&buf, "content"); /* col name */
498  pq_sendint32(&buf, 0); /* table oid */
499  pq_sendint16(&buf, 0); /* attnum */
500  pq_sendint32(&buf, TEXTOID); /* type oid */
501  pq_sendint16(&buf, -1); /* typlen */
502  pq_sendint32(&buf, 0); /* typmod */
503  pq_sendint16(&buf, 0); /* format code */
504  pq_endmessage(&buf);
505 
506  /* Send a DataRow message */
507  pq_beginmessage(&buf, 'D');
508  pq_sendint16(&buf, 2); /* # of columns */
509  len = strlen(histfname);
510  pq_sendint32(&buf, len); /* col1 len */
511  pq_sendbytes(&buf, histfname, len);
512 
513  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
514  if (fd < 0)
515  ereport(ERROR,
517  errmsg("could not open file \"%s\": %m", path)));
518 
519  /* Determine file length and send it to client */
520  histfilelen = lseek(fd, 0, SEEK_END);
521  if (histfilelen < 0)
522  ereport(ERROR,
524  errmsg("could not seek to end of file \"%s\": %m", path)));
525  if (lseek(fd, 0, SEEK_SET) != 0)
526  ereport(ERROR,
528  errmsg("could not seek to beginning of file \"%s\": %m", path)));
529 
530  pq_sendint32(&buf, histfilelen); /* col2 len */
531 
532  bytesleft = histfilelen;
533  while (bytesleft > 0)
534  {
535  PGAlignedBlock rbuf;
536  int nread;
537 
539  nread = read(fd, rbuf.data, sizeof(rbuf));
541  if (nread < 0)
542  ereport(ERROR,
544  errmsg("could not read file \"%s\": %m",
545  path)));
546  else if (nread == 0)
547  ereport(ERROR,
549  errmsg("could not read file \"%s\": read %d of %zu",
550  path, nread, (Size) bytesleft)));
551 
552  pq_sendbytes(&buf, rbuf.data, nread);
553  bytesleft -= nread;
554  }
555 
556  if (CloseTransientFile(fd) != 0)
557  ereport(ERROR,
559  errmsg("could not close file \"%s\": %m", path)));
560 
561  pq_endmessage(&buf);
562 }
563 
564 /*
565  * Handle START_REPLICATION command.
566  *
567  * At the moment, this never returns, but an ereport(ERROR) will take us back
568  * to the main loop.
569  */
570 static void
572 {
574  XLogRecPtr FlushPtr;
575 
576  if (ThisTimeLineID == 0)
577  ereport(ERROR,
578  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
579  errmsg("IDENTIFY_SYSTEM has not been run before START_REPLICATION")));
580 
581  /* create xlogreader for physical replication */
582  xlogreader =
584 
585  if (!xlogreader)
586  ereport(ERROR,
587  (errcode(ERRCODE_OUT_OF_MEMORY),
588  errmsg("out of memory")));
589 
590  /*
591  * We assume here that we're logging enough information in the WAL for
592  * log-shipping, since this is checked in PostmasterMain().
593  *
594  * NOTE: wal_level can only change at shutdown, so in most cases it is
595  * difficult for there to be WAL data that we can still see that was
596  * written at wal_level='minimal'.
597  */
598 
599  if (cmd->slotname)
600  {
603  ereport(ERROR,
604  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
605  errmsg("cannot use a logical replication slot for physical replication")));
606 
607  /*
608  * We don't need to verify the slot's restart_lsn here; instead we
609  * rely on the caller requesting the starting point to use. If the
610  * WAL segment doesn't exist, we'll fail later.
611  */
612  }
613 
614  /*
615  * Select the timeline. If it was given explicitly by the client, use
616  * that. Otherwise use the timeline of the last replayed record, which is
617  * kept in ThisTimeLineID.
618  */
620  {
621  /* this also updates ThisTimeLineID */
622  FlushPtr = GetStandbyFlushRecPtr();
623  }
624  else
625  FlushPtr = GetFlushRecPtr();
626 
627  if (cmd->timeline != 0)
628  {
629  XLogRecPtr switchpoint;
630 
631  sendTimeLine = cmd->timeline;
633  {
634  sendTimeLineIsHistoric = false;
636  }
637  else
638  {
639  List *timeLineHistory;
640 
641  sendTimeLineIsHistoric = true;
642 
643  /*
644  * Check that the timeline the client requested exists, and the
645  * requested start location is on that timeline.
646  */
647  timeLineHistory = readTimeLineHistory(ThisTimeLineID);
648  switchpoint = tliSwitchPoint(cmd->timeline, timeLineHistory,
650  list_free_deep(timeLineHistory);
651 
652  /*
653  * Found the requested timeline in the history. Check that
654  * requested startpoint is on that timeline in our history.
655  *
656  * This is quite loose on purpose. We only check that we didn't
657  * fork off the requested timeline before the switchpoint. We
658  * don't check that we switched *to* it before the requested
659  * starting point. This is because the client can legitimately
660  * request to start replication from the beginning of the WAL
661  * segment that contains switchpoint, but on the new timeline, so
662  * that it doesn't end up with a partial segment. If you ask for
663  * too old a starting point, you'll get an error later when we
664  * fail to find the requested WAL segment in pg_wal.
665  *
666  * XXX: we could be more strict here and only allow a startpoint
667  * that's older than the switchpoint, if it's still in the same
668  * WAL segment.
669  */
670  if (!XLogRecPtrIsInvalid(switchpoint) &&
671  switchpoint < cmd->startpoint)
672  {
673  ereport(ERROR,
674  (errmsg("requested starting point %X/%X on timeline %u is not in this server's history",
676  cmd->timeline),
677  errdetail("This server's history forked from timeline %u at %X/%X.",
678  cmd->timeline,
679  LSN_FORMAT_ARGS(switchpoint))));
680  }
681  sendTimeLineValidUpto = switchpoint;
682  }
683  }
684  else
685  {
688  sendTimeLineIsHistoric = false;
689  }
690 
692 
693  /* If there is nothing to stream, don't even enter COPY mode */
695  {
696  /*
697  * When we first start replication the standby will be behind the
698  * primary. For some applications, for example synchronous
699  * replication, it is important to have a clear state for this initial
700  * catchup mode, so we can trigger actions when we change streaming
701  * state later. We may stay in this state for a long time, which is
702  * exactly why we want to be able to monitor whether or not we are
703  * still here.
704  */
706 
707  /* Send a CopyBothResponse message, and start streaming */
708  pq_beginmessage(&buf, 'W');
709  pq_sendbyte(&buf, 0);
710  pq_sendint16(&buf, 0);
711  pq_endmessage(&buf);
712  pq_flush();
713 
714  /*
715  * Don't allow a request to stream from a future point in WAL that
716  * hasn't been flushed to disk in this server yet.
717  */
718  if (FlushPtr < cmd->startpoint)
719  {
720  ereport(ERROR,
721  (errmsg("requested starting point %X/%X is ahead of the WAL flush position of this server %X/%X",
723  LSN_FORMAT_ARGS(FlushPtr))));
724  }
725 
726  /* Start streaming from the requested point */
727  sentPtr = cmd->startpoint;
728 
729  /* Initialize shared memory status, too */
730  SpinLockAcquire(&MyWalSnd->mutex);
731  MyWalSnd->sentPtr = sentPtr;
732  SpinLockRelease(&MyWalSnd->mutex);
733 
735 
736  /* Main loop of walsender */
737  replication_active = true;
738 
740 
741  replication_active = false;
742  if (got_STOPPING)
743  proc_exit(0);
745 
747  }
748 
749  if (cmd->slotname)
751 
752  /*
753  * Copy is finished now. Send a single-row result set indicating the next
754  * timeline.
755  */
757  {
758  char startpos_str[8 + 1 + 8 + 1];
760  TupOutputState *tstate;
761  TupleDesc tupdesc;
762  Datum values[2];
763  bool nulls[2];
764 
765  snprintf(startpos_str, sizeof(startpos_str), "%X/%X",
767 
769  MemSet(nulls, false, sizeof(nulls));
770 
771  /*
772  * Need a tuple descriptor representing two columns. int8 may seem
773  * like a surprising data type for this, but in theory int4 would not
774  * be wide enough for this, as TimeLineID is unsigned.
775  */
776  tupdesc = CreateTemplateTupleDesc(2);
777  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "next_tli",
778  INT8OID, -1, 0);
779  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "next_tli_startpos",
780  TEXTOID, -1, 0);
781 
782  /* prepare for projection of tuple */
783  tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
784 
785  values[0] = Int64GetDatum((int64) sendTimeLineNextTLI);
786  values[1] = CStringGetTextDatum(startpos_str);
787 
788  /* send it to dest */
789  do_tup_output(tstate, values, nulls);
790 
791  end_tup_output(tstate);
792  }
793 
794  /* Send CommandComplete message */
795  EndReplicationCommand("START_STREAMING");
796 }
797 
798 /*
799  * XLogReaderRoutine->page_read callback for logical decoding contexts, as a
800  * walsender process.
801  *
802  * Inside the walsender we can do better than read_local_xlog_page,
803  * which has to do a plain sleep/busy loop, because the walsender's latch gets
804  * set every time WAL is flushed.
805  */
806 static bool
808 {
809  XLogRecPtr targetPagePtr = state->readPagePtr;
810  int reqLen = state->reqLen;
811  char *cur_page = state->readBuf;
812  XLogRecPtr flushptr;
813  int count;
814  WALReadError errinfo;
815  XLogSegNo segno;
816 
817  XLogReadDetermineTimeline(state, targetPagePtr, reqLen);
819  sendTimeLine = state->currTLI;
821  sendTimeLineNextTLI = state->nextTLI;
822 
823  /* make sure we have enough WAL available */
824  flushptr = WalSndWaitForWal(targetPagePtr + reqLen);
825 
826  /* fail if not (implies we are going to shut down) */
827  if (flushptr < targetPagePtr + reqLen)
828  {
829  XLogReaderSetInputData(state, -1);
830  return false;
831  }
832 
833  if (targetPagePtr + XLOG_BLCKSZ <= flushptr)
834  count = XLOG_BLCKSZ; /* more than one block available */
835  else
836  count = flushptr - targetPagePtr; /* part of the page available */
837 
838  /* now actually read the data, we know it's there */
840  cur_page,
841  targetPagePtr,
842  XLOG_BLCKSZ,
843  state->seg.ws_tli, /* Pass the current TLI because only
844  * WalSndSegmentOpen controls whether new
845  * TLI is needed. */
846  &errinfo))
847  WALReadRaiseError(&errinfo);
848 
849  /*
850  * After reading into the buffer, check that what we read was valid. We do
851  * this after reading, because even though the segment was present when we
852  * opened it, it might get recycled or removed while we read it. The
853  * read() succeeds in that case, but the data we tried to read might
854  * already have been overwritten with new WAL records.
855  */
856  XLByteToSeg(targetPagePtr, segno, state->segcxt.ws_segsize);
857  CheckXLogRemoved(segno, state->seg.ws_tli);
858 
859  XLogReaderSetInputData(state, count);
860  return true;
861 }
862 
863 /*
864  * Process extra options given to CREATE_REPLICATION_SLOT.
865  */
866 static void
868  bool *reserve_wal,
869  CRSSnapshotAction *snapshot_action)
870 {
871  ListCell *lc;
872  bool snapshot_action_given = false;
873  bool reserve_wal_given = false;
874 
875  /* Parse options */
876  foreach(lc, cmd->options)
877  {
878  DefElem *defel = (DefElem *) lfirst(lc);
879 
880  if (strcmp(defel->defname, "export_snapshot") == 0)
881  {
882  if (snapshot_action_given || cmd->kind != REPLICATION_KIND_LOGICAL)
883  ereport(ERROR,
884  (errcode(ERRCODE_SYNTAX_ERROR),
885  errmsg("conflicting or redundant options")));
886 
887  snapshot_action_given = true;
888  *snapshot_action = defGetBoolean(defel) ? CRS_EXPORT_SNAPSHOT :
890  }
891  else if (strcmp(defel->defname, "use_snapshot") == 0)
892  {
893  if (snapshot_action_given || cmd->kind != REPLICATION_KIND_LOGICAL)
894  ereport(ERROR,
895  (errcode(ERRCODE_SYNTAX_ERROR),
896  errmsg("conflicting or redundant options")));
897 
898  snapshot_action_given = true;
899  *snapshot_action = CRS_USE_SNAPSHOT;
900  }
901  else if (strcmp(defel->defname, "reserve_wal") == 0)
902  {
903  if (reserve_wal_given || cmd->kind != REPLICATION_KIND_PHYSICAL)
904  ereport(ERROR,
905  (errcode(ERRCODE_SYNTAX_ERROR),
906  errmsg("conflicting or redundant options")));
907 
908  reserve_wal_given = true;
909  *reserve_wal = true;
910  }
911  else
912  elog(ERROR, "unrecognized option: %s", defel->defname);
913  }
914 }
915 
916 /*
917  * Create a new replication slot.
918  */
919 static void
921 {
922  const char *snapshot_name = NULL;
923  char xloc[MAXFNAMELEN];
924  char *slot_name;
925  bool reserve_wal = false;
926  CRSSnapshotAction snapshot_action = CRS_EXPORT_SNAPSHOT;
928  TupOutputState *tstate;
929  TupleDesc tupdesc;
930  Datum values[4];
931  bool nulls[4];
932 
934 
935  parseCreateReplSlotOptions(cmd, &reserve_wal, &snapshot_action);
936 
937  /* setup state for WalSndSegmentOpen */
938  sendTimeLineIsHistoric = false;
940 
941  if (cmd->kind == REPLICATION_KIND_PHYSICAL)
942  {
943  ReplicationSlotCreate(cmd->slotname, false,
945  false);
946  }
947  else
948  {
950 
951  /*
952  * Initially create persistent slot as ephemeral - that allows us to
953  * nicely handle errors during initialization because it'll get
954  * dropped if this transaction fails. We'll make it persistent at the
955  * end. Temporary slots can be created as temporary from beginning as
956  * they get dropped on error as well.
957  */
958  ReplicationSlotCreate(cmd->slotname, true,
960  cmd->two_phase);
961  }
962 
963  if (cmd->kind == REPLICATION_KIND_LOGICAL)
964  {
966  bool need_full_snapshot = false;
967 
968  /*
969  * Do options check early so that we can bail before calling the
970  * DecodingContextFindStartpoint which can take long time.
971  */
972  if (snapshot_action == CRS_EXPORT_SNAPSHOT)
973  {
974  if (IsTransactionBlock())
975  ereport(ERROR,
976  /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
977  (errmsg("%s must not be called inside a transaction",
978  "CREATE_REPLICATION_SLOT ... EXPORT_SNAPSHOT")));
979 
980  need_full_snapshot = true;
981  }
982  else if (snapshot_action == CRS_USE_SNAPSHOT)
983  {
984  if (!IsTransactionBlock())
985  ereport(ERROR,
986  /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
987  (errmsg("%s must be called inside a transaction",
988  "CREATE_REPLICATION_SLOT ... USE_SNAPSHOT")));
989 
991  ereport(ERROR,
992  /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
993  (errmsg("%s must be called in REPEATABLE READ isolation mode transaction",
994  "CREATE_REPLICATION_SLOT ... USE_SNAPSHOT")));
995 
996  if (FirstSnapshotSet)
997  ereport(ERROR,
998  /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
999  (errmsg("%s must be called before any query",
1000  "CREATE_REPLICATION_SLOT ... USE_SNAPSHOT")));
1001 
1002  if (IsSubTransaction())
1003  ereport(ERROR,
1004  /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1005  (errmsg("%s must not be called in a subtransaction",
1006  "CREATE_REPLICATION_SLOT ... USE_SNAPSHOT")));
1007 
1008  need_full_snapshot = true;
1009  }
1010 
1011  ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot,
1017 
1018  /*
1019  * Signal that we don't need the timeout mechanism. We're just
1020  * creating the replication slot and don't yet accept feedback
1021  * messages or send keepalives. As we possibly need to wait for
1022  * further WAL the walsender would otherwise possibly be killed too
1023  * soon.
1024  */
1026 
1027  /* build initial snapshot, might take a while */
1029 
1030  /*
1031  * Export or use the snapshot if we've been asked to do so.
1032  *
1033  * NB. We will convert the snapbuild.c kind of snapshot to normal
1034  * snapshot when doing this.
1035  */
1036  if (snapshot_action == CRS_EXPORT_SNAPSHOT)
1037  {
1038  snapshot_name = SnapBuildExportSnapshot(ctx->snapshot_builder);
1039  }
1040  else if (snapshot_action == CRS_USE_SNAPSHOT)
1041  {
1042  Snapshot snap;
1043 
1046  }
1047 
1048  /* don't need the decoding context anymore */
1049  FreeDecodingContext(ctx);
1050 
1051  if (!cmd->temporary)
1053  }
1054  else if (cmd->kind == REPLICATION_KIND_PHYSICAL && reserve_wal)
1055  {
1057 
1059 
1060  /* Write this slot to disk if it's a permanent one. */
1061  if (!cmd->temporary)
1063  }
1064 
1065  snprintf(xloc, sizeof(xloc), "%X/%X",
1067 
1069  MemSet(nulls, false, sizeof(nulls));
1070 
1071  /*----------
1072  * Need a tuple descriptor representing four columns:
1073  * - first field: the slot name
1074  * - second field: LSN at which we became consistent
1075  * - third field: exported snapshot's name
1076  * - fourth field: output plugin
1077  *----------
1078  */
1079  tupdesc = CreateTemplateTupleDesc(4);
1080  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "slot_name",
1081  TEXTOID, -1, 0);
1082  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "consistent_point",
1083  TEXTOID, -1, 0);
1084  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "snapshot_name",
1085  TEXTOID, -1, 0);
1086  TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "output_plugin",
1087  TEXTOID, -1, 0);
1088 
1089  /* prepare for projection of tuples */
1090  tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
1091 
1092  /* slot_name */
1093  slot_name = NameStr(MyReplicationSlot->data.name);
1094  values[0] = CStringGetTextDatum(slot_name);
1095 
1096  /* consistent wal location */
1097  values[1] = CStringGetTextDatum(xloc);
1098 
1099  /* snapshot name, or NULL if none */
1100  if (snapshot_name != NULL)
1101  values[2] = CStringGetTextDatum(snapshot_name);
1102  else
1103  nulls[2] = true;
1104 
1105  /* plugin, or NULL if none */
1106  if (cmd->plugin != NULL)
1107  values[3] = CStringGetTextDatum(cmd->plugin);
1108  else
1109  nulls[3] = true;
1110 
1111  /* send it to dest */
1112  do_tup_output(tstate, values, nulls);
1113  end_tup_output(tstate);
1114 
1116 }
1117 
1118 /*
1119  * Get rid of a replication slot that is no longer wanted.
1120  */
1121 static void
1123 {
1124  ReplicationSlotDrop(cmd->slotname, !cmd->wait);
1125 }
1126 
1127 /*
1128  * Load previously initiated logical slot and prepare for sending data (via
1129  * WalSndLoop).
1130  */
1131 static void
1133 {
1135  QueryCompletion qc;
1136 
1137  /* make sure that our requirements are still fulfilled */
1139 
1141 
1143 
1145  ereport(ERROR,
1146  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1147  errmsg("cannot read from logical replication slot \"%s\"",
1148  cmd->slotname),
1149  errdetail("This slot has been invalidated because it exceeded the maximum reserved size.")));
1150 
1151  /*
1152  * Force a disconnect, so that the decoding code doesn't need to care
1153  * about an eventual switch from running in recovery, to running in a
1154  * normal environment. Client code is expected to handle reconnects.
1155  */
1157  {
1158  ereport(LOG,
1159  (errmsg("terminating walsender process after promotion")));
1160  got_STOPPING = true;
1161  }
1162 
1163  /*
1164  * Create our decoding context, making it start at the previously ack'ed
1165  * position.
1166  *
1167  * Do this before sending a CopyBothResponse message, so that any errors
1168  * are reported early.
1169  */
1170  logical_decoding_ctx =
1171  CreateDecodingContext(cmd->startpoint, cmd->options, false,
1176  xlogreader = logical_decoding_ctx->reader;
1177 
1179 
1180  /* Send a CopyBothResponse message, and start streaming */
1181  pq_beginmessage(&buf, 'W');
1182  pq_sendbyte(&buf, 0);
1183  pq_sendint16(&buf, 0);
1184  pq_endmessage(&buf);
1185  pq_flush();
1186 
1187  /* Start reading WAL from the oldest required WAL. */
1188  XLogBeginRead(logical_decoding_ctx->reader,
1190 
1191  /*
1192  * Report the location after which we'll send out further commits as the
1193  * current sentPtr.
1194  */
1196 
1197  /* Also update the sent position status in shared memory */
1198  SpinLockAcquire(&MyWalSnd->mutex);
1200  SpinLockRelease(&MyWalSnd->mutex);
1201 
1202  replication_active = true;
1203 
1205 
1206  /* Main loop of walsender */
1208 
1209  FreeDecodingContext(logical_decoding_ctx);
1211 
1212  replication_active = false;
1213  if (got_STOPPING)
1214  proc_exit(0);
1216 
1217  /* Get out of COPY mode (CommandComplete). */
1218  SetQueryCompletion(&qc, CMDTAG_COPY, 0);
1219  EndCommand(&qc, DestRemote, false);
1220 }
1221 
1222 /*
1223  * LogicalDecodingContext 'prepare_write' callback.
1224  *
1225  * Prepare a write into a StringInfo.
1226  *
1227  * Don't do anything lasting in here, it's quite possible that nothing will be done
1228  * with the data.
1229  */
1230 static void
1232 {
1233  /* can't have sync rep confused by sending the same LSN several times */
1234  if (!last_write)
1235  lsn = InvalidXLogRecPtr;
1236 
1237  resetStringInfo(ctx->out);
1238 
1239  pq_sendbyte(ctx->out, 'w');
1240  pq_sendint64(ctx->out, lsn); /* dataStart */
1241  pq_sendint64(ctx->out, lsn); /* walEnd */
1242 
1243  /*
1244  * Fill out the sendtime later, just as it's done in XLogSendPhysical, but
1245  * reserve space here.
1246  */
1247  pq_sendint64(ctx->out, 0); /* sendtime */
1248 }
1249 
1250 /*
1251  * LogicalDecodingContext 'write' callback.
1252  *
1253  * Actually write out data previously prepared by WalSndPrepareWrite out to
1254  * the network. Take as long as needed, but process replies from the other
1255  * side and check timeouts during that.
1256  */
1257 static void
1259  bool last_write)
1260 {
1261  TimestampTz now;
1262 
1263  /*
1264  * Fill the send timestamp last, so that it is taken as late as possible.
1265  * This is somewhat ugly, but the protocol is set as it's already used for
1266  * several releases by streaming physical replication.
1267  */
1268  resetStringInfo(&tmpbuf);
1269  now = GetCurrentTimestamp();
1270  pq_sendint64(&tmpbuf, now);
1271  memcpy(&ctx->out->data[1 + sizeof(int64) + sizeof(int64)],
1272  tmpbuf.data, sizeof(int64));
1273 
1274  /* output previously gathered data in a CopyData packet */
1275  pq_putmessage_noblock('d', ctx->out->data, ctx->out->len);
1276 
1278 
1279  /* Try to flush pending output to the client */
1280  if (pq_flush_if_writable() != 0)
1281  WalSndShutdown();
1282 
1283  /* Try taking fast path unless we get too close to walsender timeout. */
1285  wal_sender_timeout / 2) &&
1286  !pq_is_send_pending())
1287  {
1288  return;
1289  }
1290 
1291  /* If we have pending write here, go to slow path */
1292  for (;;)
1293  {
1294  long sleeptime;
1295 
1296  /* Check for input from the client */
1298 
1299  /* die if timeout was reached */
1301 
1302  /* Send keepalive if the time has come */
1304 
1305  if (!pq_is_send_pending())
1306  break;
1307 
1309 
1310  /* Sleep until something happens or we time out */
1313 
1314  /* Clear any already-pending wakeups */
1316 
1318 
1319  /* Process any requests or signals received recently */
1320  if (ConfigReloadPending)
1321  {
1322  ConfigReloadPending = false;
1325  }
1326 
1327  /* Try to flush pending output to the client */
1328  if (pq_flush_if_writable() != 0)
1329  WalSndShutdown();
1330  }
1331 
1332  /* reactivate latch so WalSndLoop knows to continue */
1333  SetLatch(MyLatch);
1334 }
1335 
1336 /*
1337  * LogicalDecodingContext 'update_progress' callback.
1338  *
1339  * Write the current position to the lag tracker (see XLogSendPhysical).
1340  */
1341 static void
1343 {
1344  static TimestampTz sendTime = 0;
1346 
1347  /*
1348  * Track lag no more than once per WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS to
1349  * avoid flooding the lag tracker when we commit frequently.
1350  */
1351 #define WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS 1000
1352  if (!TimestampDifferenceExceeds(sendTime, now,
1354  return;
1355 
1356  LagTrackerWrite(lsn, now);
1357  sendTime = now;
1358 }
1359 
1360 /*
1361  * Wait till WAL < loc is flushed to disk so it can be safely sent to client.
1362  *
1363  * Returns end LSN of flushed WAL. Normally this will be >= loc, but
1364  * if we detect a shutdown request (either from postmaster or client)
1365  * we will return early, so caller must always check.
1366  */
1367 static XLogRecPtr
1369 {
1370  int wakeEvents;
1371  static XLogRecPtr RecentFlushPtr = InvalidXLogRecPtr;
1372 
1373  /*
1374  * Fast path to avoid acquiring the spinlock in case we already know we
1375  * have enough WAL available. This is particularly interesting if we're
1376  * far behind.
1377  */
1378  if (RecentFlushPtr != InvalidXLogRecPtr &&
1379  loc <= RecentFlushPtr)
1380  return RecentFlushPtr;
1381 
1382  /* Get a more recent flush pointer. */
1383  if (!RecoveryInProgress())
1384  RecentFlushPtr = GetFlushRecPtr();
1385  else
1386  RecentFlushPtr = GetXLogReplayRecPtr(NULL);
1387 
1388  for (;;)
1389  {
1390  long sleeptime;
1391 
1392  /* Clear any already-pending wakeups */
1394 
1396 
1397  /* Process any requests or signals received recently */
1398  if (ConfigReloadPending)
1399  {
1400  ConfigReloadPending = false;
1403  }
1404 
1405  /* Check for input from the client */
1407 
1408  /*
1409  * If we're shutting down, trigger pending WAL to be written out,
1410  * otherwise we'd possibly end up waiting for WAL that never gets
1411  * written, because walwriter has shut down already.
1412  */
1413  if (got_STOPPING)
1415 
1416  /* Update our idea of the currently flushed position. */
1417  if (!RecoveryInProgress())
1418  RecentFlushPtr = GetFlushRecPtr();
1419  else
1420  RecentFlushPtr = GetXLogReplayRecPtr(NULL);
1421 
1422  /*
1423  * If postmaster asked us to stop, don't wait anymore.
1424  *
1425  * It's important to do this check after the recomputation of
1426  * RecentFlushPtr, so we can send all remaining data before shutting
1427  * down.
1428  */
1429  if (got_STOPPING)
1430  break;
1431 
1432  /*
1433  * We only send regular messages to the client for full decoded
1434  * transactions, but a synchronous replication and walsender shutdown
1435  * possibly are waiting for a later location. So, before sleeping, we
1436  * send a ping containing the flush location. If the receiver is
1437  * otherwise idle, this keepalive will trigger a reply. Processing the
1438  * reply will update these MyWalSnd locations.
1439  */
1440  if (MyWalSnd->flush < sentPtr &&
1441  MyWalSnd->write < sentPtr &&
1443  WalSndKeepalive(false);
1444 
1445  /* check whether we're done */
1446  if (loc <= RecentFlushPtr)
1447  break;
1448 
1449  /* Waiting for new WAL. Since we need to wait, we're now caught up. */
1450  WalSndCaughtUp = true;
1451 
1452  /*
1453  * Try to flush any pending output to the client.
1454  */
1455  if (pq_flush_if_writable() != 0)
1456  WalSndShutdown();
1457 
1458  /*
1459  * If we have received CopyDone from the client, sent CopyDone
1460  * ourselves, and the output buffer is empty, it's time to exit
1461  * streaming, so fail the current WAL fetch request.
1462  */
1464  !pq_is_send_pending())
1465  break;
1466 
1467  /* die if timeout was reached */
1469 
1470  /* Send keepalive if the time has come */
1472 
1473  /*
1474  * Sleep until something happens or we time out. Also wait for the
1475  * socket becoming writable, if there's still pending output.
1476  * Otherwise we might sit on sendable output data while waiting for
1477  * new WAL to be generated. (But if we have nothing to send, we don't
1478  * want to wake on socket-writable.)
1479  */
1481 
1482  wakeEvents = WL_SOCKET_READABLE;
1483 
1484  if (pq_is_send_pending())
1485  wakeEvents |= WL_SOCKET_WRITEABLE;
1486 
1487  WalSndWait(wakeEvents, sleeptime, WAIT_EVENT_WAL_SENDER_WAIT_WAL);
1488  }
1489 
1490  /* reactivate latch so WalSndLoop knows to continue */
1491  SetLatch(MyLatch);
1492  return RecentFlushPtr;
1493 }
1494 
1495 /*
1496  * Execute an incoming replication command.
1497  *
1498  * Returns true if the cmd_string was recognized as WalSender command, false
1499  * if not.
1500  */
1501 bool
1502 exec_replication_command(const char *cmd_string)
1503 {
1504  int parse_rc;
1505  Node *cmd_node;
1506  const char *cmdtag;
1507  MemoryContext cmd_context;
1508  MemoryContext old_context;
1509 
1510  /*
1511  * If WAL sender has been told that shutdown is getting close, switch its
1512  * status accordingly to handle the next replication commands correctly.
1513  */
1514  if (got_STOPPING)
1516 
1517  /*
1518  * Throw error if in stopping mode. We need prevent commands that could
1519  * generate WAL while the shutdown checkpoint is being written. To be
1520  * safe, we just prohibit all new commands.
1521  */
1522  if (MyWalSnd->state == WALSNDSTATE_STOPPING)
1523  ereport(ERROR,
1524  (errmsg("cannot execute new commands while WAL sender is in stopping mode")));
1525 
1526  /*
1527  * CREATE_REPLICATION_SLOT ... LOGICAL exports a snapshot until the next
1528  * command arrives. Clean up the old stuff if there's anything.
1529  */
1531 
1533 
1534  /*
1535  * Parse the command.
1536  */
1538  "Replication command context",
1540  old_context = MemoryContextSwitchTo(cmd_context);
1541 
1542  replication_scanner_init(cmd_string);
1543  parse_rc = replication_yyparse();
1544  if (parse_rc != 0)
1545  ereport(ERROR,
1546  (errcode(ERRCODE_SYNTAX_ERROR),
1547  errmsg_internal("replication command parser returned %d",
1548  parse_rc)));
1550 
1551  cmd_node = replication_parse_result;
1552 
1553  /*
1554  * If it's a SQL command, just clean up our mess and return false; the
1555  * caller will take care of executing it.
1556  */
1557  if (IsA(cmd_node, SQLCmd))
1558  {
1559  if (MyDatabaseId == InvalidOid)
1560  ereport(ERROR,
1561  (errmsg("cannot execute SQL commands in WAL sender for physical replication")));
1562 
1563  MemoryContextSwitchTo(old_context);
1564  MemoryContextDelete(cmd_context);
1565 
1566  /* Tell the caller that this wasn't a WalSender command. */
1567  return false;
1568  }
1569 
1570  /*
1571  * Report query to various monitoring facilities. For this purpose, we
1572  * report replication commands just like SQL commands.
1573  */
1574  debug_query_string = cmd_string;
1575 
1577 
1578  /*
1579  * Log replication command if log_replication_commands is enabled. Even
1580  * when it's disabled, log the command with DEBUG1 level for backward
1581  * compatibility.
1582  */
1584  (errmsg("received replication command: %s", cmd_string)));
1585 
1586  /*
1587  * Disallow replication commands in aborted transaction blocks.
1588  */
1590  ereport(ERROR,
1591  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1592  errmsg("current transaction is aborted, "
1593  "commands ignored until end of transaction block")));
1594 
1596 
1597  /*
1598  * Allocate buffers that will be used for each outgoing and incoming
1599  * message. We do this just once per command to reduce palloc overhead.
1600  */
1601  initStringInfo(&output_message);
1602  initStringInfo(&reply_message);
1603  initStringInfo(&tmpbuf);
1604 
1605  switch (cmd_node->type)
1606  {
1607  case T_IdentifySystemCmd:
1608  cmdtag = "IDENTIFY_SYSTEM";
1609  set_ps_display(cmdtag);
1610  IdentifySystem();
1611  EndReplicationCommand(cmdtag);
1612  break;
1613 
1614  case T_BaseBackupCmd:
1615  cmdtag = "BASE_BACKUP";
1616  set_ps_display(cmdtag);
1617  PreventInTransactionBlock(true, cmdtag);
1618  SendBaseBackup((BaseBackupCmd *) cmd_node);
1619  EndReplicationCommand(cmdtag);
1620  break;
1621 
1623  cmdtag = "CREATE_REPLICATION_SLOT";
1624  set_ps_display(cmdtag);
1626  EndReplicationCommand(cmdtag);
1627  break;
1628 
1630  cmdtag = "DROP_REPLICATION_SLOT";
1631  set_ps_display(cmdtag);
1633  EndReplicationCommand(cmdtag);
1634  break;
1635 
1636  case T_StartReplicationCmd:
1637  {
1638  StartReplicationCmd *cmd = (StartReplicationCmd *) cmd_node;
1639 
1640  cmdtag = "START_REPLICATION";
1641  set_ps_display(cmdtag);
1642  PreventInTransactionBlock(true, cmdtag);
1643 
1644  if (cmd->kind == REPLICATION_KIND_PHYSICAL)
1645  StartReplication(cmd);
1646  else
1648 
1649  /* dupe, but necessary per libpqrcv_endstreaming */
1650  EndReplicationCommand(cmdtag);
1651 
1652  Assert(xlogreader != NULL);
1653  break;
1654  }
1655 
1656  case T_TimeLineHistoryCmd:
1657  cmdtag = "TIMELINE_HISTORY";
1658  set_ps_display(cmdtag);
1659  PreventInTransactionBlock(true, cmdtag);
1661  EndReplicationCommand(cmdtag);
1662  break;
1663 
1664  case T_VariableShowStmt:
1665  {
1667  VariableShowStmt *n = (VariableShowStmt *) cmd_node;
1668 
1669  cmdtag = "SHOW";
1670  set_ps_display(cmdtag);
1671 
1672  /* syscache access needs a transaction environment */
1674  GetPGVariable(n->name, dest);
1676  EndReplicationCommand(cmdtag);
1677  }
1678  break;
1679 
1680  default:
1681  elog(ERROR, "unrecognized replication command node tag: %u",
1682  cmd_node->type);
1683  }
1684 
1685  /* done */
1686  MemoryContextSwitchTo(old_context);
1687  MemoryContextDelete(cmd_context);
1688 
1689  /*
1690  * We need not update ps display or pg_stat_activity, because PostgresMain
1691  * will reset those to "idle". But we must reset debug_query_string to
1692  * ensure it doesn't become a dangling pointer.
1693  */
1694  debug_query_string = NULL;
1695 
1696  return true;
1697 }
1698 
1699 /*
1700  * Process any incoming messages while streaming. Also checks if the remote
1701  * end has closed the connection.
1702  */
1703 static void
1705 {
1706  unsigned char firstchar;
1707  int r;
1708  bool received = false;
1709 
1711 
1712  /*
1713  * If we already received a CopyDone from the frontend, any subsequent
1714  * message is the beginning of a new command, and should be processed in
1715  * the main processing loop.
1716  */
1717  while (!streamingDoneReceiving)
1718  {
1719  pq_startmsgread();
1720  r = pq_getbyte_if_available(&firstchar);
1721  if (r < 0)
1722  {
1723  /* unexpected error or EOF */
1725  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1726  errmsg("unexpected EOF on standby connection")));
1727  proc_exit(0);
1728  }
1729  if (r == 0)
1730  {
1731  /* no data available without blocking */
1732  pq_endmsgread();
1733  break;
1734  }
1735 
1736  /* Read the message contents */
1737  resetStringInfo(&reply_message);
1738  if (pq_getmessage(&reply_message, 0))
1739  {
1741  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1742  errmsg("unexpected EOF on standby connection")));
1743  proc_exit(0);
1744  }
1745 
1746  /* Handle the very limited subset of commands expected in this phase */
1747  switch (firstchar)
1748  {
1749  /*
1750  * 'd' means a standby reply wrapped in a CopyData packet.
1751  */
1752  case 'd':
1754  received = true;
1755  break;
1756 
1757  /*
1758  * CopyDone means the standby requested to finish streaming.
1759  * Reply with CopyDone, if we had not sent that already.
1760  */
1761  case 'c':
1762  if (!streamingDoneSending)
1763  {
1764  pq_putmessage_noblock('c', NULL, 0);
1765  streamingDoneSending = true;
1766  }
1767 
1768  streamingDoneReceiving = true;
1769  received = true;
1770  break;
1771 
1772  /*
1773  * 'X' means that the standby is closing down the socket.
1774  */
1775  case 'X':
1776  proc_exit(0);
1777 
1778  default:
1779  ereport(FATAL,
1780  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1781  errmsg("invalid standby message type \"%c\"",
1782  firstchar)));
1783  }
1784  }
1785 
1786  /*
1787  * Save the last reply timestamp if we've received at least one reply.
1788  */
1789  if (received)
1790  {
1792  waiting_for_ping_response = false;
1793  }
1794 }
1795 
1796 /*
1797  * Process a status update message received from standby.
1798  */
1799 static void
1801 {
1802  char msgtype;
1803 
1804  /*
1805  * Check message type from the first byte.
1806  */
1807  msgtype = pq_getmsgbyte(&reply_message);
1808 
1809  switch (msgtype)
1810  {
1811  case 'r':
1813  break;
1814 
1815  case 'h':
1817  break;
1818 
1819  default:
1821  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1822  errmsg("unexpected message type \"%c\"", msgtype)));
1823  proc_exit(0);
1824  }
1825 }
1826 
1827 /*
1828  * Remember that a walreceiver just confirmed receipt of lsn `lsn`.
1829  */
1830 static void
1832 {
1833  bool changed = false;
1835 
1836  Assert(lsn != InvalidXLogRecPtr);
1837  SpinLockAcquire(&slot->mutex);
1838  if (slot->data.restart_lsn != lsn)
1839  {
1840  changed = true;
1841  slot->data.restart_lsn = lsn;
1842  }
1843  SpinLockRelease(&slot->mutex);
1844 
1845  if (changed)
1846  {
1849  }
1850 
1851  /*
1852  * One could argue that the slot should be saved to disk now, but that'd
1853  * be energy wasted - the worst lost information can do here is give us
1854  * wrong information in a statistics view - we'll just potentially be more
1855  * conservative in removing files.
1856  */
1857 }
1858 
1859 /*
1860  * Regular reply from standby advising of WAL locations on standby server.
1861  */
1862 static void
1864 {
1865  XLogRecPtr writePtr,
1866  flushPtr,
1867  applyPtr;
1868  bool replyRequested;
1869  TimeOffset writeLag,
1870  flushLag,
1871  applyLag;
1872  bool clearLagTimes;
1873  TimestampTz now;
1874  TimestampTz replyTime;
1875 
1876  static bool fullyAppliedLastTime = false;
1877 
1878  /* the caller already consumed the msgtype byte */
1879  writePtr = pq_getmsgint64(&reply_message);
1880  flushPtr = pq_getmsgint64(&reply_message);
1881  applyPtr = pq_getmsgint64(&reply_message);
1882  replyTime = pq_getmsgint64(&reply_message);
1883  replyRequested = pq_getmsgbyte(&reply_message);
1884 
1886  {
1887  char *replyTimeStr;
1888 
1889  /* Copy because timestamptz_to_str returns a static buffer */
1890  replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
1891 
1892  elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X%s reply_time %s",
1893  LSN_FORMAT_ARGS(writePtr),
1894  LSN_FORMAT_ARGS(flushPtr),
1895  LSN_FORMAT_ARGS(applyPtr),
1896  replyRequested ? " (reply requested)" : "",
1897  replyTimeStr);
1898 
1899  pfree(replyTimeStr);
1900  }
1901 
1902  /* See if we can compute the round-trip lag for these positions. */
1903  now = GetCurrentTimestamp();
1904  writeLag = LagTrackerRead(SYNC_REP_WAIT_WRITE, writePtr, now);
1905  flushLag = LagTrackerRead(SYNC_REP_WAIT_FLUSH, flushPtr, now);
1906  applyLag = LagTrackerRead(SYNC_REP_WAIT_APPLY, applyPtr, now);
1907 
1908  /*
1909  * If the standby reports that it has fully replayed the WAL in two
1910  * consecutive reply messages, then the second such message must result
1911  * from wal_receiver_status_interval expiring on the standby. This is a
1912  * convenient time to forget the lag times measured when it last
1913  * wrote/flushed/applied a WAL record, to avoid displaying stale lag data
1914  * until more WAL traffic arrives.
1915  */
1916  clearLagTimes = false;
1917  if (applyPtr == sentPtr)
1918  {
1919  if (fullyAppliedLastTime)
1920  clearLagTimes = true;
1921  fullyAppliedLastTime = true;
1922  }
1923  else
1924  fullyAppliedLastTime = false;
1925 
1926  /* Send a reply if the standby requested one. */
1927  if (replyRequested)
1928  WalSndKeepalive(false);
1929 
1930  /*
1931  * Update shared state for this WalSender process based on reply data from
1932  * standby.
1933  */
1934  {
1935  WalSnd *walsnd = MyWalSnd;
1936 
1937  SpinLockAcquire(&walsnd->mutex);
1938  walsnd->write = writePtr;
1939  walsnd->flush = flushPtr;
1940  walsnd->apply = applyPtr;
1941  if (writeLag != -1 || clearLagTimes)
1942  walsnd->writeLag = writeLag;
1943  if (flushLag != -1 || clearLagTimes)
1944  walsnd->flushLag = flushLag;
1945  if (applyLag != -1 || clearLagTimes)
1946  walsnd->applyLag = applyLag;
1947  walsnd->replyTime = replyTime;
1948  SpinLockRelease(&walsnd->mutex);
1949  }
1950 
1953 
1954  /*
1955  * Advance our local xmin horizon when the client confirmed a flush.
1956  */
1957  if (MyReplicationSlot && flushPtr != InvalidXLogRecPtr)
1958  {
1961  else
1963  }
1964 }
1965 
1966 /* compute new replication slot xmin horizon if needed */
1967 static void
1969 {
1970  bool changed = false;
1972 
1973  SpinLockAcquire(&slot->mutex);
1975 
1976  /*
1977  * For physical replication we don't need the interlock provided by xmin
1978  * and effective_xmin since the consequences of a missed increase are
1979  * limited to query cancellations, so set both at once.
1980  */
1981  if (!TransactionIdIsNormal(slot->data.xmin) ||
1982  !TransactionIdIsNormal(feedbackXmin) ||
1983  TransactionIdPrecedes(slot->data.xmin, feedbackXmin))
1984  {
1985  changed = true;
1986  slot->data.xmin = feedbackXmin;
1987  slot->effective_xmin = feedbackXmin;
1988  }
1989  if (!TransactionIdIsNormal(slot->data.catalog_xmin) ||
1990  !TransactionIdIsNormal(feedbackCatalogXmin) ||
1991  TransactionIdPrecedes(slot->data.catalog_xmin, feedbackCatalogXmin))
1992  {
1993  changed = true;
1994  slot->data.catalog_xmin = feedbackCatalogXmin;
1995  slot->effective_catalog_xmin = feedbackCatalogXmin;
1996  }
1997  SpinLockRelease(&slot->mutex);
1998 
1999  if (changed)
2000  {
2003  }
2004 }
2005 
2006 /*
2007  * Check that the provided xmin/epoch are sane, that is, not in the future
2008  * and not so far back as to be already wrapped around.
2009  *
2010  * Epoch of nextXid should be same as standby, or if the counter has
2011  * wrapped, then one greater than standby.
2012  *
2013  * This check doesn't care about whether clog exists for these xids
2014  * at all.
2015  */
2016 static bool
2018 {
2019  FullTransactionId nextFullXid;
2020  TransactionId nextXid;
2021  uint32 nextEpoch;
2022 
2023  nextFullXid = ReadNextFullTransactionId();
2024  nextXid = XidFromFullTransactionId(nextFullXid);
2025  nextEpoch = EpochFromFullTransactionId(nextFullXid);
2026 
2027  if (xid <= nextXid)
2028  {
2029  if (epoch != nextEpoch)
2030  return false;
2031  }
2032  else
2033  {
2034  if (epoch + 1 != nextEpoch)
2035  return false;
2036  }
2037 
2038  if (!TransactionIdPrecedesOrEquals(xid, nextXid))
2039  return false; /* epoch OK, but it's wrapped around */
2040 
2041  return true;
2042 }
2043 
2044 /*
2045  * Hot Standby feedback
2046  */
2047 static void
2049 {
2050  TransactionId feedbackXmin;
2051  uint32 feedbackEpoch;
2052  TransactionId feedbackCatalogXmin;
2053  uint32 feedbackCatalogEpoch;
2054  TimestampTz replyTime;
2055 
2056  /*
2057  * Decipher the reply message. The caller already consumed the msgtype
2058  * byte. See XLogWalRcvSendHSFeedback() in walreceiver.c for the creation
2059  * of this message.
2060  */
2061  replyTime = pq_getmsgint64(&reply_message);
2062  feedbackXmin = pq_getmsgint(&reply_message, 4);
2063  feedbackEpoch = pq_getmsgint(&reply_message, 4);
2064  feedbackCatalogXmin = pq_getmsgint(&reply_message, 4);
2065  feedbackCatalogEpoch = pq_getmsgint(&reply_message, 4);
2066 
2068  {
2069  char *replyTimeStr;
2070 
2071  /* Copy because timestamptz_to_str returns a static buffer */
2072  replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
2073 
2074  elog(DEBUG2, "hot standby feedback xmin %u epoch %u, catalog_xmin %u epoch %u reply_time %s",
2075  feedbackXmin,
2076  feedbackEpoch,
2077  feedbackCatalogXmin,
2078  feedbackCatalogEpoch,
2079  replyTimeStr);
2080 
2081  pfree(replyTimeStr);
2082  }
2083 
2084  /*
2085  * Update shared state for this WalSender process based on reply data from
2086  * standby.
2087  */
2088  {
2089  WalSnd *walsnd = MyWalSnd;
2090 
2091  SpinLockAcquire(&walsnd->mutex);
2092  walsnd->replyTime = replyTime;
2093  SpinLockRelease(&walsnd->mutex);
2094  }
2095 
2096  /*
2097  * Unset WalSender's xmins if the feedback message values are invalid.
2098  * This happens when the downstream turned hot_standby_feedback off.
2099  */
2100  if (!TransactionIdIsNormal(feedbackXmin)
2101  && !TransactionIdIsNormal(feedbackCatalogXmin))
2102  {
2104  if (MyReplicationSlot != NULL)
2105  PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
2106  return;
2107  }
2108 
2109  /*
2110  * Check that the provided xmin/epoch are sane, that is, not in the future
2111  * and not so far back as to be already wrapped around. Ignore if not.
2112  */
2113  if (TransactionIdIsNormal(feedbackXmin) &&
2114  !TransactionIdInRecentPast(feedbackXmin, feedbackEpoch))
2115  return;
2116 
2117  if (TransactionIdIsNormal(feedbackCatalogXmin) &&
2118  !TransactionIdInRecentPast(feedbackCatalogXmin, feedbackCatalogEpoch))
2119  return;
2120 
2121  /*
2122  * Set the WalSender's xmin equal to the standby's requested xmin, so that
2123  * the xmin will be taken into account by GetSnapshotData() /
2124  * ComputeXidHorizons(). This will hold back the removal of dead rows and
2125  * thereby prevent the generation of cleanup conflicts on the standby
2126  * server.
2127  *
2128  * There is a small window for a race condition here: although we just
2129  * checked that feedbackXmin precedes nextXid, the nextXid could have
2130  * gotten advanced between our fetching it and applying the xmin below,
2131  * perhaps far enough to make feedbackXmin wrap around. In that case the
2132  * xmin we set here would be "in the future" and have no effect. No point
2133  * in worrying about this since it's too late to save the desired data
2134  * anyway. Assuming that the standby sends us an increasing sequence of
2135  * xmins, this could only happen during the first reply cycle, else our
2136  * own xmin would prevent nextXid from advancing so far.
2137  *
2138  * We don't bother taking the ProcArrayLock here. Setting the xmin field
2139  * is assumed atomic, and there's no real need to prevent concurrent
2140  * horizon determinations. (If we're moving our xmin forward, this is
2141  * obviously safe, and if we're moving it backwards, well, the data is at
2142  * risk already since a VACUUM could already have determined the horizon.)
2143  *
2144  * If we're using a replication slot we reserve the xmin via that,
2145  * otherwise via the walsender's PGPROC entry. We can only track the
2146  * catalog xmin separately when using a slot, so we store the least of the
2147  * two provided when not using a slot.
2148  *
2149  * XXX: It might make sense to generalize the ephemeral slot concept and
2150  * always use the slot mechanism to handle the feedback xmin.
2151  */
2152  if (MyReplicationSlot != NULL) /* XXX: persistency configurable? */
2153  PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
2154  else
2155  {
2156  if (TransactionIdIsNormal(feedbackCatalogXmin)
2157  && TransactionIdPrecedes(feedbackCatalogXmin, feedbackXmin))
2158  MyProc->xmin = feedbackCatalogXmin;
2159  else
2160  MyProc->xmin = feedbackXmin;
2161  }
2162 }
2163 
2164 /*
2165  * Compute how long send/receive loops should sleep.
2166  *
2167  * If wal_sender_timeout is enabled we want to wake up in time to send
2168  * keepalives and to abort the connection if wal_sender_timeout has been
2169  * reached.
2170  */
2171 static long
2173 {
2174  long sleeptime = 10000; /* 10 s */
2175 
2177  {
2178  TimestampTz wakeup_time;
2179 
2180  /*
2181  * At the latest stop sleeping once wal_sender_timeout has been
2182  * reached.
2183  */
2186 
2187  /*
2188  * If no ping has been sent yet, wakeup when it's time to do so.
2189  * WalSndKeepaliveIfNecessary() wants to send a keepalive once half of
2190  * the timeout passed without a response.
2191  */
2194  wal_sender_timeout / 2);
2195 
2196  /* Compute relative time until wakeup. */
2197  sleeptime = TimestampDifferenceMilliseconds(now, wakeup_time);
2198  }
2199 
2200  return sleeptime;
2201 }
2202 
2203 /*
2204  * Check whether there have been responses by the client within
2205  * wal_sender_timeout and shutdown if not. Using last_processing as the
2206  * reference point avoids counting server-side stalls against the client.
2207  * However, a long server-side stall can make WalSndKeepaliveIfNecessary()
2208  * postdate last_processing by more than wal_sender_timeout. If that happens,
2209  * the client must reply almost immediately to avoid a timeout. This rarely
2210  * affects the default configuration, under which clients spontaneously send a
2211  * message every standby_message_timeout = wal_sender_timeout/6 = 10s. We
2212  * could eliminate that problem by recognizing timeout expiration at
2213  * wal_sender_timeout/2 after the keepalive.
2214  */
2215 static void
2217 {
2218  TimestampTz timeout;
2219 
2220  /* don't bail out if we're doing something that doesn't require timeouts */
2221  if (last_reply_timestamp <= 0)
2222  return;
2223 
2226 
2227  if (wal_sender_timeout > 0 && last_processing >= timeout)
2228  {
2229  /*
2230  * Since typically expiration of replication timeout means
2231  * communication problem, we don't send the error message to the
2232  * standby.
2233  */
2235  (errmsg("terminating walsender process due to replication timeout")));
2236 
2237  WalSndShutdown();
2238  }
2239 }
2240 
2241 /* Main loop of walsender process that streams the WAL over Copy messages. */
2242 static void
2244 {
2245  /*
2246  * Initialize the last reply timestamp. That enables timeout processing
2247  * from hereon.
2248  */
2250  waiting_for_ping_response = false;
2251 
2252  /*
2253  * Loop until we reach the end of this timeline or the client requests to
2254  * stop streaming.
2255  */
2256  for (;;)
2257  {
2258  /* Clear any already-pending wakeups */
2260 
2262 
2263  /* Process any requests or signals received recently */
2264  if (ConfigReloadPending)
2265  {
2266  ConfigReloadPending = false;
2269  }
2270 
2271  /* Check for input from the client */
2273 
2274  /*
2275  * If we have received CopyDone from the client, sent CopyDone
2276  * ourselves, and the output buffer is empty, it's time to exit
2277  * streaming.
2278  */
2280  !pq_is_send_pending())
2281  break;
2282 
2283  /*
2284  * If we don't have any pending data in the output buffer, try to send
2285  * some more. If there is some, we don't bother to call send_data
2286  * again until we've flushed it ... but we'd better assume we are not
2287  * caught up.
2288  */
2289  if (!pq_is_send_pending())
2290  send_data();
2291  else
2292  WalSndCaughtUp = false;
2293 
2294  /* Try to flush pending output to the client */
2295  if (pq_flush_if_writable() != 0)
2296  WalSndShutdown();
2297 
2298  /* If nothing remains to be sent right now ... */
2300  {
2301  /*
2302  * If we're in catchup state, move to streaming. This is an
2303  * important state change for users to know about, since before
2304  * this point data loss might occur if the primary dies and we
2305  * need to failover to the standby. The state change is also
2306  * important for synchronous replication, since commits that
2307  * started to wait at that point might wait for some time.
2308  */
2309  if (MyWalSnd->state == WALSNDSTATE_CATCHUP)
2310  {
2311  ereport(DEBUG1,
2312  (errmsg_internal("\"%s\" has now caught up with upstream server",
2313  application_name)));
2315  }
2316 
2317  /*
2318  * When SIGUSR2 arrives, we send any outstanding logs up to the
2319  * shutdown checkpoint record (i.e., the latest record), wait for
2320  * them to be replicated to the standby, and exit. This may be a
2321  * normal termination at shutdown, or a promotion, the walsender
2322  * is not sure which.
2323  */
2324  if (got_SIGUSR2)
2325  WalSndDone(send_data);
2326  }
2327 
2328  /* Check for replication timeout. */
2330 
2331  /* Send keepalive if the time has come */
2333 
2334  /*
2335  * Block if we have unsent data. XXX For logical replication, let
2336  * WalSndWaitForWal() handle any other blocking; idle receivers need
2337  * its additional actions. For physical replication, also block if
2338  * caught up; its send_data does not block.
2339  */
2340  if ((WalSndCaughtUp && send_data != XLogSendLogical &&
2343  {
2344  long sleeptime;
2345  int wakeEvents;
2346 
2348  wakeEvents = WL_SOCKET_READABLE;
2349  else
2350  wakeEvents = 0;
2351 
2352  /*
2353  * Use fresh timestamp, not last_processing, to reduce the chance
2354  * of reaching wal_sender_timeout before sending a keepalive.
2355  */
2357 
2358  if (pq_is_send_pending())
2359  wakeEvents |= WL_SOCKET_WRITEABLE;
2360 
2361  /* Sleep until something happens or we time out */
2362  WalSndWait(wakeEvents, sleeptime, WAIT_EVENT_WAL_SENDER_MAIN);
2363  }
2364  }
2365 }
2366 
2367 /* Initialize a per-walsender data structure for this walsender process */
2368 static void
2370 {
2371  int i;
2372 
2373  /*
2374  * WalSndCtl should be set up already (we inherit this by fork() or
2375  * EXEC_BACKEND mechanism from the postmaster).
2376  */
2377  Assert(WalSndCtl != NULL);
2378  Assert(MyWalSnd == NULL);
2379 
2380  /*
2381  * Find a free walsender slot and reserve it. This must not fail due to
2382  * the prior check for free WAL senders in InitProcess().
2383  */
2384  for (i = 0; i < max_wal_senders; i++)
2385  {
2386  WalSnd *walsnd = &WalSndCtl->walsnds[i];
2387 
2388  SpinLockAcquire(&walsnd->mutex);
2389 
2390  if (walsnd->pid != 0)
2391  {
2392  SpinLockRelease(&walsnd->mutex);
2393  continue;
2394  }
2395  else
2396  {
2397  /*
2398  * Found a free slot. Reserve it for us.
2399  */
2400  walsnd->pid = MyProcPid;
2401  walsnd->state = WALSNDSTATE_STARTUP;
2402  walsnd->sentPtr = InvalidXLogRecPtr;
2403  walsnd->needreload = false;
2404  walsnd->write = InvalidXLogRecPtr;
2405  walsnd->flush = InvalidXLogRecPtr;
2406  walsnd->apply = InvalidXLogRecPtr;
2407  walsnd->writeLag = -1;
2408  walsnd->flushLag = -1;
2409  walsnd->applyLag = -1;
2410  walsnd->sync_standby_priority = 0;
2411  walsnd->latch = &MyProc->procLatch;
2412  walsnd->replyTime = 0;
2413  SpinLockRelease(&walsnd->mutex);
2414  /* don't need the lock anymore */
2415  MyWalSnd = (WalSnd *) walsnd;
2416 
2417  break;
2418  }
2419  }
2420 
2421  Assert(MyWalSnd != NULL);
2422 
2423  /* Arrange to clean up at walsender exit */
2425 }
2426 
2427 /* Destroy the per-walsender data structure for this walsender process */
2428 static void
2430 {
2431  WalSnd *walsnd = MyWalSnd;
2432 
2433  Assert(walsnd != NULL);
2434 
2435  MyWalSnd = NULL;
2436 
2437  SpinLockAcquire(&walsnd->mutex);
2438  /* clear latch while holding the spinlock, so it can safely be read */
2439  walsnd->latch = NULL;
2440  /* Mark WalSnd struct as no longer being in use. */
2441  walsnd->pid = 0;
2442  SpinLockRelease(&walsnd->mutex);
2443 }
2444 
2445 /* XLogReaderRoutine->segment_open callback */
2446 static void
2448  TimeLineID *tli_p)
2449 {
2450  char path[MAXPGPATH];
2451 
2452  /*-------
2453  * When reading from a historic timeline, and there is a timeline switch
2454  * within this segment, read from the WAL segment belonging to the new
2455  * timeline.
2456  *
2457  * For example, imagine that this server is currently on timeline 5, and
2458  * we're streaming timeline 4. The switch from timeline 4 to 5 happened at
2459  * 0/13002088. In pg_wal, we have these files:
2460  *
2461  * ...
2462  * 000000040000000000000012
2463  * 000000040000000000000013
2464  * 000000050000000000000013
2465  * 000000050000000000000014
2466  * ...
2467  *
2468  * In this situation, when requested to send the WAL from segment 0x13, on
2469  * timeline 4, we read the WAL from file 000000050000000000000013. Archive
2470  * recovery prefers files from newer timelines, so if the segment was
2471  * restored from the archive on this server, the file belonging to the old
2472  * timeline, 000000040000000000000013, might not exist. Their contents are
2473  * equal up to the switchpoint, because at a timeline switch, the used
2474  * portion of the old segment is copied to the new file. -------
2475  */
2476  *tli_p = sendTimeLine;
2478  {
2479  XLogSegNo endSegNo;
2480 
2482  if (nextSegNo == endSegNo)
2483  *tli_p = sendTimeLineNextTLI;
2484  }
2485 
2486  XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize);
2487  state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
2488  if (state->seg.ws_file >= 0)
2489  return;
2490 
2491  /*
2492  * If the file is not found, assume it's because the standby asked for a
2493  * too old WAL segment that has already been removed or recycled.
2494  */
2495  if (errno == ENOENT)
2496  {
2497  char xlogfname[MAXFNAMELEN];
2498  int save_errno = errno;
2499 
2500  XLogFileName(xlogfname, *tli_p, nextSegNo, wal_segment_size);
2501  errno = save_errno;
2502  ereport(ERROR,
2504  errmsg("requested WAL segment %s has already been removed",
2505  xlogfname)));
2506  }
2507  else
2508  ereport(ERROR,
2510  errmsg("could not open file \"%s\": %m",
2511  path)));
2512 }
2513 
2514 /*
2515  * Send out the WAL in its normal physical/stored form.
2516  *
2517  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
2518  * but not yet sent to the client, and buffer it in the libpq output
2519  * buffer.
2520  *
2521  * If there is no unsent WAL remaining, WalSndCaughtUp is set to true,
2522  * otherwise WalSndCaughtUp is set to false.
2523  */
2524 static void
2526 {
2527  XLogRecPtr SendRqstPtr;
2529  XLogRecPtr endptr;
2530  Size nbytes;
2531  XLogSegNo segno;
2532  WALReadError errinfo;
2533 
2534  /* If requested switch the WAL sender to the stopping state. */
2535  if (got_STOPPING)
2537 
2539  {
2540  WalSndCaughtUp = true;
2541  return;
2542  }
2543 
2544  /* Figure out how far we can safely send the WAL. */
2546  {
2547  /*
2548  * Streaming an old timeline that's in this server's history, but is
2549  * not the one we're currently inserting or replaying. It can be
2550  * streamed up to the point where we switched off that timeline.
2551  */
2552  SendRqstPtr = sendTimeLineValidUpto;
2553  }
2554  else if (am_cascading_walsender)
2555  {
2556  /*
2557  * Streaming the latest timeline on a standby.
2558  *
2559  * Attempt to send all WAL that has already been replayed, so that we
2560  * know it's valid. If we're receiving WAL through streaming
2561  * replication, it's also OK to send any WAL that has been received
2562  * but not replayed.
2563  *
2564  * The timeline we're recovering from can change, or we can be
2565  * promoted. In either case, the current timeline becomes historic. We
2566  * need to detect that so that we don't try to stream past the point
2567  * where we switched to another timeline. We check for promotion or
2568  * timeline switch after calculating FlushPtr, to avoid a race
2569  * condition: if the timeline becomes historic just after we checked
2570  * that it was still current, it's still be OK to stream it up to the
2571  * FlushPtr that was calculated before it became historic.
2572  */
2573  bool becameHistoric = false;
2574 
2575  SendRqstPtr = GetStandbyFlushRecPtr();
2576 
2577  if (!RecoveryInProgress())
2578  {
2579  /*
2580  * We have been promoted. RecoveryInProgress() updated
2581  * ThisTimeLineID to the new current timeline.
2582  */
2583  am_cascading_walsender = false;
2584  becameHistoric = true;
2585  }
2586  else
2587  {
2588  /*
2589  * Still a cascading standby. But is the timeline we're sending
2590  * still the one recovery is recovering from? ThisTimeLineID was
2591  * updated by the GetStandbyFlushRecPtr() call above.
2592  */
2594  becameHistoric = true;
2595  }
2596 
2597  if (becameHistoric)
2598  {
2599  /*
2600  * The timeline we were sending has become historic. Read the
2601  * timeline history file of the new timeline to see where exactly
2602  * we forked off from the timeline we were sending.
2603  */
2604  List *history;
2605 
2608 
2610  list_free_deep(history);
2611 
2612  sendTimeLineIsHistoric = true;
2613 
2614  SendRqstPtr = sendTimeLineValidUpto;
2615  }
2616  }
2617  else
2618  {
2619  /*
2620  * Streaming the current timeline on a primary.
2621  *
2622  * Attempt to send all data that's already been written out and
2623  * fsync'd to disk. We cannot go further than what's been written out
2624  * given the current implementation of WALRead(). And in any case
2625  * it's unsafe to send WAL that is not securely down to disk on the
2626  * primary: if the primary subsequently crashes and restarts, standbys
2627  * must not have applied any WAL that got lost on the primary.
2628  */
2629  SendRqstPtr = GetFlushRecPtr();
2630  }
2631 
2632  /*
2633  * Record the current system time as an approximation of the time at which
2634  * this WAL location was written for the purposes of lag tracking.
2635  *
2636  * In theory we could make XLogFlush() record a time in shmem whenever WAL
2637  * is flushed and we could get that time as well as the LSN when we call
2638  * GetFlushRecPtr() above (and likewise for the cascading standby
2639  * equivalent), but rather than putting any new code into the hot WAL path
2640  * it seems good enough to capture the time here. We should reach this
2641  * after XLogFlush() runs WalSndWakeupProcessRequests(), and although that
2642  * may take some time, we read the WAL flush pointer and take the time
2643  * very close to together here so that we'll get a later position if it is
2644  * still moving.
2645  *
2646  * Because LagTrackerWrite ignores samples when the LSN hasn't advanced,
2647  * this gives us a cheap approximation for the WAL flush time for this
2648  * LSN.
2649  *
2650  * Note that the LSN is not necessarily the LSN for the data contained in
2651  * the present message; it's the end of the WAL, which might be further
2652  * ahead. All the lag tracking machinery cares about is finding out when
2653  * that arbitrary LSN is eventually reported as written, flushed and
2654  * applied, so that it can measure the elapsed time.
2655  */
2656  LagTrackerWrite(SendRqstPtr, GetCurrentTimestamp());
2657 
2658  /*
2659  * If this is a historic timeline and we've reached the point where we
2660  * forked to the next timeline, stop streaming.
2661  *
2662  * Note: We might already have sent WAL > sendTimeLineValidUpto. The
2663  * startup process will normally replay all WAL that has been received
2664  * from the primary, before promoting, but if the WAL streaming is
2665  * terminated at a WAL page boundary, the valid portion of the timeline
2666  * might end in the middle of a WAL record. We might've already sent the
2667  * first half of that partial WAL record to the cascading standby, so that
2668  * sentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
2669  * replay the partial WAL record either, so it can still follow our
2670  * timeline switch.
2671  */
2673  {
2674  /* close the current file. */
2675  if (xlogreader->seg.ws_file >= 0)
2676  wal_segment_close(xlogreader);
2677 
2678  /* Send CopyDone */
2679  pq_putmessage_noblock('c', NULL, 0);
2680  streamingDoneSending = true;
2681 
2682  WalSndCaughtUp = true;
2683 
2684  elog(DEBUG1, "walsender reached end of timeline at %X/%X (sent up to %X/%X)",
2687  return;
2688  }
2689 
2690  /* Do we have any work to do? */
2691  Assert(sentPtr <= SendRqstPtr);
2692  if (SendRqstPtr <= sentPtr)
2693  {
2694  WalSndCaughtUp = true;
2695  return;
2696  }
2697 
2698  /*
2699  * Figure out how much to send in one message. If there's no more than
2700  * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
2701  * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
2702  *
2703  * The rounding is not only for performance reasons. Walreceiver relies on
2704  * the fact that we never split a WAL record across two messages. Since a
2705  * long WAL record is split at page boundary into continuation records,
2706  * page boundary is always a safe cut-off point. We also assume that
2707  * SendRqstPtr never points to the middle of a WAL record.
2708  */
2709  startptr = sentPtr;
2710  endptr = startptr;
2711  endptr += MAX_SEND_SIZE;
2712 
2713  /* if we went beyond SendRqstPtr, back off */
2714  if (SendRqstPtr <= endptr)
2715  {
2716  endptr = SendRqstPtr;
2718  WalSndCaughtUp = false;
2719  else
2720  WalSndCaughtUp = true;
2721  }
2722  else
2723  {
2724  /* round down to page boundary. */
2725  endptr -= (endptr % XLOG_BLCKSZ);
2726  WalSndCaughtUp = false;
2727  }
2728 
2729  nbytes = endptr - startptr;
2730  Assert(nbytes <= MAX_SEND_SIZE);
2731 
2732  /*
2733  * OK to read and send the slice.
2734  */
2735  resetStringInfo(&output_message);
2736  pq_sendbyte(&output_message, 'w');
2737 
2738  pq_sendint64(&output_message, startptr); /* dataStart */
2739  pq_sendint64(&output_message, SendRqstPtr); /* walEnd */
2740  pq_sendint64(&output_message, 0); /* sendtime, filled in last */
2741 
2742  /*
2743  * Read the log directly into the output buffer to avoid extra memcpy
2744  * calls.
2745  */
2746  enlargeStringInfo(&output_message, nbytes);
2747 
2748 retry:
2749  if (!WALRead(xlogreader, WalSndSegmentOpen, wal_segment_close,
2750  &output_message.data[output_message.len],
2751  startptr,
2752  nbytes,
2753  xlogreader->seg.ws_tli, /* Pass the current TLI because
2754  * only WalSndSegmentOpen controls
2755  * whether new TLI is needed. */
2756  &errinfo))
2757  WALReadRaiseError(&errinfo);
2758 
2759  /* See logical_read_xlog_page(). */
2760  XLByteToSeg(startptr, segno, xlogreader->segcxt.ws_segsize);
2761  CheckXLogRemoved(segno, xlogreader->seg.ws_tli);
2762 
2763  /*
2764  * During recovery, the currently-open WAL file might be replaced with the
2765  * file of the same name retrieved from archive. So we always need to
2766  * check what we read was valid after reading into the buffer. If it's
2767  * invalid, we try to open and read the file again.
2768  */
2770  {
2771  WalSnd *walsnd = MyWalSnd;
2772  bool reload;
2773 
2774  SpinLockAcquire(&walsnd->mutex);
2775  reload = walsnd->needreload;
2776  walsnd->needreload = false;
2777  SpinLockRelease(&walsnd->mutex);
2778 
2779  if (reload && xlogreader->seg.ws_file >= 0)
2780  {
2781  wal_segment_close(xlogreader);
2782 
2783  goto retry;
2784  }
2785  }
2786 
2787  output_message.len += nbytes;
2788  output_message.data[output_message.len] = '\0';
2789 
2790  /*
2791  * Fill the send timestamp last, so that it is taken as late as possible.
2792  */
2793  resetStringInfo(&tmpbuf);
2794  pq_sendint64(&tmpbuf, GetCurrentTimestamp());
2795  memcpy(&output_message.data[1 + sizeof(int64) + sizeof(int64)],
2796  tmpbuf.data, sizeof(int64));
2797 
2798  pq_putmessage_noblock('d', output_message.data, output_message.len);
2799 
2800  sentPtr = endptr;
2801 
2802  /* Update shared memory status */
2803  {
2804  WalSnd *walsnd = MyWalSnd;
2805 
2806  SpinLockAcquire(&walsnd->mutex);
2807  walsnd->sentPtr = sentPtr;
2808  SpinLockRelease(&walsnd->mutex);
2809  }
2810 
2811  /* Report progress of XLOG streaming in PS display */
2813  {
2814  char activitymsg[50];
2815 
2816  snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
2818  set_ps_display(activitymsg);
2819  }
2820 }
2821 
2822 /*
2823  * Stream out logically decoded data.
2824  */
2825 static void
2827 {
2828  XLogRecord *record;
2829  char *errm;
2830 
2831  /*
2832  * We'll use the current flush point to determine whether we've caught up.
2833  * This variable is static in order to cache it across calls. Caching is
2834  * helpful because GetFlushRecPtr() needs to acquire a heavily-contended
2835  * spinlock.
2836  */
2837  static XLogRecPtr flushPtr = InvalidXLogRecPtr;
2838 
2839  /*
2840  * Don't know whether we've caught up yet. We'll set WalSndCaughtUp to
2841  * true in WalSndWaitForWal, if we're actually waiting. We also set to
2842  * true if XLogReadRecord() had to stop reading but WalSndWaitForWal
2843  * didn't wait - i.e. when we're shutting down.
2844  */
2845  WalSndCaughtUp = false;
2846 
2847  while (XLogReadRecord(logical_decoding_ctx->reader, &record, &errm) ==
2849  {
2850  if (!logical_decoding_ctx->page_read(logical_decoding_ctx->reader))
2851  break;
2852  }
2853 
2854  /* xlog record was invalid */
2855  if (errm != NULL)
2856  elog(ERROR, "%s", errm);
2857 
2858  if (record != NULL)
2859  {
2860  /*
2861  * Note the lack of any call to LagTrackerWrite() which is handled by
2862  * WalSndUpdateProgress which is called by output plugin through
2863  * logical decoding write api.
2864  */
2865  LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
2866 
2867  sentPtr = logical_decoding_ctx->reader->EndRecPtr;
2868  }
2869 
2870  /*
2871  * If first time through in this session, initialize flushPtr. Otherwise,
2872  * we only need to update flushPtr if EndRecPtr is past it.
2873  */
2874  if (flushPtr == InvalidXLogRecPtr)
2875  flushPtr = GetFlushRecPtr();
2876  else if (logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
2877  flushPtr = GetFlushRecPtr();
2878 
2879  /* If EndRecPtr is still past our flushPtr, it means we caught up. */
2880  if (logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
2881  WalSndCaughtUp = true;
2882 
2883  /*
2884  * If we're caught up and have been requested to stop, have WalSndLoop()
2885  * terminate the connection in an orderly manner, after writing out all
2886  * the pending data.
2887  */
2889  got_SIGUSR2 = true;
2890 
2891  /* Update shared memory status */
2892  {
2893  WalSnd *walsnd = MyWalSnd;
2894 
2895  SpinLockAcquire(&walsnd->mutex);
2896  walsnd->sentPtr = sentPtr;
2897  SpinLockRelease(&walsnd->mutex);
2898  }
2899 }
2900 
2901 /*
2902  * Shutdown if the sender is caught up.
2903  *
2904  * NB: This should only be called when the shutdown signal has been received
2905  * from postmaster.
2906  *
2907  * Note that if we determine that there's still more data to send, this
2908  * function will return control to the caller.
2909  */
2910 static void
2912 {
2913  XLogRecPtr replicatedPtr;
2914 
2915  /* ... let's just be real sure we're caught up ... */
2916  send_data();
2917 
2918  /*
2919  * To figure out whether all WAL has successfully been replicated, check
2920  * flush location if valid, write otherwise. Tools like pg_receivewal will
2921  * usually (unless in synchronous mode) return an invalid flush location.
2922  */
2923  replicatedPtr = XLogRecPtrIsInvalid(MyWalSnd->flush) ?
2924  MyWalSnd->write : MyWalSnd->flush;
2925 
2926  if (WalSndCaughtUp && sentPtr == replicatedPtr &&
2927  !pq_is_send_pending())
2928  {
2929  QueryCompletion qc;
2930 
2931  /* Inform the standby that XLOG streaming is done */
2932  SetQueryCompletion(&qc, CMDTAG_COPY, 0);
2933  EndCommand(&qc, DestRemote, false);
2934  pq_flush();
2935 
2936  proc_exit(0);
2937  }
2939  WalSndKeepalive(true);
2940 }
2941 
2942 /*
2943  * Returns the latest point in WAL that has been safely flushed to disk, and
2944  * can be sent to the standby. This should only be called when in recovery,
2945  * ie. we're streaming to a cascaded standby.
2946  *
2947  * As a side-effect, ThisTimeLineID is updated to the TLI of the last
2948  * replayed WAL record.
2949  */
2950 static XLogRecPtr
2952 {
2953  XLogRecPtr replayPtr;
2954  TimeLineID replayTLI;
2955  XLogRecPtr receivePtr;
2957  XLogRecPtr result;
2958 
2959  /*
2960  * We can safely send what's already been replayed. Also, if walreceiver
2961  * is streaming WAL from the same timeline, we can send anything that it
2962  * has streamed, but hasn't been replayed yet.
2963  */
2964 
2965  receivePtr = GetWalRcvFlushRecPtr(NULL, &receiveTLI);
2966  replayPtr = GetXLogReplayRecPtr(&replayTLI);
2967 
2968  ThisTimeLineID = replayTLI;
2969 
2970  result = replayPtr;
2971  if (receiveTLI == ThisTimeLineID && receivePtr > replayPtr)
2972  result = receivePtr;
2973 
2974  return result;
2975 }
2976 
2977 /*
2978  * Request walsenders to reload the currently-open WAL file
2979  */
2980 void
2982 {
2983  int i;
2984 
2985  for (i = 0; i < max_wal_senders; i++)
2986  {
2987  WalSnd *walsnd = &WalSndCtl->walsnds[i];
2988 
2989  SpinLockAcquire(&walsnd->mutex);
2990  if (walsnd->pid == 0)
2991  {
2992  SpinLockRelease(&walsnd->mutex);
2993  continue;
2994  }
2995  walsnd->needreload = true;
2996  SpinLockRelease(&walsnd->mutex);
2997  }
2998 }
2999 
3000 /*
3001  * Handle PROCSIG_WALSND_INIT_STOPPING signal.
3002  */
3003 void
3005 {
3007 
3008  /*
3009  * If replication has not yet started, die like with SIGTERM. If
3010  * replication is active, only set a flag and wake up the main loop. It
3011  * will send any outstanding WAL, wait for it to be replicated to the
3012  * standby, and then exit gracefully.
3013  */
3014  if (!replication_active)
3015  kill(MyProcPid, SIGTERM);
3016  else
3017  got_STOPPING = true;
3018 }
3019 
3020 /*
3021  * SIGUSR2: set flag to do a last cycle and shut down afterwards. The WAL
3022  * sender should already have been switched to WALSNDSTATE_STOPPING at
3023  * this point.
3024  */
3025 static void
3027 {
3028  int save_errno = errno;
3029 
3030  got_SIGUSR2 = true;
3031  SetLatch(MyLatch);
3032 
3033  errno = save_errno;
3034 }
3035 
3036 /* Set up signal handlers */
3037 void
3039 {
3040  /* Set up signal handlers */
3042  pqsignal(SIGINT, StatementCancelHandler); /* query cancel */
3043  pqsignal(SIGTERM, die); /* request shutdown */
3044  /* SIGQUIT handler was already set up by InitPostmasterChild */
3045  InitializeTimeouts(); /* establishes SIGALRM handler */
3048  pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
3049  * shutdown */
3050 
3051  /* Reset some signals that are accepted by postmaster but not here */
3053 }
3054 
3055 /* Report shared-memory space needed by WalSndShmemInit */
3056 Size
3058 {
3059  Size size = 0;
3060 
3061  size = offsetof(WalSndCtlData, walsnds);
3062  size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
3063 
3064  return size;
3065 }
3066 
3067 /* Allocate and initialize walsender-related shared memory */
3068 void
3070 {
3071  bool found;
3072  int i;
3073 
3074  WalSndCtl = (WalSndCtlData *)
3075  ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
3076 
3077  if (!found)
3078  {
3079  /* First time through, so initialize */
3080  MemSet(WalSndCtl, 0, WalSndShmemSize());
3081 
3082  for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
3083  SHMQueueInit(&(WalSndCtl->SyncRepQueue[i]));
3084 
3085  for (i = 0; i < max_wal_senders; i++)
3086  {
3087  WalSnd *walsnd = &WalSndCtl->walsnds[i];
3088 
3089  SpinLockInit(&walsnd->mutex);
3090  }
3091  }
3092 }
3093 
3094 /*
3095  * Wake up all walsenders
3096  *
3097  * This will be called inside critical sections, so throwing an error is not
3098  * advisable.
3099  */
3100 void
3102 {
3103  int i;
3104 
3105  for (i = 0; i < max_wal_senders; i++)
3106  {
3107  Latch *latch;
3108  WalSnd *walsnd = &WalSndCtl->walsnds[i];
3109 
3110  /*
3111  * Get latch pointer with spinlock held, for the unlikely case that
3112  * pointer reads aren't atomic (as they're 8 bytes).
3113  */
3114  SpinLockAcquire(&walsnd->mutex);
3115  latch = walsnd->latch;
3116  SpinLockRelease(&walsnd->mutex);
3117 
3118  if (latch != NULL)
3119  SetLatch(latch);
3120  }
3121 }
3122 
3123 /*
3124  * Wait for readiness on the FeBe socket, or a timeout. The mask should be
3125  * composed of optional WL_SOCKET_WRITEABLE and WL_SOCKET_READABLE flags. Exit
3126  * on postmaster death.
3127  */
3128 static void
3129 WalSndWait(uint32 socket_events, long timeout, uint32 wait_event)
3130 {
3131  WaitEvent event;
3132 
3133  ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetSocketPos, socket_events, NULL);
3134  if (WaitEventSetWait(FeBeWaitSet, timeout, &event, 1, wait_event) == 1 &&
3135  (event.events & WL_POSTMASTER_DEATH))
3136  proc_exit(1);
3137 }
3138 
3139 /*
3140  * Signal all walsenders to move to stopping state.
3141  *
3142  * This will trigger walsenders to move to a state where no further WAL can be
3143  * generated. See this file's header for details.
3144  */
3145 void
3147 {
3148  int i;
3149 
3150  for (i = 0; i < max_wal_senders; i++)
3151  {
3152  WalSnd *walsnd = &WalSndCtl->walsnds[i];
3153  pid_t pid;
3154 
3155  SpinLockAcquire(&walsnd->mutex);
3156  pid = walsnd->pid;
3157  SpinLockRelease(&walsnd->mutex);
3158 
3159  if (pid == 0)
3160  continue;
3161 
3163  }
3164 }
3165 
3166 /*
3167  * Wait that all the WAL senders have quit or reached the stopping state. This
3168  * is used by the checkpointer to control when the shutdown checkpoint can
3169  * safely be performed.
3170  */
3171 void
3173 {
3174  for (;;)
3175  {
3176  int i;
3177  bool all_stopped = true;
3178 
3179  for (i = 0; i < max_wal_senders; i++)
3180  {
3181  WalSnd *walsnd = &WalSndCtl->walsnds[i];
3182 
3183  SpinLockAcquire(&walsnd->mutex);
3184 
3185  if (walsnd->pid == 0)
3186  {
3187  SpinLockRelease(&walsnd->mutex);
3188  continue;
3189  }
3190 
3191  if (walsnd->state != WALSNDSTATE_STOPPING)
3192  {
3193  all_stopped = false;
3194  SpinLockRelease(&walsnd->mutex);
3195  break;
3196  }
3197  SpinLockRelease(&walsnd->mutex);
3198  }
3199 
3200  /* safe to leave if confirmation is done for all WAL senders */
3201  if (all_stopped)
3202  return;
3203 
3204  pg_usleep(10000L); /* wait for 10 msec */
3205  }
3206 }
3207 
3208 /* Set state for current walsender (only called in walsender) */
3209 void
3211 {
3212  WalSnd *walsnd = MyWalSnd;
3213 
3215 
3216  if (walsnd->state == state)
3217  return;
3218 
3219  SpinLockAcquire(&walsnd->mutex);
3220  walsnd->state = state;
3221  SpinLockRelease(&walsnd->mutex);
3222 }
3223 
3224 /*
3225  * Return a string constant representing the state. This is used
3226  * in system views, and should *not* be translated.
3227  */
3228 static const char *
3230 {
3231  switch (state)
3232  {
3233  case WALSNDSTATE_STARTUP:
3234  return "startup";
3235  case WALSNDSTATE_BACKUP:
3236  return "backup";
3237  case WALSNDSTATE_CATCHUP:
3238  return "catchup";
3239  case WALSNDSTATE_STREAMING:
3240  return "streaming";
3241  case WALSNDSTATE_STOPPING:
3242  return "stopping";
3243  }
3244  return "UNKNOWN";
3245 }
3246 
3247 static Interval *
3249 {
3250  Interval *result = palloc(sizeof(Interval));
3251 
3252  result->month = 0;
3253  result->day = 0;
3254  result->time = offset;
3255 
3256  return result;
3257 }
3258 
3259 /*
3260  * Returns activity of walsenders, including pids and xlog locations sent to
3261  * standby servers.
3262  */
3263 Datum
3265 {
3266 #define PG_STAT_GET_WAL_SENDERS_COLS 12
3267  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
3268  TupleDesc tupdesc;
3269  Tuplestorestate *tupstore;
3270  MemoryContext per_query_ctx;
3271  MemoryContext oldcontext;
3272  SyncRepStandbyData *sync_standbys;
3273  int num_standbys;
3274  int i;
3275 
3276  /* check to see if caller supports us returning a tuplestore */
3277  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
3278  ereport(ERROR,
3279  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3280  errmsg("set-valued function called in context that cannot accept a set")));
3281  if (!(rsinfo->allowedModes & SFRM_Materialize))
3282  ereport(ERROR,
3283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3284  errmsg("materialize mode required, but it is not allowed in this context")));
3285 
3286  /* Build a tuple descriptor for our result type */
3287  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
3288  elog(ERROR, "return type must be a row type");
3289 
3290  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
3291  oldcontext = MemoryContextSwitchTo(per_query_ctx);
3292 
3293  tupstore = tuplestore_begin_heap(true, false, work_mem);
3294  rsinfo->returnMode = SFRM_Materialize;
3295  rsinfo->setResult = tupstore;
3296  rsinfo->setDesc = tupdesc;
3297 
3298  MemoryContextSwitchTo(oldcontext);
3299 
3300  /*
3301  * Get the currently active synchronous standbys. This could be out of
3302  * date before we're done, but we'll use the data anyway.
3303  */
3304  num_standbys = SyncRepGetCandidateStandbys(&sync_standbys);
3305 
3306  for (i = 0; i < max_wal_senders; i++)
3307  {
3308  WalSnd *walsnd = &WalSndCtl->walsnds[i];
3310  XLogRecPtr write;
3311  XLogRecPtr flush;
3312  XLogRecPtr apply;
3313  TimeOffset writeLag;
3314  TimeOffset flushLag;
3315  TimeOffset applyLag;
3316  int priority;
3317  int pid;
3319  TimestampTz replyTime;
3320  bool is_sync_standby;
3322  bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
3323  int j;
3324 
3325  /* Collect data from shared memory */
3326  SpinLockAcquire(&walsnd->mutex);
3327  if (walsnd->pid == 0)
3328  {
3329  SpinLockRelease(&walsnd->mutex);
3330  continue;
3331  }
3332  pid = walsnd->pid;
3333  sentPtr = walsnd->sentPtr;
3334  state = walsnd->state;
3335  write = walsnd->write;
3336  flush = walsnd->flush;
3337  apply = walsnd->apply;
3338  writeLag = walsnd->writeLag;
3339  flushLag = walsnd->flushLag;
3340  applyLag = walsnd->applyLag;
3341  priority = walsnd->sync_standby_priority;
3342  replyTime = walsnd->replyTime;
3343  SpinLockRelease(&walsnd->mutex);
3344 
3345  /*
3346  * Detect whether walsender is/was considered synchronous. We can
3347  * provide some protection against stale data by checking the PID
3348  * along with walsnd_index.
3349  */
3350  is_sync_standby = false;
3351  for (j = 0; j < num_standbys; j++)
3352  {
3353  if (sync_standbys[j].walsnd_index == i &&
3354  sync_standbys[j].pid == pid)
3355  {
3356  is_sync_standby = true;
3357  break;
3358  }
3359  }
3360 
3361  memset(nulls, 0, sizeof(nulls));
3362  values[0] = Int32GetDatum(pid);
3363 
3364  if (!is_member_of_role(GetUserId(), ROLE_PG_READ_ALL_STATS))
3365  {
3366  /*
3367  * Only superusers and members of pg_read_all_stats can see
3368  * details. Other users only get the pid value to know it's a
3369  * walsender, but no details.
3370  */
3371  MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
3372  }
3373  else
3374  {
3375  values[1] = CStringGetTextDatum(WalSndGetStateString(state));
3376 
3377  if (XLogRecPtrIsInvalid(sentPtr))
3378  nulls[2] = true;
3379  values[2] = LSNGetDatum(sentPtr);
3380 
3381  if (XLogRecPtrIsInvalid(write))
3382  nulls[3] = true;
3383  values[3] = LSNGetDatum(write);
3384 
3385  if (XLogRecPtrIsInvalid(flush))
3386  nulls[4] = true;
3387  values[4] = LSNGetDatum(flush);
3388 
3389  if (XLogRecPtrIsInvalid(apply))
3390  nulls[5] = true;
3391  values[5] = LSNGetDatum(apply);
3392 
3393  /*
3394  * Treat a standby such as a pg_basebackup background process
3395  * which always returns an invalid flush location, as an
3396  * asynchronous standby.
3397  */
3398  priority = XLogRecPtrIsInvalid(flush) ? 0 : priority;
3399 
3400  if (writeLag < 0)
3401  nulls[6] = true;
3402  else
3403  values[6] = IntervalPGetDatum(offset_to_interval(writeLag));
3404 
3405  if (flushLag < 0)
3406  nulls[7] = true;
3407  else
3408  values[7] = IntervalPGetDatum(offset_to_interval(flushLag));
3409 
3410  if (applyLag < 0)
3411  nulls[8] = true;
3412  else
3413  values[8] = IntervalPGetDatum(offset_to_interval(applyLag));
3414 
3415  values[9] = Int32GetDatum(priority);
3416 
3417  /*
3418  * More easily understood version of standby state. This is purely
3419  * informational.
3420  *
3421  * In quorum-based sync replication, the role of each standby
3422  * listed in synchronous_standby_names can be changing very
3423  * frequently. Any standbys considered as "sync" at one moment can
3424  * be switched to "potential" ones at the next moment. So, it's
3425  * basically useless to report "sync" or "potential" as their sync
3426  * states. We report just "quorum" for them.
3427  */
3428  if (priority == 0)
3429  values[10] = CStringGetTextDatum("async");
3430  else if (is_sync_standby)
3432  CStringGetTextDatum("sync") : CStringGetTextDatum("quorum");
3433  else
3434  values[10] = CStringGetTextDatum("potential");
3435 
3436  if (replyTime == 0)
3437  nulls[11] = true;
3438  else
3439  values[11] = TimestampTzGetDatum(replyTime);
3440  }
3441 
3442  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
3443  }
3444 
3445  /* clean up and return the tuplestore */
3446  tuplestore_donestoring(tupstore);
3447 
3448  return (Datum) 0;
3449 }
3450 
3451 /*
3452  * Send a keepalive message to standby.
3453  *
3454  * If requestReply is set, the message requests the other party to send
3455  * a message back to us, for heartbeat purposes. We also set a flag to
3456  * let nearby code that we're waiting for that response, to avoid
3457  * repeated requests.
3458  */
3459 static void
3460 WalSndKeepalive(bool requestReply)
3461 {
3462  elog(DEBUG2, "sending replication keepalive");
3463 
3464  /* construct the message... */
3465  resetStringInfo(&output_message);
3466  pq_sendbyte(&output_message, 'k');
3467  pq_sendint64(&output_message, sentPtr);
3468  pq_sendint64(&output_message, GetCurrentTimestamp());
3469  pq_sendbyte(&output_message, requestReply ? 1 : 0);
3470 
3471  /* ... and send it wrapped in CopyData */
3472  pq_putmessage_noblock('d', output_message.data, output_message.len);
3473 
3474  /* Set local flag */
3475  if (requestReply)
3477 }
3478 
3479 /*
3480  * Send keepalive message if too much time has elapsed.
3481  */
3482 static void
3484 {
3485  TimestampTz ping_time;
3486 
3487  /*
3488  * Don't send keepalive messages if timeouts are globally disabled or
3489  * we're doing something not partaking in timeouts.
3490  */
3491  if (wal_sender_timeout <= 0 || last_reply_timestamp <= 0)
3492  return;
3493 
3495  return;
3496 
3497  /*
3498  * If half of wal_sender_timeout has lapsed without receiving any reply
3499  * from the standby, send a keep-alive message to the standby requesting
3500  * an immediate reply.
3501  */
3503  wal_sender_timeout / 2);
3504  if (last_processing >= ping_time)
3505  {
3506  WalSndKeepalive(true);
3507 
3508  /* Try to flush pending output to the client */
3509  if (pq_flush_if_writable() != 0)
3510  WalSndShutdown();
3511  }
3512 }
3513 
3514 /*
3515  * Record the end of the WAL and the time it was flushed locally, so that
3516  * LagTrackerRead can compute the elapsed time (lag) when this WAL location is
3517  * eventually reported to have been written, flushed and applied by the
3518  * standby in a reply message.
3519  */
3520 static void
3522 {
3523  bool buffer_full;
3524  int new_write_head;
3525  int i;
3526 
3527  if (!am_walsender)
3528  return;
3529 
3530  /*
3531  * If the lsn hasn't advanced since last time, then do nothing. This way
3532  * we only record a new sample when new WAL has been written.
3533  */
3534  if (lag_tracker->last_lsn == lsn)
3535  return;
3536  lag_tracker->last_lsn = lsn;
3537 
3538  /*
3539  * If advancing the write head of the circular buffer would crash into any
3540  * of the read heads, then the buffer is full. In other words, the
3541  * slowest reader (presumably apply) is the one that controls the release
3542  * of space.
3543  */
3544  new_write_head = (lag_tracker->write_head + 1) % LAG_TRACKER_BUFFER_SIZE;
3545  buffer_full = false;
3546  for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; ++i)
3547  {
3548  if (new_write_head == lag_tracker->read_heads[i])
3549  buffer_full = true;
3550  }
3551 
3552  /*
3553  * If the buffer is full, for now we just rewind by one slot and overwrite
3554  * the last sample, as a simple (if somewhat uneven) way to lower the
3555  * sampling rate. There may be better adaptive compaction algorithms.
3556  */
3557  if (buffer_full)
3558  {
3559  new_write_head = lag_tracker->write_head;
3560  if (lag_tracker->write_head > 0)
3561  lag_tracker->write_head--;
3562  else
3563  lag_tracker->write_head = LAG_TRACKER_BUFFER_SIZE - 1;
3564  }
3565 
3566  /* Store a sample at the current write head position. */
3567  lag_tracker->buffer[lag_tracker->write_head].lsn = lsn;
3568  lag_tracker->buffer[lag_tracker->write_head].time = local_flush_time;
3569  lag_tracker->write_head = new_write_head;
3570 }
3571 
3572 /*
3573  * Find out how much time has elapsed between the moment WAL location 'lsn'
3574  * (or the highest known earlier LSN) was flushed locally and the time 'now'.
3575  * We have a separate read head for each of the reported LSN locations we
3576  * receive in replies from standby; 'head' controls which read head is
3577  * used. Whenever a read head crosses an LSN which was written into the
3578  * lag buffer with LagTrackerWrite, we can use the associated timestamp to
3579  * find out the time this LSN (or an earlier one) was flushed locally, and
3580  * therefore compute the lag.
3581  *
3582  * Return -1 if no new sample data is available, and otherwise the elapsed
3583  * time in microseconds.
3584  */
3585 static TimeOffset
3587 {
3588  TimestampTz time = 0;
3589 
3590  /* Read all unread samples up to this LSN or end of buffer. */
3591  while (lag_tracker->read_heads[head] != lag_tracker->write_head &&
3592  lag_tracker->buffer[lag_tracker->read_heads[head]].lsn <= lsn)
3593  {
3594  time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
3595  lag_tracker->last_read[head] =
3596  lag_tracker->buffer[lag_tracker->read_heads[head]];
3597  lag_tracker->read_heads[head] =
3598  (lag_tracker->read_heads[head] + 1) % LAG_TRACKER_BUFFER_SIZE;
3599  }
3600 
3601  /*
3602  * If the lag tracker is empty, that means the standby has processed
3603  * everything we've ever sent so we should now clear 'last_read'. If we
3604  * didn't do that, we'd risk using a stale and irrelevant sample for
3605  * interpolation at the beginning of the next burst of WAL after a period
3606  * of idleness.
3607  */
3608  if (lag_tracker->read_heads[head] == lag_tracker->write_head)
3609  lag_tracker->last_read[head].time = 0;
3610 
3611  if (time > now)
3612  {
3613  /* If the clock somehow went backwards, treat as not found. */
3614  return -1;
3615  }
3616  else if (time == 0)
3617  {
3618  /*
3619  * We didn't cross a time. If there is a future sample that we
3620  * haven't reached yet, and we've already reached at least one sample,
3621  * let's interpolate the local flushed time. This is mainly useful
3622  * for reporting a completely stuck apply position as having
3623  * increasing lag, since otherwise we'd have to wait for it to
3624  * eventually start moving again and cross one of our samples before
3625  * we can show the lag increasing.
3626  */
3627  if (lag_tracker->read_heads[head] == lag_tracker->write_head)
3628  {
3629  /* There are no future samples, so we can't interpolate. */
3630  return -1;
3631  }
3632  else if (lag_tracker->last_read[head].time != 0)
3633  {
3634  /* We can interpolate between last_read and the next sample. */
3635  double fraction;
3636  WalTimeSample prev = lag_tracker->last_read[head];
3637  WalTimeSample next = lag_tracker->buffer[lag_tracker->read_heads[head]];
3638 
3639  if (lsn < prev.lsn)
3640  {
3641  /*
3642  * Reported LSNs shouldn't normally go backwards, but it's
3643  * possible when there is a timeline change. Treat as not
3644  * found.
3645  */
3646  return -1;
3647  }
3648 
3649  Assert(prev.lsn < next.lsn);
3650 
3651  if (prev.time > next.time)
3652  {
3653  /* If the clock somehow went backwards, treat as not found. */
3654  return -1;
3655  }
3656 
3657  /* See how far we are between the previous and next samples. */
3658  fraction =
3659  (double) (lsn - prev.lsn) / (double) (next.lsn - prev.lsn);
3660 
3661  /* Scale the local flush time proportionally. */
3662  time = (TimestampTz)
3663  ((double) prev.time + (next.time - prev.time) * fraction);
3664  }
3665  else
3666  {
3667  /*
3668  * We have only a future sample, implying that we were entirely
3669  * caught up but and now there is a new burst of WAL and the
3670  * standby hasn't processed the first sample yet. Until the
3671  * standby reaches the future sample the best we can do is report
3672  * the hypothetical lag if that sample were to be replayed now.
3673  */
3674  time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
3675  }
3676  }
3677 
3678  /* Return the elapsed time since local flush time in microseconds. */
3679  Assert(time != 0);
3680  return now - time;
3681 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
static void InitWalSenderSlot(void)
Definition: walsender.c:2369
void InitializeTimeouts(void)
Definition: timeout.c:435
#define pq_is_send_pending()
Definition: libpq.h:39
#define NIL
Definition: pg_list.h:65
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
XLogRecPtr write
#define WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:213
static void ProcessStandbyMessage(void)
Definition: walsender.c:1800
#define pg_attribute_noreturn()
Definition: c.h:179
#define FeBeWaitSetSocketPos
Definition: libpq.h:54
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
static void WalSndWait(uint32 socket_events, long timeout, uint32 wait_event)
Definition: walsender.c:3129
XLogRecPtr startpoint
Definition: replnodes.h:86
#define DEBUG1
Definition: elog.h:25
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
int MyProcPid
Definition: globals.c:43
int wal_sender_timeout
Definition: walsender.c:123
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:823
uint32 TimeLineID
Definition: xlogdefs.h:59
#define pq_flush()
Definition: libpq.h:37
static int32 next
Definition: blutils.c:219
static void pgstat_report_wait_end(void)
Definition: wait_event.h:277
void ProcessConfigFile(GucContext context)
int wal_segment_size
Definition: xlog.c:121
int write_head
Definition: walsender.c:214
uint32 TransactionId
Definition: c.h:587
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, WALSegmentCleanupCB cleanup_cb)
Definition: xlogreader.c:82
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
bool wake_wal_senders
Definition: walsender.c:130
#define SYNC_REP_PRIORITY
Definition: syncrep.h:36
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1502
Oid GetUserId(void)
Definition: miscinit.c:478
#define SIGUSR1
Definition: win32_port.h:171
bool update_process_title
Definition: ps_status.c:36
#define write(a, b, c)
Definition: win32.h:14
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
static void WalSndLastCycleHandler(SIGNAL_ARGS)
Definition: walsender.c:3026
static void SendTimeLineHistory(TimeLineHistoryCmd *cmd)
Definition: walsender.c:465
static void parseCreateReplSlotOptions(CreateReplicationSlotCmd *cmd, bool *reserve_wal, CRSSnapshotAction *snapshot_action)
Definition: walsender.c:867
static void DropReplicationSlot(DropReplicationSlotCmd *cmd)
Definition: walsender.c:1122
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
int64 TimestampTz
Definition: timestamp.h:39
WalTimeSample last_read[NUM_SYNC_REP_WAIT_MODE]
Definition: walsender.c:216
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
Size WalSndShmemSize(void)
Definition: walsender.c:3057
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void MarkPostmasterChildWalSender(void)
Definition: pmsignal.c:307
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void CommitTransactionCommand(void)
Definition: xact.c:2939
#define XACT_REPEATABLE_READ
Definition: xact.h:38
#define SpinLockInit(lock)
Definition: spin.h:60
uint8 syncrep_method
Definition: syncrep.h:69
LogicalDecodingContext * CreateDecodingContext(XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, LogicalDecodingXLogPageReadCB page_read, WALSegmentCleanupCB cleanup_cb, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:479
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
void WALReadRaiseError(WALReadError *errinfo)
Definition: xlogutils.c:974
List * readTimeLineHistory(TimeLineID targetTLI)
Definition: timeline.c:76
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static void XLogSendPhysical(void)
Definition: walsender.c:2525
void do_tup_output(TupOutputState *tstate, Datum *values, bool *isnull)
Definition: execTuples.c:2256
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
TimeOffset flushLag
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:737
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:539
static StringInfoData output_message
Definition: walsender.c:157
WalSndCtlData * WalSndCtl
Definition: walsender.c:109
struct cursor * cur
Definition: ecpg.c:28
static volatile sig_atomic_t got_STOPPING
Definition: walsender.c:187
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4701
#define MemSet(start, val, len)
Definition: c.h:1008
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
static void WalSndKill(int code, Datum arg)
Definition: walsender.c:2429
#define kill(pid, sig)
Definition: win32_port.h:454
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase)
Definition: slot.c:228
WalSnd walsnds[FLEXIBLE_ARRAY_MEMBER]
static void WalSndDone(WalSndSendDataCallback send_data)
Definition: walsender.c:2911
#define WL_SOCKET_READABLE
Definition: latch.h:126
void ReplicationSlotSave(void)
Definition: slot.c:732
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8589
void pq_sendstring(StringInfo buf, const char *str)
Definition: pqformat.c:197
TimestampTz time
Definition: walsender.c:203
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void RestoreTransactionSnapshot(Snapshot snapshot, void *source_pgproc)
Definition: snapmgr.c:2226
#define SIGPIPE
Definition: win32_port.h:164
ReplicationSlotPersistentData data
Definition: slot.h:156
TimeOffset writeLag
#define SIGUSR2
Definition: win32_port.h:172
#define LOG
Definition: elog.h:26
static void pq_sendint64(StringInfo buf, uint64 i)
Definition: pqformat.h:153
bool RecoveryInProgress(void)
Definition: xlog.c:8237
void SetLatch(Latch *latch)
Definition: latch.c:567
SyncRepConfigData * SyncRepConfig
Definition: syncrep.c:97
XLogReadRecordResult XLogReadRecord(XLogReaderState *state, XLogRecord **record, char **errormsg)
Definition: xlogreader.c:346
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
void list_free_deep(List *list)
Definition: list.c:1405
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
void GetPGVariable(const char *name, DestReceiver *dest)
Definition: guc.c:9333
void ResetLatch(Latch *latch)
Definition: latch.c:660
slock_t mutex
Node * replication_parse_result
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2931
Latch procLatch
Definition: proc.h:130
void XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage, uint32 wantLength)
Definition: xlogutils.c:702
XLogRecPtr confirmed_flush
Definition: slot.h:92
XLogRecPtr EndRecPtr
Definition: xlogreader.h:179
int32 day
Definition: timestamp.h:47
#define XidFromFullTransactionId(x)
Definition: transam.h:48
static bool TransactionIdInRecentPast(TransactionId xid, uint32 epoch)
Definition: walsender.c:2017
static LagTracker * lag_tracker
Definition: walsender.c:219
TimeLineID timeline
Definition: replnodes.h:98
ReplicationKind kind
Definition: replnodes.h:56
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool IsTransactionBlock(void)
Definition: xact.c:4683
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
WALOpenSegment seg
Definition: xlogreader.h:243
const char * SnapBuildExportSnapshot(SnapBuild *builder)
Definition: snapbuild.c:613
bool am_walsender
Definition: walsender.c:115
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
void HandleWalSndInitStopping(void)
Definition: walsender.c:3004
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
void ReplicationSlotReserveWal(void)
Definition: slot.c:1091
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:261
XLogRecPtr flush
bool defGetBoolean(DefElem *def)
Definition: define.c:111
char data[BLCKSZ]
Definition: c.h:1141
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:575
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:839
ReplicationKind kind
Definition: replnodes.h:83
void WalSndRqstFileReload(void)
Definition: walsender.c:2981
void pfree(void *pointer)
Definition: mcxt.c:1169
void ConditionVariableCancelSleep(void)
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
static void WalSndKeepalive(bool requestReply)
Definition: walsender.c:3460
void end_tup_output(TupOutputState *tstate)
Definition: execTuples.c:2314
void TupleDescInitBuiltinEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:658
#define ERROR
Definition: elog.h:46
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:106
static TimestampTz last_processing
Definition: walsender.c:162
void pq_startmsgread(void)
Definition: pqcomm.c:1150
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2423
static void PhysicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: walsender.c:1831
#define IntervalPGetDatum(X)
Definition: timestamp.h:33
#define SYNC_REP_WAIT_APPLY
Definition: syncrep.h:26
void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
Definition: xlog.c:3976
bool FirstSnapshotSet
Definition: snapmgr.c:149
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:166
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
void WalSndSignals(void)
Definition: walsender.c:3038
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
#define FATAL
Definition: elog.h:49
void SendBaseBackup(BaseBackupCmd *cmd)
Definition: basebackup.c:932
Latch * latch
void(* WalSndSendDataCallback)(void)
Definition: walsender.c:225
uint32 events
Definition: latch.h:145
#define MAXPGPATH
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11728
TupOutputState * begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2236
void ReplicationSlotPersist(void)
Definition: slot.c:767
TransactionId effective_xmin
Definition: slot.h:152
int pq_getbyte_if_available(unsigned char *c)
Definition: pqcomm.c:1032
static bool logical_read_xlog_page(XLogReaderState *state)
Definition: walsender.c:807
static LogicalDecodingContext * logical_decoding_ctx
Definition: walsender.c:197
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
TransactionId xmin
Definition: proc.h:138
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
#define DEBUG2
Definition: elog.h:24
bool XLogBackgroundFlush(void)
Definition: xlog.c:3070
Definition: latch.h:110
bool message_level_is_interesting(int elevel)
Definition: elog.c:270
Definition: dest.h:89
#define TLHistoryFileName(fname, tli)
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
WalSndState state
NodeTag type
Definition: nodes.h:541
static char * buf
Definition: pg_test_fsync.c:68
void WalSndWaitStopping(void)
Definition: walsender.c:3172
XLogRecPtr readPagePtr
Definition: xlogreader.h:187
static bool streamingDoneSending
Definition: walsender.c:179
uint64 XLogSegNo
Definition: xlogdefs.h:48
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define COMMERROR
Definition: elog.h:30
int errcode_for_file_access(void)
Definition: elog.c:721
static void StartReplication(StartReplicationCmd *cmd)
Definition: walsender.c:571
#define SIGHUP
Definition: win32_port.h:159
TransactionId catalog_xmin
Definition: slot.h:78
#define pq_flush_if_writable()
Definition: libpq.h:38
TimeOffset time
Definition: timestamp.h:45
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
XLogRecPtr currTLIValidUntil
Definition: xlogreader.h:264
#define InvalidTransactionId
Definition: transam.h:31
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:252
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
static void WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write)
Definition: walsender.c:1258
unsigned int uint32
Definition: c.h:441
void ReplicationSlotRelease(void)
Definition: slot.c:497
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
TransactionId xmin
Definition: slot.h:70
SHM_QUEUE SyncRepQueue[NUM_SYNC_REP_WAIT_MODE]
void InitWalSender(void)
static volatile sig_atomic_t got_SIGUSR2
Definition: walsender.c:186
#define SlotIsLogical(slot)
Definition: slot.h:178
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1700
static XLogReaderState * xlogreader
Definition: walsender.c:137
void SyncRepInitConfig(void)
Definition: syncrep.c:412
void EndReplicationCommand(const char *commandTag)
Definition: dest.c:221
static bool WalSndCaughtUp
Definition: walsender.c:183
#define SYNC_REP_WAIT_FLUSH
Definition: syncrep.h:25
MemoryContext TopMemoryContext
Definition: mcxt.c:48
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static void LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time)
Definition: walsender.c:3521
XLogRecPtr lsn
Definition: walsender.c:202
int replication_yyparse(void)
FullTransactionId ReadNextFullTransactionId(void)
Definition: varsup.c:261
Definition: guc.h:72
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:261
XLogRecPtr last_lsn
Definition: walsender.c:212
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
int32 month
Definition: timestamp.h:48
int max_wal_senders
Definition: walsender.c:121
static void WalSndLoop(WalSndSendDataCallback send_data)
Definition: walsender.c:2243
static void WalSndKeepaliveIfNecessary(void)
Definition: walsender.c:3483
int CloseTransientFile(int fd)
Definition: fd.c:2600
#define SIG_IGN
Definition: win32_port.h:156
static void WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write)
Definition: walsender.c:1231
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
const char * debug_query_string
Definition: postgres.c:89
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1212
static StringInfoData reply_message
Definition: walsender.c:158
#define MAXFNAMELEN
TimeLineID nextTLI
Definition: xlogreader.h:270
#define SpinLockRelease(lock)
Definition: spin.h:64
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int64 TimeOffset
Definition: timestamp.h:40
static XLogRecPtr WalSndWaitForWal(XLogRecPtr loc)
Definition: walsender.c:1368
static void WalSndCheckTimeOut(void)
Definition: walsender.c:2216
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
#define InvalidBackendId
Definition: backendid.h:23
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
static TimeOffset LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now)
Definition: walsender.c:3586
void WalSndErrorCleanup(void)
Definition: walsender.c:296
static volatile sig_atomic_t replication_active
Definition: walsender.c:195
uintptr_t Datum
Definition: postgres.h:411
static const char * WalSndGetStateString(WalSndState state)
Definition: walsender.c:3229
XLogRecPtr sentPtr
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
bool am_db_walsender
Definition: walsender.c:118
TransactionId effective_catalog_xmin
Definition: slot.h:153
static void StartLogicalReplication(StartReplicationCmd *cmd)
Definition: walsender.c:1132
Oid MyDatabaseId
Definition: globals.c:88
static void WalSndShutdown(void)
Definition: walsender.c:229
static TimeLineID receiveTLI
Definition: xlog.c:218
int work_mem
Definition: globals.c:124
XLogRecPtr tliSwitchPoint(TimeLineID tli, List *history, TimeLineID *nextTLI)
Definition: timeline.c:580
void WalSndResourceCleanup(bool isCommit)
Definition: walsender.c:331
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
WalSnd * MyWalSnd
Definition: walsender.c:112
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
static XLogRecPtr sentPtr
Definition: walsender.c:154
void pq_endmsgread(void)
Definition: pqcomm.c:1174
#define InvalidOid
Definition: postgres_ext.h:36
static void WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: walsender.c:2447
TimeLineID ThisTimeLineID
Definition: xlog.c:196
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:157
int allowedModes
Definition: execnodes.h:305
void WalSndInitStopping(void)
Definition: walsender.c:3146
TimeLineID currTLI
Definition: xlogreader.h:254
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4869
TimeOffset applyLag
struct SnapBuild * snapshot_builder
Definition: logical.h:46
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
bool WALRead(XLogReaderState *state, WALSegmentOpenCB segopenfn, WALSegmentCloseCB segclosefn, char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALReadError *errinfo)
Definition: xlogreader.c:1665
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
static long WalSndComputeSleeptime(TimestampTz now)
Definition: walsender.c:2172
#define SIG_DFL
Definition: win32_port.h:154
#define SIGNAL_ARGS
Definition: c.h:1333
static TimeLineID sendTimeLine
Definition: walsender.c:145
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void WalSndSetState(WalSndState state)
Definition: walsender.c:3210
int sync_standby_priority
Definition: regguts.h:317
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:486
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:624
static void XLogSendLogical(void)
Definition: walsender.c:2826
XLogRecPtr restart_lsn
Definition: slot.h:81
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
int read_heads[NUM_SYNC_REP_WAIT_MODE]
Definition: walsender.c:215
void StartTransactionCommand(void)
Definition: xact.c:2838
bool needreload
static void ProcessStandbyReplyMessage(void)
Definition: walsender.c:1863
size_t Size
Definition: c.h:540
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
char * dbname
Definition: streamutil.c:51
#define LAG_TRACKER_BUFFER_SIZE
Definition: walsender.c:207
int XactIsoLevel
Definition: xact.c:75
static TimeLineID sendTimeLineNextTLI
Definition: walsender.c:146
static XLogRecPtr sendTimeLineValidUpto
Definition: walsender.c:148
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1676
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
XLogRecPtr GetWalRcvFlushRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
WalSndState
Datum pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
Definition: walsender.c:3264
TimeLineID ws_tli
Definition: xlogreader.h:49
static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
Definition: walsender.c:920
static bool streamingDoneReceiving
Definition: walsender.c:180
Tuplestorestate * setResult
Definition: execnodes.h:310
static StringInfoData tmpbuf
Definition: walsender.c:159
int BasicOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1033
#define XLogFilePath(path, tli, logSegNo, wal_segsz_bytes)
int SyncRepGetCandidateStandbys(SyncRepStandbyData **standbys)
Definition: syncrep.c:726
bool IsSubTransaction(void)
Definition: xact.c:4756
Snapshot SnapBuildInitialSnapshot(SnapBuild *builder)
Definition: snapbuild.c:521
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define PG_STAT_GET_WAL_SENDERS_COLS
ExprContext * econtext
Definition: execnodes.h:303
bool log_replication_commands
Definition: walsender.c:125
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4965
#define Int32GetDatum(X)
Definition: postgres.h:523
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:591
char * application_name
Definition: guc.c:590
TupleDesc setDesc
Definition: execnodes.h:311
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:125
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
XLogReaderState * reader
Definition: logical.h:43
void pgstat_report_activity(BackendState state, const char *cmd_str)
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
int ReplicationSlotAcquire(const char *name, SlotAcquireBehavior behavior)
Definition: slot.c:388
#define pq_putmessage_noblock(msgtype, s, len)
Definition: libpq.h:42
CRSSnapshotAction
Definition: walsender.h:20
#define elog(elevel,...)
Definition: elog.h:232
StringInfo out
Definition: logical.h:73
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
void WalSndShmemInit(void)
Definition: walsender.c:3069
Definition: slot.h:43
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:455
#define NameStr(name)
Definition: c.h:681
TimeLineID timeline
Definition: replnodes.h:85
#define CStringGetTextDatum(s)
Definition: builtins.h:82
LogicalDecodingXLogPageReadCB page_read
Definition: logical.h:44
void * arg
static void PhysicalReplicationSlotNewXmin(TransactionId feedbackXmin, TransactionId feedbackCatalogXmin)
Definition: walsender.c:1968
struct Latch * MyLatch
Definition: globals.c:57
void ReplicationSlotCleanup(void)
Definition: slot.c:553
WALSegmentContext segcxt
Definition: xlogreader.h:242
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
char * defname
Definition: parsenodes.h:746
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
static XLogRecPtr GetStandbyFlushRecPtr(void)
Definition: walsender.c:2951
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
TimestampTz replyTime
void LWLockReleaseAll(void)
Definition: lwlock.c:1903
#define NUM_SYNC_REP_WAIT_MODE
Definition: syncrep.h:28
static Interval * offset_to_interval(TimeOffset offset)
Definition: walsender.c:3248
slock_t mutex
Definition: slot.h:129
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
LogicalDecodingContext * CreateInitDecodingContext(const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, LogicalDecodingXLogPageReadCB page_read, WALSegmentCleanupCB cleanup_cb, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:320
CommandDest whereToSendOutput
Definition: postgres.c:92
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
static bool waiting_for_ping_response
Definition: walsender.c:171
XLogRecPtr apply
static void IdentifySystem(void)
Definition: walsender.c:376
Definition: pg_list.h:50
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:103
#define snprintf
Definition: port.h:216
int16 AttrNumber
Definition: attnum.h:21
#define UINT64_FORMAT
Definition: c.h:484
void replication_scanner_finish(void)
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:789
static void XLogReaderSetInputData(XLogReaderState *state, int32 len)
Definition: xlogreader.h:304
void SyncRepReleaseWaiters(void)
Definition: syncrep.c:441
static TimestampTz last_reply_timestamp
Definition: walsender.c:168
static void ProcessRepliesIfAny(void)
Definition: walsender.c:1704
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
#define MAX_SEND_SIZE
Definition: walsender.c:106
#define die(msg)
Definition: pg_test_fsync.c:97
#define read(a, b, c)
Definition: win32.h:13
static bool sendTimeLineIsHistoric
Definition: walsender.c:147
#define offsetof(type, field)
Definition: c.h:727
void WalSndWakeup(void)
Definition: walsender.c:3101
void ReplicationSlotMarkDirty(void)
Definition: slot.c:750
bool am_cascading_walsender
Definition: walsender.c:116
static void ProcessStandbyHSFeedbackMessage(void)
Definition: walsender.c:2048
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1693
#define SYNC_REP_WAIT_WRITE
Definition: syncrep.h:24
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1308
void SnapBuildClearExportedSnapshot(void)
Definition: snapbuild.c:674
static XLogRecPtr startptr
Definition: basebackup.c:116
static void WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid)
Definition: walsender.c:1342
void replication_scanner_init(const char *query_string)
#define TLHistoryFilePath(path, tli)
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1774
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)