PostgreSQL Source Code  git master
walreceiver.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * walreceiver.c
4  *
5  * The WAL receiver process (walreceiver) is new as of Postgres 9.0. It
6  * is the process in the standby server that takes charge of receiving
7  * XLOG records from a primary server during streaming replication.
8  *
9  * When the startup process determines that it's time to start streaming,
10  * it instructs postmaster to start walreceiver. Walreceiver first connects
11  * to the primary server (it will be served by a walsender process
12  * in the primary server), and then keeps receiving XLOG records and
13  * writing them to the disk as long as the connection is alive. As XLOG
14  * records are received and flushed to disk, it updates the
15  * WalRcv->flushedUpto variable in shared memory, to inform the startup
16  * process of how far it can proceed with XLOG replay.
17  *
18  * A WAL receiver cannot directly load GUC parameters used when establishing
19  * its connection to the primary. Instead it relies on parameter values
20  * that are passed down by the startup process when streaming is requested.
21  * This applies, for example, to the replication slot and the connection
22  * string to be used for the connection with the primary.
23  *
24  * If the primary server ends streaming, but doesn't disconnect, walreceiver
25  * goes into "waiting" mode, and waits for the startup process to give new
26  * instructions. The startup process will treat that the same as
27  * disconnection, and will rescan the archive/pg_wal directory. But when the
28  * startup process wants to try streaming replication again, it will just
29  * nudge the existing walreceiver process that's waiting, instead of launching
30  * a new one.
31  *
32  * Normal termination is by SIGTERM, which instructs the walreceiver to
33  * exit(0). Emergency termination is by SIGQUIT; like any postmaster child
34  * process, the walreceiver will simply abort and exit on SIGQUIT. A close
35  * of the connection and a FATAL error are treated not as a crash but as
36  * normal operation.
37  *
38  * This file contains the server-facing parts of walreceiver. The libpq-
39  * specific parts are in the libpqwalreceiver module. It's loaded
40  * dynamically to avoid linking the server with libpq.
41  *
42  * Portions Copyright (c) 2010-2020, PostgreSQL Global Development Group
43  *
44  *
45  * IDENTIFICATION
46  * src/backend/replication/walreceiver.c
47  *
48  *-------------------------------------------------------------------------
49  */
50 #include "postgres.h"
51 
52 #include <unistd.h>
53 
54 #include "access/htup_details.h"
55 #include "access/timeline.h"
56 #include "access/transam.h"
57 #include "access/xlog_internal.h"
58 #include "access/xlogarchive.h"
59 #include "catalog/pg_authid.h"
60 #include "catalog/pg_type.h"
61 #include "common/ip.h"
62 #include "funcapi.h"
63 #include "libpq/pqformat.h"
64 #include "libpq/pqsignal.h"
65 #include "miscadmin.h"
66 #include "pgstat.h"
67 #include "postmaster/interrupt.h"
69 #include "replication/walsender.h"
70 #include "storage/ipc.h"
71 #include "storage/pmsignal.h"
72 #include "storage/procarray.h"
73 #include "storage/procsignal.h"
74 #include "utils/acl.h"
75 #include "utils/builtins.h"
76 #include "utils/guc.h"
77 #include "utils/pg_lsn.h"
78 #include "utils/ps_status.h"
79 #include "utils/resowner.h"
80 #include "utils/timestamp.h"
81 
82 
83 /*
84  * GUC variables. (Other variables that affect walreceiver are in xlog.c
85  * because they're passed down from the startup process, for better
86  * synchronization.)
87  */
91 
92 /* libpqwalreceiver connection */
93 static WalReceiverConn *wrconn = NULL;
95 
96 #define NAPTIME_PER_CYCLE 100 /* max sleep time between cycles (100ms) */
97 
98 /*
99  * These variables are used similarly to openLogFile/SegNo,
100  * but for walreceiver to write the XLOG. recvFileTLI is the TimeLineID
101  * corresponding the filename of recvFile.
102  */
103 static int recvFile = -1;
105 static XLogSegNo recvSegNo = 0;
106 
107 /*
108  * Flags set by interrupt handlers of walreceiver for later service in the
109  * main loop.
110  */
111 static volatile sig_atomic_t got_SIGHUP = false;
112 static volatile sig_atomic_t got_SIGTERM = false;
113 
114 /*
115  * LogstreamResult indicates the byte positions that we have already
116  * written/fsynced.
117  */
118 static struct
119 {
120  XLogRecPtr Write; /* last byte + 1 written out in the standby */
121  XLogRecPtr Flush; /* last byte + 1 flushed in the standby */
123 
126 
127 /* Prototypes for private functions */
128 static void WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last);
129 static void WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI);
130 static void WalRcvDie(int code, Datum arg);
131 static void XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len);
132 static void XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr);
133 static void XLogWalRcvFlush(bool dying);
134 static void XLogWalRcvSendReply(bool force, bool requestReply);
135 static void XLogWalRcvSendHSFeedback(bool immed);
136 static void ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime);
137 
138 /* Signal handlers */
139 static void WalRcvSigHupHandler(SIGNAL_ARGS);
141 
142 
143 /*
144  * Process any interrupts the walreceiver process may have received.
145  * This should be called any time the process's latch has become set.
146  *
147  * Currently, only SIGTERM is of interest. We can't just exit(1) within the
148  * SIGTERM signal handler, because the signal might arrive in the middle of
149  * some critical operation, like while we're holding a spinlock. Instead, the
150  * signal handler sets a flag variable as well as setting the process's latch.
151  * We must check the flag (by calling ProcessWalRcvInterrupts) anytime the
152  * latch has become set. Operations that could block for a long time, such as
153  * reading from a remote server, must pay attention to the latch too; see
154  * libpqrcv_PQgetResult for example.
155  */
156 void
158 {
159  /*
160  * Although walreceiver interrupt handling doesn't use the same scheme as
161  * regular backends, call CHECK_FOR_INTERRUPTS() to make sure we receive
162  * any incoming signals on Win32, and also to make sure we process any
163  * barrier events.
164  */
166 
167  if (got_SIGTERM)
168  {
169  ereport(FATAL,
170  (errcode(ERRCODE_ADMIN_SHUTDOWN),
171  errmsg("terminating walreceiver process due to administrator command")));
172  }
173 }
174 
175 
176 /* Main entry point for walreceiver process */
177 void
179 {
180  char conninfo[MAXCONNINFO];
181  char *tmp_conninfo;
182  char slotname[NAMEDATALEN];
183  bool is_temp_slot;
184  XLogRecPtr startpoint;
185  TimeLineID startpointTLI;
186  TimeLineID primaryTLI;
187  bool first_stream;
188  WalRcvData *walrcv = WalRcv;
189  TimestampTz last_recv_timestamp;
191  bool ping_sent;
192  char *err;
193  char *sender_host = NULL;
194  int sender_port = 0;
195 
196  /*
197  * WalRcv should be set up already (if we are a backend, we inherit this
198  * by fork() or EXEC_BACKEND mechanism from the postmaster).
199  */
200  Assert(walrcv != NULL);
201 
202  now = GetCurrentTimestamp();
203 
204  /*
205  * Mark walreceiver as running in shared memory.
206  *
207  * Do this as early as possible, so that if we fail later on, we'll set
208  * state to STOPPED. If we die before this, the startup process will keep
209  * waiting for us to start up, until it times out.
210  */
211  SpinLockAcquire(&walrcv->mutex);
212  Assert(walrcv->pid == 0);
213  switch (walrcv->walRcvState)
214  {
215  case WALRCV_STOPPING:
216  /* If we've already been requested to stop, don't start up. */
217  walrcv->walRcvState = WALRCV_STOPPED;
218  /* fall through */
219 
220  case WALRCV_STOPPED:
221  SpinLockRelease(&walrcv->mutex);
222  proc_exit(1);
223  break;
224 
225  case WALRCV_STARTING:
226  /* The usual case */
227  break;
228 
229  case WALRCV_WAITING:
230  case WALRCV_STREAMING:
231  case WALRCV_RESTARTING:
232  default:
233  /* Shouldn't happen */
234  SpinLockRelease(&walrcv->mutex);
235  elog(PANIC, "walreceiver still running according to shared memory state");
236  }
237  /* Advertise our PID so that the startup process can kill us */
238  walrcv->pid = MyProcPid;
239  walrcv->walRcvState = WALRCV_STREAMING;
240 
241  /* Fetch information required to start streaming */
242  walrcv->ready_to_display = false;
243  strlcpy(conninfo, (char *) walrcv->conninfo, MAXCONNINFO);
244  strlcpy(slotname, (char *) walrcv->slotname, NAMEDATALEN);
245  is_temp_slot = walrcv->is_temp_slot;
246  startpoint = walrcv->receiveStart;
247  startpointTLI = walrcv->receiveStartTLI;
248 
249  /*
250  * At most one of is_temp_slot and slotname can be set; otherwise,
251  * RequestXLogStreaming messed up.
252  */
253  Assert(!is_temp_slot || (slotname[0] == '\0'));
254 
255  /* Initialise to a sanish value */
256  walrcv->lastMsgSendTime =
257  walrcv->lastMsgReceiptTime = walrcv->latestWalEndTime = now;
258 
259  /* Report the latch to use to awaken this process */
260  walrcv->latch = &MyProc->procLatch;
261 
262  SpinLockRelease(&walrcv->mutex);
263 
265 
266  /* Arrange to clean up at walreceiver exit */
268 
269  /* Properly accept or ignore signals the postmaster might send us */
270  pqsignal(SIGHUP, WalRcvSigHupHandler); /* set flag to read config file */
271  pqsignal(SIGINT, SIG_IGN);
272  pqsignal(SIGTERM, WalRcvShutdownHandler); /* request shutdown */
273  /* SIGQUIT handler was already set up by InitPostmasterChild */
278 
279  /* Reset some signals that are accepted by postmaster but not here */
281 
282  /* Load the libpq-specific functions */
283  load_file("libpqwalreceiver", false);
284  if (WalReceiverFunctions == NULL)
285  elog(ERROR, "libpqwalreceiver didn't initialize correctly");
286 
287  /* Unblock signals (they were blocked when the postmaster forked us) */
289 
290  /* Establish the connection to the primary for XLOG streaming */
291  wrconn = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
292  if (!wrconn)
293  ereport(ERROR,
294  (errmsg("could not connect to the primary server: %s", err)));
295 
296  /*
297  * Save user-visible connection string. This clobbers the original
298  * conninfo, for security. Also save host and port of the sender server
299  * this walreceiver is connected to.
300  */
301  tmp_conninfo = walrcv_get_conninfo(wrconn);
302  walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
303  SpinLockAcquire(&walrcv->mutex);
304  memset(walrcv->conninfo, 0, MAXCONNINFO);
305  if (tmp_conninfo)
306  strlcpy((char *) walrcv->conninfo, tmp_conninfo, MAXCONNINFO);
307 
308  memset(walrcv->sender_host, 0, NI_MAXHOST);
309  if (sender_host)
310  strlcpy((char *) walrcv->sender_host, sender_host, NI_MAXHOST);
311 
312  walrcv->sender_port = sender_port;
313  walrcv->ready_to_display = true;
314  SpinLockRelease(&walrcv->mutex);
315 
316  if (tmp_conninfo)
317  pfree(tmp_conninfo);
318 
319  if (sender_host)
320  pfree(sender_host);
321 
322  first_stream = true;
323  for (;;)
324  {
325  char *primary_sysid;
326  char standby_sysid[32];
328 
329  /*
330  * Check that we're connected to a valid server using the
331  * IDENTIFY_SYSTEM replication command.
332  */
333  primary_sysid = walrcv_identify_system(wrconn, &primaryTLI);
334 
335  snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
337  if (strcmp(primary_sysid, standby_sysid) != 0)
338  {
339  ereport(ERROR,
340  (errmsg("database system identifier differs between the primary and standby"),
341  errdetail("The primary's identifier is %s, the standby's identifier is %s.",
342  primary_sysid, standby_sysid)));
343  }
344 
345  /*
346  * Confirm that the current timeline of the primary is the same or
347  * ahead of ours.
348  */
349  if (primaryTLI < startpointTLI)
350  ereport(ERROR,
351  (errmsg("highest timeline %u of the primary is behind recovery timeline %u",
352  primaryTLI, startpointTLI)));
353 
354  /*
355  * Get any missing history files. We do this always, even when we're
356  * not interested in that timeline, so that if we're promoted to
357  * become the primary later on, we don't select the same timeline that
358  * was already used in the current primary. This isn't bullet-proof -
359  * you'll need some external software to manage your cluster if you
360  * need to ensure that a unique timeline id is chosen in every case,
361  * but let's avoid the confusion of timeline id collisions where we
362  * can.
363  */
364  WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
365 
366  /*
367  * Create temporary replication slot if requested, and update slot
368  * name in shared memory. (Note the slot name cannot already be set
369  * in this case.)
370  */
371  if (is_temp_slot)
372  {
373  snprintf(slotname, sizeof(slotname),
374  "pg_walreceiver_%lld",
375  (long long int) walrcv_get_backend_pid(wrconn));
376 
377  walrcv_create_slot(wrconn, slotname, true, 0, NULL);
378 
379  SpinLockAcquire(&walrcv->mutex);
380  strlcpy(walrcv->slotname, slotname, NAMEDATALEN);
381  SpinLockRelease(&walrcv->mutex);
382  }
383 
384  /*
385  * Start streaming.
386  *
387  * We'll try to start at the requested starting point and timeline,
388  * even if it's different from the server's latest timeline. In case
389  * we've already reached the end of the old timeline, the server will
390  * finish the streaming immediately, and we will go back to await
391  * orders from the startup process. If recovery_target_timeline is
392  * 'latest', the startup process will scan pg_wal and find the new
393  * history file, bump recovery target timeline, and ask us to restart
394  * on the new timeline.
395  */
396  options.logical = false;
397  options.startpoint = startpoint;
398  options.slotname = slotname[0] != '\0' ? slotname : NULL;
399  options.proto.physical.startpointTLI = startpointTLI;
400  ThisTimeLineID = startpointTLI;
401  if (walrcv_startstreaming(wrconn, &options))
402  {
403  if (first_stream)
404  ereport(LOG,
405  (errmsg("started streaming WAL from primary at %X/%X on timeline %u",
406  (uint32) (startpoint >> 32), (uint32) startpoint,
407  startpointTLI)));
408  else
409  ereport(LOG,
410  (errmsg("restarted WAL streaming at %X/%X on timeline %u",
411  (uint32) (startpoint >> 32), (uint32) startpoint,
412  startpointTLI)));
413  first_stream = false;
414 
415  /* Initialize LogstreamResult and buffers for processing messages */
417  initStringInfo(&reply_message);
418  initStringInfo(&incoming_message);
419 
420  /* Initialize the last recv timestamp */
421  last_recv_timestamp = GetCurrentTimestamp();
422  ping_sent = false;
423 
424  /* Loop until end-of-streaming or error */
425  for (;;)
426  {
427  char *buf;
428  int len;
429  bool endofwal = false;
430  pgsocket wait_fd = PGINVALID_SOCKET;
431  int rc;
432 
433  /*
434  * Exit walreceiver if we're not in recovery. This should not
435  * happen, but cross-check the status here.
436  */
437  if (!RecoveryInProgress())
438  ereport(FATAL,
439  (errmsg("cannot continue WAL streaming, recovery has already ended")));
440 
441  /* Process any requests or signals received recently */
443 
444  if (got_SIGHUP)
445  {
446  got_SIGHUP = false;
449  }
450 
451  /* See if we can read data immediately */
452  len = walrcv_receive(wrconn, &buf, &wait_fd);
453  if (len != 0)
454  {
455  /*
456  * Process the received data, and any subsequent data we
457  * can read without blocking.
458  */
459  for (;;)
460  {
461  if (len > 0)
462  {
463  /*
464  * Something was received from primary, so reset
465  * timeout
466  */
467  last_recv_timestamp = GetCurrentTimestamp();
468  ping_sent = false;
469  XLogWalRcvProcessMsg(buf[0], &buf[1], len - 1);
470  }
471  else if (len == 0)
472  break;
473  else if (len < 0)
474  {
475  ereport(LOG,
476  (errmsg("replication terminated by primary server"),
477  errdetail("End of WAL reached on timeline %u at %X/%X.",
478  startpointTLI,
479  (uint32) (LogstreamResult.Write >> 32), (uint32) LogstreamResult.Write)));
480  endofwal = true;
481  break;
482  }
483  len = walrcv_receive(wrconn, &buf, &wait_fd);
484  }
485 
486  /* Let the primary know that we received some data. */
487  XLogWalRcvSendReply(false, false);
488 
489  /*
490  * If we've written some records, flush them to disk and
491  * let the startup process and primary server know about
492  * them.
493  */
494  XLogWalRcvFlush(false);
495  }
496 
497  /* Check if we need to exit the streaming loop. */
498  if (endofwal)
499  break;
500 
501  /*
502  * Ideally we would reuse a WaitEventSet object repeatedly
503  * here to avoid the overheads of WaitLatchOrSocket on epoll
504  * systems, but we can't be sure that libpq (or any other
505  * walreceiver implementation) has the same socket (even if
506  * the fd is the same number, it may have been closed and
507  * reopened since the last time). In future, if there is a
508  * function for removing sockets from WaitEventSet, then we
509  * could add and remove just the socket each time, potentially
510  * avoiding some system calls.
511  */
512  Assert(wait_fd != PGINVALID_SOCKET);
513  rc = WaitLatchOrSocket(walrcv->latch,
516  wait_fd,
519  if (rc & WL_LATCH_SET)
520  {
521  ResetLatch(walrcv->latch);
523 
524  if (walrcv->force_reply)
525  {
526  /*
527  * The recovery process has asked us to send apply
528  * feedback now. Make sure the flag is really set to
529  * false in shared memory before sending the reply, so
530  * we don't miss a new request for a reply.
531  */
532  walrcv->force_reply = false;
534  XLogWalRcvSendReply(true, false);
535  }
536  }
537  if (rc & WL_TIMEOUT)
538  {
539  /*
540  * We didn't receive anything new. If we haven't heard
541  * anything from the server for more than
542  * wal_receiver_timeout / 2, ping the server. Also, if
543  * it's been longer than wal_receiver_status_interval
544  * since the last update we sent, send a status update to
545  * the primary anyway, to report any progress in applying
546  * WAL.
547  */
548  bool requestReply = false;
549 
550  /*
551  * Check if time since last receive from standby has
552  * reached the configured limit.
553  */
554  if (wal_receiver_timeout > 0)
555  {
557  TimestampTz timeout;
558 
559  timeout =
560  TimestampTzPlusMilliseconds(last_recv_timestamp,
562 
563  if (now >= timeout)
564  ereport(ERROR,
565  (errmsg("terminating walreceiver due to timeout")));
566 
567  /*
568  * We didn't receive anything new, for half of
569  * receiver replication timeout. Ping the server.
570  */
571  if (!ping_sent)
572  {
573  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
574  (wal_receiver_timeout / 2));
575  if (now >= timeout)
576  {
577  requestReply = true;
578  ping_sent = true;
579  }
580  }
581  }
582 
583  XLogWalRcvSendReply(requestReply, requestReply);
585  }
586  }
587 
588  /*
589  * The backend finished streaming. Exit streaming COPY-mode from
590  * our side, too.
591  */
592  walrcv_endstreaming(wrconn, &primaryTLI);
593 
594  /*
595  * If the server had switched to a new timeline that we didn't
596  * know about when we began streaming, fetch its timeline history
597  * file now.
598  */
599  WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
600  }
601  else
602  ereport(LOG,
603  (errmsg("primary server contains no more WAL on requested timeline %u",
604  startpointTLI)));
605 
606  /*
607  * End of WAL reached on the requested timeline. Close the last
608  * segment, and await for new orders from the startup process.
609  */
610  if (recvFile >= 0)
611  {
612  char xlogfname[MAXFNAMELEN];
613 
614  XLogWalRcvFlush(false);
616  if (close(recvFile) != 0)
617  ereport(PANIC,
619  errmsg("could not close log segment %s: %m",
620  xlogfname)));
621 
622  /*
623  * Create .done file forcibly to prevent the streamed segment from
624  * being archived later.
625  */
627  XLogArchiveForceDone(xlogfname);
628  else
629  XLogArchiveNotify(xlogfname);
630  }
631  recvFile = -1;
632 
633  elog(DEBUG1, "walreceiver ended streaming and awaits new instructions");
634  WalRcvWaitForStartPosition(&startpoint, &startpointTLI);
635  }
636  /* not reached */
637 }
638 
639 /*
640  * Wait for startup process to set receiveStart and receiveStartTLI.
641  */
642 static void
644 {
645  WalRcvData *walrcv = WalRcv;
646  int state;
647 
648  SpinLockAcquire(&walrcv->mutex);
649  state = walrcv->walRcvState;
650  if (state != WALRCV_STREAMING)
651  {
652  SpinLockRelease(&walrcv->mutex);
653  if (state == WALRCV_STOPPING)
654  proc_exit(0);
655  else
656  elog(FATAL, "unexpected walreceiver state");
657  }
658  walrcv->walRcvState = WALRCV_WAITING;
660  walrcv->receiveStartTLI = 0;
661  SpinLockRelease(&walrcv->mutex);
662 
663  set_ps_display("idle");
664 
665  /*
666  * nudge startup process to notice that we've stopped streaming and are
667  * now waiting for instructions.
668  */
669  WakeupRecovery();
670  for (;;)
671  {
672  ResetLatch(walrcv->latch);
673 
675 
676  SpinLockAcquire(&walrcv->mutex);
677  Assert(walrcv->walRcvState == WALRCV_RESTARTING ||
678  walrcv->walRcvState == WALRCV_WAITING ||
679  walrcv->walRcvState == WALRCV_STOPPING);
680  if (walrcv->walRcvState == WALRCV_RESTARTING)
681  {
682  /*
683  * No need to handle changes in primary_conninfo or
684  * primary_slotname here. Startup process will signal us to
685  * terminate in case those change.
686  */
687  *startpoint = walrcv->receiveStart;
688  *startpointTLI = walrcv->receiveStartTLI;
689  walrcv->walRcvState = WALRCV_STREAMING;
690  SpinLockRelease(&walrcv->mutex);
691  break;
692  }
693  if (walrcv->walRcvState == WALRCV_STOPPING)
694  {
695  /*
696  * We should've received SIGTERM if the startup process wants us
697  * to die, but might as well check it here too.
698  */
699  SpinLockRelease(&walrcv->mutex);
700  exit(1);
701  }
702  SpinLockRelease(&walrcv->mutex);
703 
704  (void) WaitLatch(walrcv->latch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
706  }
707 
709  {
710  char activitymsg[50];
711 
712  snprintf(activitymsg, sizeof(activitymsg), "restarting at %X/%X",
713  (uint32) (*startpoint >> 32),
714  (uint32) *startpoint);
715  set_ps_display(activitymsg);
716  }
717 }
718 
719 /*
720  * Fetch any missing timeline history files between 'first' and 'last'
721  * (inclusive) from the server.
722  */
723 static void
725 {
726  TimeLineID tli;
727 
728  for (tli = first; tli <= last; tli++)
729  {
730  /* there's no history file for timeline 1 */
731  if (tli != 1 && !existsTimeLineHistory(tli))
732  {
733  char *fname;
734  char *content;
735  int len;
736  char expectedfname[MAXFNAMELEN];
737 
738  ereport(LOG,
739  (errmsg("fetching timeline history file for timeline %u from primary server",
740  tli)));
741 
742  walrcv_readtimelinehistoryfile(wrconn, tli, &fname, &content, &len);
743 
744  /*
745  * Check that the filename on the primary matches what we
746  * calculated ourselves. This is just a sanity check, it should
747  * always match.
748  */
749  TLHistoryFileName(expectedfname, tli);
750  if (strcmp(fname, expectedfname) != 0)
751  ereport(ERROR,
752  (errcode(ERRCODE_PROTOCOL_VIOLATION),
753  errmsg_internal("primary reported unexpected file name for timeline history file of timeline %u",
754  tli)));
755 
756  /*
757  * Write the file to pg_wal.
758  */
759  writeTimeLineHistoryFile(tli, content, len);
760 
761  pfree(fname);
762  pfree(content);
763  }
764  }
765 }
766 
767 /*
768  * Mark us as STOPPED in shared memory at exit.
769  */
770 static void
771 WalRcvDie(int code, Datum arg)
772 {
773  WalRcvData *walrcv = WalRcv;
774 
775  /* Ensure that all WAL records received are flushed to disk */
776  XLogWalRcvFlush(true);
777 
778  /* Mark ourselves inactive in shared memory */
779  SpinLockAcquire(&walrcv->mutex);
780  Assert(walrcv->walRcvState == WALRCV_STREAMING ||
781  walrcv->walRcvState == WALRCV_RESTARTING ||
782  walrcv->walRcvState == WALRCV_STARTING ||
783  walrcv->walRcvState == WALRCV_WAITING ||
784  walrcv->walRcvState == WALRCV_STOPPING);
785  Assert(walrcv->pid == MyProcPid);
786  walrcv->walRcvState = WALRCV_STOPPED;
787  walrcv->pid = 0;
788  walrcv->ready_to_display = false;
789  walrcv->latch = NULL;
790  SpinLockRelease(&walrcv->mutex);
791 
792  /* Terminate the connection gracefully. */
793  if (wrconn != NULL)
794  walrcv_disconnect(wrconn);
795 
796  /* Wake up the startup process to notice promptly that we're gone */
797  WakeupRecovery();
798 }
799 
800 /* SIGHUP: set flag to re-read config file at next convenient time */
801 static void
803 {
804  got_SIGHUP = true;
805 }
806 
807 
808 /* SIGTERM: set flag for ProcessWalRcvInterrupts */
809 static void
811 {
812  int save_errno = errno;
813 
814  got_SIGTERM = true;
815 
816  if (WalRcv->latch)
818 
819  errno = save_errno;
820 }
821 
822 /*
823  * Accept the message from XLOG stream, and process it.
824  */
825 static void
826 XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len)
827 {
828  int hdrlen;
829  XLogRecPtr dataStart;
830  XLogRecPtr walEnd;
831  TimestampTz sendTime;
832  bool replyRequested;
833 
834  resetStringInfo(&incoming_message);
835 
836  switch (type)
837  {
838  case 'w': /* WAL records */
839  {
840  /* copy message to StringInfo */
841  hdrlen = sizeof(int64) + sizeof(int64) + sizeof(int64);
842  if (len < hdrlen)
843  ereport(ERROR,
844  (errcode(ERRCODE_PROTOCOL_VIOLATION),
845  errmsg_internal("invalid WAL message received from primary")));
846  appendBinaryStringInfo(&incoming_message, buf, hdrlen);
847 
848  /* read the fields */
849  dataStart = pq_getmsgint64(&incoming_message);
850  walEnd = pq_getmsgint64(&incoming_message);
851  sendTime = pq_getmsgint64(&incoming_message);
852  ProcessWalSndrMessage(walEnd, sendTime);
853 
854  buf += hdrlen;
855  len -= hdrlen;
856  XLogWalRcvWrite(buf, len, dataStart);
857  break;
858  }
859  case 'k': /* Keepalive */
860  {
861  /* copy message to StringInfo */
862  hdrlen = sizeof(int64) + sizeof(int64) + sizeof(char);
863  if (len != hdrlen)
864  ereport(ERROR,
865  (errcode(ERRCODE_PROTOCOL_VIOLATION),
866  errmsg_internal("invalid keepalive message received from primary")));
867  appendBinaryStringInfo(&incoming_message, buf, hdrlen);
868 
869  /* read the fields */
870  walEnd = pq_getmsgint64(&incoming_message);
871  sendTime = pq_getmsgint64(&incoming_message);
872  replyRequested = pq_getmsgbyte(&incoming_message);
873 
874  ProcessWalSndrMessage(walEnd, sendTime);
875 
876  /* If the primary requested a reply, send one immediately */
877  if (replyRequested)
878  XLogWalRcvSendReply(true, false);
879  break;
880  }
881  default:
882  ereport(ERROR,
883  (errcode(ERRCODE_PROTOCOL_VIOLATION),
884  errmsg_internal("invalid replication message type %d",
885  type)));
886  }
887 }
888 
889 /*
890  * Write XLOG data to disk.
891  */
892 static void
893 XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr)
894 {
895  int startoff;
896  int byteswritten;
897 
898  while (nbytes > 0)
899  {
900  int segbytes;
901 
902  if (recvFile < 0 || !XLByteInSeg(recptr, recvSegNo, wal_segment_size))
903  {
904  bool use_existent;
905 
906  /*
907  * fsync() and close current file before we switch to next one. We
908  * would otherwise have to reopen this file to fsync it later
909  */
910  if (recvFile >= 0)
911  {
912  char xlogfname[MAXFNAMELEN];
913 
914  XLogWalRcvFlush(false);
915 
917 
918  /*
919  * XLOG segment files will be re-read by recovery in startup
920  * process soon, so we don't advise the OS to release cache
921  * pages associated with the file like XLogFileClose() does.
922  */
923  if (close(recvFile) != 0)
924  ereport(PANIC,
926  errmsg("could not close log segment %s: %m",
927  xlogfname)));
928 
929  /*
930  * Create .done file forcibly to prevent the streamed segment
931  * from being archived later.
932  */
934  XLogArchiveForceDone(xlogfname);
935  else
936  XLogArchiveNotify(xlogfname);
937  }
938  recvFile = -1;
939 
940  /* Create/use new log file */
942  use_existent = true;
943  recvFile = XLogFileInit(recvSegNo, &use_existent, true);
945  }
946 
947  /* Calculate the start offset of the received logs */
948  startoff = XLogSegmentOffset(recptr, wal_segment_size);
949 
950  if (startoff + nbytes > wal_segment_size)
951  segbytes = wal_segment_size - startoff;
952  else
953  segbytes = nbytes;
954 
955  /* OK to write the logs */
956  errno = 0;
957 
958  byteswritten = pg_pwrite(recvFile, buf, segbytes, (off_t) startoff);
959  if (byteswritten <= 0)
960  {
961  char xlogfname[MAXFNAMELEN];
962  int save_errno;
963 
964  /* if write didn't set errno, assume no disk space */
965  if (errno == 0)
966  errno = ENOSPC;
967 
968  save_errno = errno;
970  errno = save_errno;
971  ereport(PANIC,
973  errmsg("could not write to log segment %s "
974  "at offset %u, length %lu: %m",
975  xlogfname, startoff, (unsigned long) segbytes)));
976  }
977 
978  /* Update state for write */
979  recptr += byteswritten;
980 
981  nbytes -= byteswritten;
982  buf += byteswritten;
983 
984  LogstreamResult.Write = recptr;
985  }
986 
987  /* Update shared-memory status */
989 }
990 
991 /*
992  * Flush the log to disk.
993  *
994  * If we're in the midst of dying, it's unwise to do anything that might throw
995  * an error, so we skip sending a reply in that case.
996  */
997 static void
998 XLogWalRcvFlush(bool dying)
999 {
1000  if (LogstreamResult.Flush < LogstreamResult.Write)
1001  {
1002  WalRcvData *walrcv = WalRcv;
1003 
1005 
1006  LogstreamResult.Flush = LogstreamResult.Write;
1007 
1008  /* Update shared-memory status */
1009  SpinLockAcquire(&walrcv->mutex);
1010  if (walrcv->flushedUpto < LogstreamResult.Flush)
1011  {
1012  walrcv->latestChunkStart = walrcv->flushedUpto;
1013  walrcv->flushedUpto = LogstreamResult.Flush;
1014  walrcv->receivedTLI = ThisTimeLineID;
1015  }
1016  SpinLockRelease(&walrcv->mutex);
1017 
1018  /* Signal the startup process and walsender that new WAL has arrived */
1019  WakeupRecovery();
1021  WalSndWakeup();
1022 
1023  /* Report XLOG streaming progress in PS display */
1025  {
1026  char activitymsg[50];
1027 
1028  snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1029  (uint32) (LogstreamResult.Write >> 32),
1030  (uint32) LogstreamResult.Write);
1031  set_ps_display(activitymsg);
1032  }
1033 
1034  /* Also let the primary know that we made some progress */
1035  if (!dying)
1036  {
1037  XLogWalRcvSendReply(false, false);
1038  XLogWalRcvSendHSFeedback(false);
1039  }
1040  }
1041 }
1042 
1043 /*
1044  * Send reply message to primary, indicating our current WAL locations, oldest
1045  * xmin and the current time.
1046  *
1047  * If 'force' is not set, the message is only sent if enough time has
1048  * passed since last status update to reach wal_receiver_status_interval.
1049  * If wal_receiver_status_interval is disabled altogether and 'force' is
1050  * false, this is a no-op.
1051  *
1052  * If 'requestReply' is true, requests the server to reply immediately upon
1053  * receiving this message. This is used for heartbeats, when approaching
1054  * wal_receiver_timeout.
1055  */
1056 static void
1057 XLogWalRcvSendReply(bool force, bool requestReply)
1058 {
1059  static XLogRecPtr writePtr = 0;
1060  static XLogRecPtr flushPtr = 0;
1061  XLogRecPtr applyPtr;
1062  static TimestampTz sendTime = 0;
1063  TimestampTz now;
1064 
1065  /*
1066  * If the user doesn't want status to be reported to the primary, be sure
1067  * to exit before doing anything at all.
1068  */
1069  if (!force && wal_receiver_status_interval <= 0)
1070  return;
1071 
1072  /* Get current timestamp. */
1073  now = GetCurrentTimestamp();
1074 
1075  /*
1076  * We can compare the write and flush positions to the last message we
1077  * sent without taking any lock, but the apply position requires a spin
1078  * lock, so we don't check that unless something else has changed or 10
1079  * seconds have passed. This means that the apply WAL location will
1080  * appear, from the primary's point of view, to lag slightly, but since
1081  * this is only for reporting purposes and only on idle systems, that's
1082  * probably OK.
1083  */
1084  if (!force
1085  && writePtr == LogstreamResult.Write
1086  && flushPtr == LogstreamResult.Flush
1087  && !TimestampDifferenceExceeds(sendTime, now,
1089  return;
1090  sendTime = now;
1091 
1092  /* Construct a new message */
1093  writePtr = LogstreamResult.Write;
1094  flushPtr = LogstreamResult.Flush;
1095  applyPtr = GetXLogReplayRecPtr(NULL);
1096 
1097  resetStringInfo(&reply_message);
1098  pq_sendbyte(&reply_message, 'r');
1099  pq_sendint64(&reply_message, writePtr);
1100  pq_sendint64(&reply_message, flushPtr);
1101  pq_sendint64(&reply_message, applyPtr);
1102  pq_sendint64(&reply_message, GetCurrentTimestamp());
1103  pq_sendbyte(&reply_message, requestReply ? 1 : 0);
1104 
1105  /* Send it */
1106  elog(DEBUG2, "sending write %X/%X flush %X/%X apply %X/%X%s",
1107  (uint32) (writePtr >> 32), (uint32) writePtr,
1108  (uint32) (flushPtr >> 32), (uint32) flushPtr,
1109  (uint32) (applyPtr >> 32), (uint32) applyPtr,
1110  requestReply ? " (reply requested)" : "");
1111 
1112  walrcv_send(wrconn, reply_message.data, reply_message.len);
1113 }
1114 
1115 /*
1116  * Send hot standby feedback message to primary, plus the current time,
1117  * in case they don't have a watch.
1118  *
1119  * If the user disables feedback, send one final message to tell sender
1120  * to forget about the xmin on this standby. We also send this message
1121  * on first connect because a previous connection might have set xmin
1122  * on a replication slot. (If we're not using a slot it's harmless to
1123  * send a feedback message explicitly setting InvalidTransactionId).
1124  */
1125 static void
1127 {
1128  TimestampTz now;
1129  FullTransactionId nextFullXid;
1130  TransactionId nextXid;
1131  uint32 xmin_epoch,
1132  catalog_xmin_epoch;
1133  TransactionId xmin,
1134  catalog_xmin;
1135  static TimestampTz sendTime = 0;
1136 
1137  /* initially true so we always send at least one feedback message */
1138  static bool primary_has_standby_xmin = true;
1139 
1140  /*
1141  * If the user doesn't want status to be reported to the primary, be sure
1142  * to exit before doing anything at all.
1143  */
1145  !primary_has_standby_xmin)
1146  return;
1147 
1148  /* Get current timestamp. */
1149  now = GetCurrentTimestamp();
1150 
1151  if (!immed)
1152  {
1153  /*
1154  * Send feedback at most once per wal_receiver_status_interval.
1155  */
1156  if (!TimestampDifferenceExceeds(sendTime, now,
1158  return;
1159  sendTime = now;
1160  }
1161 
1162  /*
1163  * If Hot Standby is not yet accepting connections there is nothing to
1164  * send. Check this after the interval has expired to reduce number of
1165  * calls.
1166  *
1167  * Bailing out here also ensures that we don't send feedback until we've
1168  * read our own replication slot state, so we don't tell the primary to
1169  * discard needed xmin or catalog_xmin from any slots that may exist on
1170  * this replica.
1171  */
1172  if (!HotStandbyActive())
1173  return;
1174 
1175  /*
1176  * Make the expensive call to get the oldest xmin once we are certain
1177  * everything else has been checked.
1178  */
1180  {
1181  GetReplicationHorizons(&xmin, &catalog_xmin);
1182  }
1183  else
1184  {
1185  xmin = InvalidTransactionId;
1186  catalog_xmin = InvalidTransactionId;
1187  }
1188 
1189  /*
1190  * Get epoch and adjust if nextXid and oldestXmin are different sides of
1191  * the epoch boundary.
1192  */
1193  nextFullXid = ReadNextFullTransactionId();
1194  nextXid = XidFromFullTransactionId(nextFullXid);
1195  xmin_epoch = EpochFromFullTransactionId(nextFullXid);
1196  catalog_xmin_epoch = xmin_epoch;
1197  if (nextXid < xmin)
1198  xmin_epoch--;
1199  if (nextXid < catalog_xmin)
1200  catalog_xmin_epoch--;
1201 
1202  elog(DEBUG2, "sending hot standby feedback xmin %u epoch %u catalog_xmin %u catalog_xmin_epoch %u",
1203  xmin, xmin_epoch, catalog_xmin, catalog_xmin_epoch);
1204 
1205  /* Construct the message and send it. */
1206  resetStringInfo(&reply_message);
1207  pq_sendbyte(&reply_message, 'h');
1208  pq_sendint64(&reply_message, GetCurrentTimestamp());
1209  pq_sendint32(&reply_message, xmin);
1210  pq_sendint32(&reply_message, xmin_epoch);
1211  pq_sendint32(&reply_message, catalog_xmin);
1212  pq_sendint32(&reply_message, catalog_xmin_epoch);
1213  walrcv_send(wrconn, reply_message.data, reply_message.len);
1214  if (TransactionIdIsValid(xmin) || TransactionIdIsValid(catalog_xmin))
1215  primary_has_standby_xmin = true;
1216  else
1217  primary_has_standby_xmin = false;
1218 }
1219 
1220 /*
1221  * Update shared memory status upon receiving a message from primary.
1222  *
1223  * 'walEnd' and 'sendTime' are the end-of-WAL and timestamp of the latest
1224  * message, reported by primary.
1225  */
1226 static void
1228 {
1229  WalRcvData *walrcv = WalRcv;
1230 
1231  TimestampTz lastMsgReceiptTime = GetCurrentTimestamp();
1232 
1233  /* Update shared-memory status */
1234  SpinLockAcquire(&walrcv->mutex);
1235  if (walrcv->latestWalEnd < walEnd)
1236  walrcv->latestWalEndTime = sendTime;
1237  walrcv->latestWalEnd = walEnd;
1238  walrcv->lastMsgSendTime = sendTime;
1239  walrcv->lastMsgReceiptTime = lastMsgReceiptTime;
1240  SpinLockRelease(&walrcv->mutex);
1241 
1242  if (log_min_messages <= DEBUG2)
1243  {
1244  char *sendtime;
1245  char *receipttime;
1246  int applyDelay;
1247 
1248  /* Copy because timestamptz_to_str returns a static buffer */
1249  sendtime = pstrdup(timestamptz_to_str(sendTime));
1250  receipttime = pstrdup(timestamptz_to_str(lastMsgReceiptTime));
1251  applyDelay = GetReplicationApplyDelay();
1252 
1253  /* apply delay is not available */
1254  if (applyDelay == -1)
1255  elog(DEBUG2, "sendtime %s receipttime %s replication apply delay (N/A) transfer latency %d ms",
1256  sendtime,
1257  receipttime,
1259  else
1260  elog(DEBUG2, "sendtime %s receipttime %s replication apply delay %d ms transfer latency %d ms",
1261  sendtime,
1262  receipttime,
1263  applyDelay,
1265 
1266  pfree(sendtime);
1267  pfree(receipttime);
1268  }
1269 }
1270 
1271 /*
1272  * Wake up the walreceiver main loop.
1273  *
1274  * This is called by the startup process whenever interesting xlog records
1275  * are applied, so that walreceiver can check if it needs to send an apply
1276  * notification back to the primary which may be waiting in a COMMIT with
1277  * synchronous_commit = remote_apply.
1278  */
1279 void
1281 {
1282  Latch *latch;
1283 
1284  WalRcv->force_reply = true;
1285  /* fetching the latch pointer might not be atomic, so use spinlock */
1287  latch = WalRcv->latch;
1289  if (latch)
1290  SetLatch(latch);
1291 }
1292 
1293 /*
1294  * Return a string constant representing the state. This is used
1295  * in system functions and views, and should *not* be translated.
1296  */
1297 static const char *
1299 {
1300  switch (state)
1301  {
1302  case WALRCV_STOPPED:
1303  return "stopped";
1304  case WALRCV_STARTING:
1305  return "starting";
1306  case WALRCV_STREAMING:
1307  return "streaming";
1308  case WALRCV_WAITING:
1309  return "waiting";
1310  case WALRCV_RESTARTING:
1311  return "restarting";
1312  case WALRCV_STOPPING:
1313  return "stopping";
1314  }
1315  return "UNKNOWN";
1316 }
1317 
1318 /*
1319  * Returns activity of WAL receiver, including pid, state and xlog locations
1320  * received from the WAL sender of another server.
1321  */
1322 Datum
1324 {
1325  TupleDesc tupdesc;
1326  Datum *values;
1327  bool *nulls;
1328  int pid;
1329  bool ready_to_display;
1331  XLogRecPtr receive_start_lsn;
1332  TimeLineID receive_start_tli;
1333  XLogRecPtr written_lsn;
1334  XLogRecPtr flushed_lsn;
1335  TimeLineID received_tli;
1336  TimestampTz last_send_time;
1337  TimestampTz last_receipt_time;
1338  XLogRecPtr latest_end_lsn;
1339  TimestampTz latest_end_time;
1340  char sender_host[NI_MAXHOST];
1341  int sender_port = 0;
1342  char slotname[NAMEDATALEN];
1343  char conninfo[MAXCONNINFO];
1344 
1345  /* Take a lock to ensure value consistency */
1347  pid = (int) WalRcv->pid;
1348  ready_to_display = WalRcv->ready_to_display;
1349  state = WalRcv->walRcvState;
1350  receive_start_lsn = WalRcv->receiveStart;
1351  receive_start_tli = WalRcv->receiveStartTLI;
1352  written_lsn = pg_atomic_read_u64(&WalRcv->writtenUpto);
1353  flushed_lsn = WalRcv->flushedUpto;
1354  received_tli = WalRcv->receivedTLI;
1355  last_send_time = WalRcv->lastMsgSendTime;
1356  last_receipt_time = WalRcv->lastMsgReceiptTime;
1357  latest_end_lsn = WalRcv->latestWalEnd;
1358  latest_end_time = WalRcv->latestWalEndTime;
1359  strlcpy(slotname, (char *) WalRcv->slotname, sizeof(slotname));
1360  strlcpy(sender_host, (char *) WalRcv->sender_host, sizeof(sender_host));
1361  sender_port = WalRcv->sender_port;
1362  strlcpy(conninfo, (char *) WalRcv->conninfo, sizeof(conninfo));
1364 
1365  /*
1366  * No WAL receiver (or not ready yet), just return a tuple with NULL
1367  * values
1368  */
1369  if (pid == 0 || !ready_to_display)
1370  PG_RETURN_NULL();
1371 
1372  /* determine result type */
1373  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1374  elog(ERROR, "return type must be a row type");
1375 
1376  values = palloc0(sizeof(Datum) * tupdesc->natts);
1377  nulls = palloc0(sizeof(bool) * tupdesc->natts);
1378 
1379  /* Fetch values */
1380  values[0] = Int32GetDatum(pid);
1381 
1382  if (!is_member_of_role(GetUserId(), DEFAULT_ROLE_READ_ALL_STATS))
1383  {
1384  /*
1385  * Only superusers and members of pg_read_all_stats can see details.
1386  * Other users only get the pid value to know whether it is a WAL
1387  * receiver, but no details.
1388  */
1389  MemSet(&nulls[1], true, sizeof(bool) * (tupdesc->natts - 1));
1390  }
1391  else
1392  {
1393  values[1] = CStringGetTextDatum(WalRcvGetStateString(state));
1394 
1395  if (XLogRecPtrIsInvalid(receive_start_lsn))
1396  nulls[2] = true;
1397  else
1398  values[2] = LSNGetDatum(receive_start_lsn);
1399  values[3] = Int32GetDatum(receive_start_tli);
1400  if (XLogRecPtrIsInvalid(written_lsn))
1401  nulls[4] = true;
1402  else
1403  values[4] = LSNGetDatum(written_lsn);
1404  if (XLogRecPtrIsInvalid(flushed_lsn))
1405  nulls[5] = true;
1406  else
1407  values[5] = LSNGetDatum(flushed_lsn);
1408  values[6] = Int32GetDatum(received_tli);
1409  if (last_send_time == 0)
1410  nulls[7] = true;
1411  else
1412  values[7] = TimestampTzGetDatum(last_send_time);
1413  if (last_receipt_time == 0)
1414  nulls[8] = true;
1415  else
1416  values[8] = TimestampTzGetDatum(last_receipt_time);
1417  if (XLogRecPtrIsInvalid(latest_end_lsn))
1418  nulls[9] = true;
1419  else
1420  values[9] = LSNGetDatum(latest_end_lsn);
1421  if (latest_end_time == 0)
1422  nulls[10] = true;
1423  else
1424  values[10] = TimestampTzGetDatum(latest_end_time);
1425  if (*slotname == '\0')
1426  nulls[11] = true;
1427  else
1428  values[11] = CStringGetTextDatum(slotname);
1429  if (*sender_host == '\0')
1430  nulls[12] = true;
1431  else
1432  values[12] = CStringGetTextDatum(sender_host);
1433  if (sender_port == 0)
1434  nulls[13] = true;
1435  else
1436  values[13] = Int32GetDatum(sender_port);
1437  if (*conninfo == '\0')
1438  nulls[14] = true;
1439  else
1440  values[14] = CStringGetTextDatum(conninfo);
1441  }
1442 
1443  /* Returns the record as Datum */
1444  PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
1445 }
int sender_port
Definition: walreceiver.h:117
static void WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
Definition: walreceiver.c:724
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define walrcv_get_conninfo(conn)
Definition: walreceiver.h:402
static const char * WalRcvGetStateString(WalRcvState state)
Definition: walreceiver.c:1298
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:414
static void ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime)
Definition: walreceiver.c:1227
#define DEBUG1
Definition: elog.h:25
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
int MyProcPid
Definition: globals.c:40
uint32 TimeLineID
Definition: xlogdefs.h:52
bool hot_standby_feedback
Definition: walreceiver.c:90
slock_t mutex
Definition: walreceiver.h:143
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
int wal_segment_size
Definition: xlog.c:117
uint32 TransactionId
Definition: c.h:520
Oid GetUserId(void)
Definition: miscinit.c:476
#define SIGUSR1
Definition: win32_port.h:165
bool update_process_title
Definition: ps_status.c:36
XLogRecPtr Write
Definition: walreceiver.c:120
int GetReplicationTransferLatency(void)
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
static void WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI)
Definition: walreceiver.c:643
sig_atomic_t force_reply
Definition: walreceiver.h:158
void issue_xlog_fsync(int fd, XLogSegNo segno)
Definition: xlog.c:10408
#define walrcv_identify_system(conn, primary_tli)
Definition: walreceiver.h:406
WalRcvState walRcvState
Definition: walreceiver.h:64
static StringInfoData incoming_message
Definition: walreceiver.c:125
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool HotStandbyActive(void)
Definition: xlog.c:8148
static void XLogWalRcvSendHSFeedback(bool immed)
Definition: walreceiver.c:1126
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3252
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:416
void ProcessWalRcvInterrupts(void)
Definition: walreceiver.c:157
static void WalRcvSigHupHandler(SIGNAL_ARGS)
Definition: walreceiver.c:802
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:412
union WalRcvStreamOptions::@104 proto
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
TimeLineID receivedTLI
Definition: walreceiver.h:84
#define MemSet(start, val, len)
Definition: c.h:949
#define WL_SOCKET_READABLE
Definition: latch.h:125
static void XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len)
Definition: walreceiver.c:826
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
#define LOG
Definition: elog.h:26
static void pq_sendint64(StringInfo buf, uint64 i)
Definition: pqformat.h:153
bool RecoveryInProgress(void)
Definition: xlog.c:8074
void SetLatch(Latch *latch)
Definition: latch.c:505
int wal_receiver_status_interval
Definition: walreceiver.c:88
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:420
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1673
#define PANIC
Definition: elog.h:53
#define NAPTIME_PER_CYCLE
Definition: walreceiver.c:96
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
TimestampTz lastMsgReceiptTime
Definition: walreceiver.h:98
Datum pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
Definition: walreceiver.c:1323
void ResetLatch(Latch *latch)
Definition: latch.c:588
TimestampTz lastMsgSendTime
Definition: walreceiver.h:97
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static void pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:438
int wal_receiver_timeout
Definition: walreceiver.c:89
Latch procLatch
Definition: proc.h:121
static WalReceiverConn * wrconn
Definition: walreceiver.c:93
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
WalRcvState
Definition: walreceiver.h:44
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
pg_atomic_uint64 writtenUpto
Definition: walreceiver.h:151
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
#define NAMEDATALEN
void set_ps_display(const char *activity)
Definition: ps_status.c:349
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define SpinLockAcquire(lock)
Definition: spin.h:62
static StringInfoData reply_message
Definition: walreceiver.c:124
void XLogArchiveNotify(const char *xlog)
Definition: xlogarchive.c:466
void WalReceiverMain(void)
Definition: walreceiver.c:178
void pfree(void *pointer)
Definition: mcxt.c:1057
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:415
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define ERROR
Definition: elog.h:43
void WakeupRecovery(void)
Definition: xlog.c:12654
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
#define FATAL
Definition: elog.h:52
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11480
pid_t pid
Definition: walreceiver.h:63
#define MAXCONNINFO
Definition: walreceiver.h:36
XLogRecPtr latestChunkStart
Definition: walreceiver.h:92
#define DEBUG2
Definition: elog.h:24
Definition: latch.h:110
#define TLHistoryFileName(fname, tli)
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
static char * buf
Definition: pg_test_fsync.c:67
void writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
Definition: timeline.c:467
uint64 XLogSegNo
Definition: xlogdefs.h:41
int XLogArchiveMode
Definition: xlog.c:95
int errdetail(const char *fmt,...)
Definition: elog.c:957
static struct @24 LogstreamResult
int errcode_for_file_access(void)
Definition: elog.c:633
#define SIGHUP
Definition: win32_port.h:153
#define InvalidTransactionId
Definition: transam.h:31
#define AllowCascadeReplication()
Definition: walreceiver.h:39
XLogRecPtr startpoint
Definition: walreceiver.h:168
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:438
unsigned int uint32
Definition: c.h:374
int pgsocket
Definition: port.h:31
sigset_t UnBlockSig
Definition: pqsignal.c:22
bool existsTimeLineHistory(TimeLineID probeTLI)
Definition: timeline.c:222
static volatile sig_atomic_t got_SIGHUP
Definition: walreceiver.c:111
XLogRecPtr Flush
Definition: walreceiver.c:121
TimeLineID receiveStartTLI
Definition: walreceiver.h:74
static TimeLineID recvFileTLI
Definition: walreceiver.c:104
#define walrcv_get_backend_pid(conn)
Definition: walreceiver.h:422
FullTransactionId ReadNextFullTransactionId(void)
Definition: varsup.c:261
Definition: guc.h:72
char * cluster_name
Definition: guc.c:555
Latch * latch
Definition: walreceiver.h:141
int GetReplicationApplyDelay(void)
#define SIG_IGN
Definition: win32_port.h:150
static char ** options
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static XLogSegNo recvSegNo
Definition: walreceiver.c:105
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
void * palloc0(Size size)
Definition: mcxt.c:981
void XLogArchiveForceDone(const char *xlog)
Definition: xlogarchive.c:516
uintptr_t Datum
Definition: postgres.h:367
void GetReplicationHorizons(TransactionId *xmin, TransactionId *catalog_xmin)
Definition: procarray.c:1905
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
WalReceiverFunctionsType * WalReceiverFunctions
Definition: walreceiver.c:94
#define PGINVALID_SOCKET
Definition: port.h:33
static void XLogWalRcvSendReply(bool force, bool requestReply)
Definition: walreceiver.c:1057
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
bool ready_to_display
Definition: walreceiver.h:132
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
TimestampTz latestWalEndTime
Definition: walreceiver.h:104
int log_min_messages
Definition: guc.c:538
static void WalRcvShutdownHandler(SIGNAL_ARGS)
Definition: walreceiver.c:810
TimeLineID ThisTimeLineID
Definition: xlog.c:192
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:144
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:4916
XLogRecPtr latestWalEnd
Definition: walreceiver.h:103
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
#define pg_memory_barrier()
Definition: atomics.h:145
#define SIG_DFL
Definition: win32_port.h:148
#define SIGNAL_ARGS
Definition: c.h:1273
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:745
Definition: regguts.h:298
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
size_t Size
Definition: c.h:473
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
#define SIGALRM
Definition: win32_port.h:159
#define walrcv_disconnect(conn)
Definition: walreceiver.h:426
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:418
bool is_temp_slot
Definition: walreceiver.h:129
#define walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)
Definition: walreceiver.h:410
static void XLogWalRcvFlush(bool dying)
Definition: walreceiver.c:998
WalRcvData * WalRcv
static Datum values[MAXATTR]
Definition: bootstrap.c:165
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4911
#define Int32GetDatum(X)
Definition: postgres.h:479
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:429
char sender_host[NI_MAXHOST]
Definition: walreceiver.h:116
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void WalRcvDie(int code, Datum arg)
Definition: walreceiver.c:771
#define elog(elevel,...)
Definition: elog.h:214
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:455
#define walrcv_get_senderinfo(conn, sender_host, sender_port)
Definition: walreceiver.h:404
#define CStringGetTextDatum(s)
Definition: builtins.h:86
void * arg
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
struct WalRcvStreamOptions::@104::@105 physical
#define close(a)
Definition: win32.h:12
XLogRecPtr receiveStart
Definition: walreceiver.h:73
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
static volatile sig_atomic_t got_SIGTERM
Definition: walreceiver.c:112
static int recvFile
Definition: walreceiver.c:103
XLogRecPtr flushedUpto
Definition: walreceiver.h:83
#define snprintf
Definition: port.h:193
#define WL_LATCH_SET
Definition: latch.h:124
#define UINT64_FORMAT
Definition: c.h:417
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define PG_RETURN_NULL()
Definition: fmgr.h:344
char slotname[NAMEDATALEN]
Definition: walreceiver.h:123
void WalSndWakeup(void)
Definition: walsender.c:3119
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
char conninfo[MAXCONNINFO]
Definition: walreceiver.h:110
static void XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr)
Definition: walreceiver.c:893
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1736
void WalRcvForceReply(void)
Definition: walreceiver.c:1280
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:398