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