Branch data Line data Source code
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 : : * ereport(FATAL). Emergency termination is by SIGQUIT; like any postmaster
34 : : * child process, the walreceiver will simply abort and exit on SIGQUIT. A
35 : : * close 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-2026, 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.h"
58 : : #include "access/xlog_internal.h"
59 : : #include "access/xlogarchive.h"
60 : : #include "access/xlogrecovery.h"
61 : : #include "access/xlogwait.h"
62 : : #include "catalog/pg_authid.h"
63 : : #include "funcapi.h"
64 : : #include "libpq/pqformat.h"
65 : : #include "libpq/pqsignal.h"
66 : : #include "miscadmin.h"
67 : : #include "pgstat.h"
68 : : #include "postmaster/auxprocess.h"
69 : : #include "postmaster/interrupt.h"
70 : : #include "replication/walreceiver.h"
71 : : #include "replication/walsender.h"
72 : : #include "storage/ipc.h"
73 : : #include "storage/proc.h"
74 : : #include "storage/procarray.h"
75 : : #include "storage/procsignal.h"
76 : : #include "tcop/tcopprot.h"
77 : : #include "utils/acl.h"
78 : : #include "utils/builtins.h"
79 : : #include "utils/guc.h"
80 : : #include "utils/pg_lsn.h"
81 : : #include "utils/ps_status.h"
82 : : #include "utils/timestamp.h"
83 : : #include "utils/wait_event.h"
84 : :
85 : :
86 : : /*
87 : : * GUC variables. (Other variables that affect walreceiver are in xlog.c
88 : : * because they're passed down from the startup process, for better
89 : : * synchronization.)
90 : : */
91 : : int wal_receiver_status_interval;
92 : : int wal_receiver_timeout;
93 : : bool hot_standby_feedback;
94 : :
95 : : /* libpqwalreceiver connection */
96 : : static WalReceiverConn *wrconn = NULL;
97 : : WalReceiverFunctionsType *WalReceiverFunctions = NULL;
98 : :
99 : : /*
100 : : * These variables are used similarly to openLogFile/SegNo,
101 : : * but for walreceiver to write the XLOG. recvFileTLI is the TimeLineID
102 : : * corresponding the filename of recvFile.
103 : : */
104 : : static int recvFile = -1;
105 : : static TimeLineID recvFileTLI = 0;
106 : : static XLogSegNo recvSegNo = 0;
107 : :
108 : : /*
109 : : * LogstreamResult indicates the byte positions that we have already
110 : : * written/fsynced.
111 : : */
112 : : static struct
113 : : {
114 : : XLogRecPtr Write; /* last byte + 1 written out in the standby */
115 : : XLogRecPtr Flush; /* last byte + 1 flushed in the standby */
116 : : } LogstreamResult;
117 : :
118 : : /*
119 : : * Reasons to wake up and perform periodic tasks.
120 : : */
121 : : typedef enum WalRcvWakeupReason
122 : : {
123 : : WALRCV_WAKEUP_TERMINATE,
124 : : WALRCV_WAKEUP_PING,
125 : : WALRCV_WAKEUP_REPLY,
126 : : WALRCV_WAKEUP_HSFEEDBACK,
127 : : #define NUM_WALRCV_WAKEUPS (WALRCV_WAKEUP_HSFEEDBACK + 1)
128 : : } WalRcvWakeupReason;
129 : :
130 : : /*
131 : : * Wake up times for periodic tasks.
132 : : */
133 : : static TimestampTz wakeup[NUM_WALRCV_WAKEUPS];
134 : :
135 : : static StringInfoData reply_message;
136 : :
137 : : /* Prototypes for private functions */
138 : : static void WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last);
139 : : static void WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI);
140 : : static void WalRcvDie(int code, Datum arg);
141 : : static void XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len,
142 : : TimeLineID tli);
143 : : static void XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr,
144 : : TimeLineID tli);
145 : : static void XLogWalRcvFlush(bool dying, TimeLineID tli);
146 : : static void XLogWalRcvClose(XLogRecPtr recptr, TimeLineID tli);
147 : : static void XLogWalRcvSendReply(bool force, bool requestReply, bool checkApply);
148 : : static void XLogWalRcvSendHSFeedback(bool immed);
149 : : static void ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime);
150 : : static void WalRcvComputeNextWakeup(WalRcvWakeupReason reason, TimestampTz now);
151 : :
152 : :
153 : : /* Main entry point for walreceiver process */
154 : : void
155 : 285 : WalReceiverMain(const void *startup_data, size_t startup_data_len)
156 : : {
157 : : char conninfo[MAXCONNINFO];
158 : : char *tmp_conninfo;
159 : : char slotname[NAMEDATALEN];
160 : : bool is_temp_slot;
161 : : XLogRecPtr startpoint;
162 : : TimeLineID startpointTLI;
163 : : TimeLineID primaryTLI;
164 : : bool first_stream;
165 : 285 : bool upstream_catchup_logged = false;
166 : 285 : TimestampTz upstream_catchup_deadline = 0;
167 : : WalRcvData *walrcv;
168 : : TimestampTz now;
169 : : char *err;
170 : 285 : char *sender_host = NULL;
171 : 285 : int sender_port = 0;
172 : : char *appname;
173 : :
174 : : Assert(startup_data_len == 0);
175 : :
176 : 285 : AuxiliaryProcessMainCommon();
177 : :
178 : : /*
179 : : * WalRcv should be set up already (if we are a backend, we inherit this
180 : : * by fork() or EXEC_BACKEND mechanism from the postmaster).
181 : : */
182 : 285 : walrcv = WalRcv;
183 : : Assert(walrcv != NULL);
184 : :
185 : : /*
186 : : * Mark walreceiver as running in shared memory.
187 : : *
188 : : * Do this as early as possible, so that if we fail later on, we'll set
189 : : * state to STOPPED. If we die before this, the startup process will keep
190 : : * waiting for us to start up, until it times out.
191 : : */
192 : 285 : SpinLockAcquire(&walrcv->mutex);
193 : : Assert(walrcv->pid == 0);
194 [ - + + - ]: 285 : switch (walrcv->walRcvState)
195 : : {
196 : 0 : case WALRCV_STOPPING:
197 : : /* If we've already been requested to stop, don't start up. */
198 : 0 : walrcv->walRcvState = WALRCV_STOPPED;
199 : : pg_fallthrough;
200 : :
201 : 5 : case WALRCV_STOPPED:
202 : 5 : SpinLockRelease(&walrcv->mutex);
203 : 5 : ConditionVariableBroadcast(&walrcv->walRcvStoppedCV);
204 : 5 : proc_exit(1);
205 : : break;
206 : :
207 : 280 : case WALRCV_STARTING:
208 : : /* The usual case */
209 : 280 : break;
210 : :
211 : 0 : case WALRCV_CONNECTING:
212 : : case WALRCV_WAITING:
213 : : case WALRCV_STREAMING:
214 : : case WALRCV_RESTARTING:
215 : : default:
216 : : /* Shouldn't happen */
217 : 0 : SpinLockRelease(&walrcv->mutex);
218 [ # # ]: 0 : elog(PANIC, "walreceiver still running according to shared memory state");
219 : : }
220 : : /* Advertise our PID so that the startup process can kill us */
221 : 280 : walrcv->pid = MyProcPid;
222 : 280 : walrcv->walRcvState = WALRCV_CONNECTING;
223 : :
224 : : /* Fetch information required to start streaming */
225 : 280 : walrcv->ready_to_display = false;
226 : 280 : strlcpy(conninfo, walrcv->conninfo, MAXCONNINFO);
227 : 280 : strlcpy(slotname, walrcv->slotname, NAMEDATALEN);
228 : 280 : is_temp_slot = walrcv->is_temp_slot;
229 : 280 : startpoint = walrcv->receiveStart;
230 : 280 : startpointTLI = walrcv->receiveStartTLI;
231 : :
232 : : /*
233 : : * At most one of is_temp_slot and slotname can be set; otherwise,
234 : : * RequestXLogStreaming messed up.
235 : : */
236 : : Assert(!is_temp_slot || (slotname[0] == '\0'));
237 : :
238 : : /* Initialise to a sanish value */
239 : 280 : now = GetCurrentTimestamp();
240 : 280 : walrcv->lastMsgSendTime =
241 : 280 : walrcv->lastMsgReceiptTime = walrcv->latestWalEndTime = now;
242 : :
243 : : /* Report our proc number so that others can wake us up */
244 : 280 : walrcv->procno = MyProcNumber;
245 : :
246 : 280 : SpinLockRelease(&walrcv->mutex);
247 : :
248 : : /* Arrange to clean up at walreceiver exit */
249 : 280 : on_shmem_exit(WalRcvDie, PointerGetDatum(&startpointTLI));
250 : :
251 : : /* Properly accept or ignore signals the postmaster might send us */
252 : 280 : pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
253 : : * file */
254 : 280 : pqsignal(SIGINT, PG_SIG_IGN);
255 : 280 : pqsignal(SIGTERM, die); /* request shutdown */
256 : : /* SIGQUIT handler was already set up by InitPostmasterChild */
257 : 280 : pqsignal(SIGALRM, PG_SIG_IGN);
258 : 280 : pqsignal(SIGPIPE, PG_SIG_IGN);
259 : 280 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
260 : 280 : pqsignal(SIGUSR2, PG_SIG_IGN);
261 : :
262 : : /* Reset some signals that are accepted by postmaster but not here */
263 : 280 : pqsignal(SIGCHLD, PG_SIG_DFL);
264 : :
265 : : /* Load the libpq-specific functions */
266 : 280 : load_file("libpqwalreceiver", false);
267 [ - + ]: 280 : if (WalReceiverFunctions == NULL)
268 [ # # ]: 0 : elog(ERROR, "libpqwalreceiver didn't initialize correctly");
269 : :
270 : : /* Unblock signals (they were blocked when the postmaster forked us) */
271 : 280 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
272 : :
273 : : /*
274 : : * Switch the WAL receiver state as ready for display before doing a
275 : : * connection attempt, so as its connecting state is visible before
276 : : * attempting to contact the primary server. Note that this resets the
277 : : * original conninfo, sender_port and sender_host, for security. These
278 : : * fields are filled once the connection is fully established.
279 : : */
280 : 280 : SpinLockAcquire(&walrcv->mutex);
281 : 280 : memset(walrcv->conninfo, 0, MAXCONNINFO);
282 : 280 : memset(walrcv->sender_host, 0, NI_MAXHOST);
283 : 280 : walrcv->sender_port = 0;
284 : 280 : walrcv->ready_to_display = true;
285 : 280 : SpinLockRelease(&walrcv->mutex);
286 : :
287 : : /* Establish the connection to the primary for XLOG streaming */
288 [ + + ]: 280 : appname = cluster_name[0] ? cluster_name : "walreceiver";
289 : 280 : wrconn = walrcv_connect(conninfo, true, false, false, appname, &err);
290 [ + + ]: 280 : if (!wrconn)
291 [ + - ]: 119 : ereport(ERROR,
292 : : (errcode(ERRCODE_CONNECTION_FAILURE),
293 : : errmsg("streaming replication receiver \"%s\" could not connect to the primary server: %s",
294 : : appname, err)));
295 : :
296 : : /*
297 : : * Save user-visible connection string, now that the connection has been
298 : : * achieved.
299 : : */
300 : 161 : tmp_conninfo = walrcv_get_conninfo(wrconn);
301 : 161 : walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
302 : 161 : SpinLockAcquire(&walrcv->mutex);
303 [ + - ]: 161 : if (tmp_conninfo)
304 : 161 : strlcpy(walrcv->conninfo, tmp_conninfo, MAXCONNINFO);
305 [ + - ]: 161 : if (sender_host)
306 : 161 : strlcpy(walrcv->sender_host, sender_host, NI_MAXHOST);
307 : 161 : walrcv->sender_port = sender_port;
308 : 161 : SpinLockRelease(&walrcv->mutex);
309 : :
310 [ + - ]: 161 : if (tmp_conninfo)
311 : 161 : pfree(tmp_conninfo);
312 : :
313 [ + - ]: 161 : if (sender_host)
314 : 161 : pfree(sender_host);
315 : :
316 : : /* Initialize buffers for processing messages */
317 : 161 : initStringInfo(&reply_message);
318 : :
319 : 161 : first_stream = true;
320 : : for (;;)
321 : 14 : {
322 : : char *primary_sysid;
323 : : char standby_sysid[32];
324 : : XLogRecPtr primaryFlushPtr;
325 : : WalRcvStreamOptions options;
326 : :
327 : : /*
328 : : * Check that we're connected to a valid server using the
329 : : * IDENTIFY_SYSTEM replication command.
330 : : */
331 : 175 : primary_sysid = walrcv_identify_system(wrconn, &primaryTLI,
332 : : &primaryFlushPtr);
333 : :
334 : 175 : snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
335 : : GetSystemIdentifier());
336 [ - + ]: 175 : if (strcmp(primary_sysid, standby_sysid) != 0)
337 : : {
338 [ # # ]: 0 : ereport(ERROR,
339 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
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 : 175 : pfree(primary_sysid);
345 : :
346 : : /*
347 : : * Confirm that the current timeline of the primary is the same or
348 : : * ahead of ours.
349 : : */
350 [ - + ]: 175 : if (primaryTLI < startpointTLI)
351 [ # # ]: 0 : ereport(ERROR,
352 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
353 : : errmsg("highest timeline %u of the primary is behind recovery timeline %u",
354 : : primaryTLI, startpointTLI)));
355 : :
356 : : /*
357 : : * If our requested startpoint is ahead of the upstream server's
358 : : * current WAL flush position, we cannot start streaming yet. (We say
359 : : * "upstream" here and not "primary" because this condition can only
360 : : * happen on a cascading standby.) This can happen when such a
361 : : * cascading standby has advanced past the upstream via archive
362 : : * recovery but the intermediate standby has not caught up with that
363 : : * yet. In this case, wait for the upstream to catch up before
364 : : * attempting START_REPLICATION, because that would fail with
365 : : * "requested starting point is ahead of the WAL flush position".
366 : : *
367 : : * We only perform this check when we're on the same timeline as the
368 : : * primary; when timelines differ, let START_REPLICATION handle the
369 : : * timeline negotiation.
370 : : *
371 : : * We also only wait if the gap is within one WAL segment. This is
372 : : * the expected case because archive recovery processes whole segment
373 : : * files: the cascade's next read position lands at the start of the
374 : : * following segment while the upstream's flush position is still
375 : : * inside the just-replayed one, producing at most a sub-segment gap.
376 : : * A larger gap means the upstream is genuinely behind, so we let
377 : : * START_REPLICATION fail normally and allow the startup process to
378 : : * fall back to other WAL sources.
379 : : *
380 : : * Honor wal_receiver_timeout so the walreceiver doesn't wait
381 : : * indefinitely: if the upstream hasn't caught up within the timeout,
382 : : * exit and let the startup process retry normally.
383 : : */
384 [ + + ]: 175 : if (startpointTLI == primaryTLI &&
385 [ + + ]: 165 : startpoint > primaryFlushPtr &&
386 [ + - ]: 1 : startpoint - primaryFlushPtr <= wal_segment_size)
387 : : {
388 : : /* Set deadline on first iteration */
389 [ + - + - ]: 1 : if (!upstream_catchup_logged && wal_receiver_timeout > 0)
390 : 1 : upstream_catchup_deadline =
391 : 1 : TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
392 : : wal_receiver_timeout);
393 : :
394 [ - + + - ]: 1 : ereport(upstream_catchup_logged ? DEBUG1 : LOG,
395 : : errmsg("walreceiver requested start point %X/%08X on timeline %u is ahead of the upstream server's flush position %X/%08X, waiting",
396 : : LSN_FORMAT_ARGS(startpoint), startpointTLI,
397 : : LSN_FORMAT_ARGS(primaryFlushPtr)));
398 : 1 : upstream_catchup_logged = true;
399 : :
400 : 1 : (void) WaitLatch(MyLatch,
401 : : WL_EXIT_ON_PM_DEATH | WL_TIMEOUT | WL_LATCH_SET,
402 : : wal_retrieve_retry_interval,
403 : : WAIT_EVENT_WAL_RECEIVER_UPSTREAM_CATCHUP);
404 : 1 : ResetLatch(MyLatch);
405 : :
406 [ + - - + ]: 2 : if (upstream_catchup_deadline > 0 &&
407 : 1 : GetCurrentTimestamp() >= upstream_catchup_deadline)
408 [ # # ]: 0 : ereport(ERROR,
409 : : (errcode(ERRCODE_CONNECTION_FAILURE),
410 : : errmsg("terminating walreceiver due to timeout while waiting for upstream to catch up")));
411 : :
412 [ - + ]: 1 : CHECK_FOR_INTERRUPTS();
413 : 1 : continue;
414 : : }
415 : : else
416 : : {
417 : 174 : upstream_catchup_logged = false;
418 : 174 : upstream_catchup_deadline = 0;
419 : : }
420 : :
421 : : /*
422 : : * Get any missing history files. We do this always, even when we're
423 : : * not interested in that timeline, so that if we're promoted to
424 : : * become the primary later on, we don't select the same timeline that
425 : : * was already used in the current primary. This isn't bullet-proof -
426 : : * you'll need some external software to manage your cluster if you
427 : : * need to ensure that a unique timeline id is chosen in every case,
428 : : * but let's avoid the confusion of timeline id collisions where we
429 : : * can.
430 : : */
431 : 174 : WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
432 : :
433 : : /*
434 : : * Create temporary replication slot if requested, and update slot
435 : : * name in shared memory. (Note the slot name cannot already be set
436 : : * in this case.)
437 : : */
438 [ - + ]: 174 : if (is_temp_slot)
439 : : {
440 : 0 : snprintf(slotname, sizeof(slotname),
441 : : "pg_walreceiver_%lld",
442 : 0 : (long long int) walrcv_get_backend_pid(wrconn));
443 : :
444 : 0 : walrcv_create_slot(wrconn, slotname, true, false, false, 0, NULL);
445 : :
446 : 0 : SpinLockAcquire(&walrcv->mutex);
447 : 0 : strlcpy(walrcv->slotname, slotname, NAMEDATALEN);
448 : 0 : SpinLockRelease(&walrcv->mutex);
449 : : }
450 : :
451 : : /*
452 : : * Start streaming.
453 : : *
454 : : * We'll try to start at the requested starting point and timeline,
455 : : * even if it's different from the server's latest timeline. In case
456 : : * we've already reached the end of the old timeline, the server will
457 : : * finish the streaming immediately, and we will go back to await
458 : : * orders from the startup process. If recovery_target_timeline is
459 : : * 'latest', the startup process will scan pg_wal and find the new
460 : : * history file, bump recovery target timeline, and ask us to restart
461 : : * on the new timeline.
462 : : */
463 : 174 : options.logical = false;
464 : 174 : options.startpoint = startpoint;
465 [ + + ]: 174 : options.slotname = slotname[0] != '\0' ? slotname : NULL;
466 : 174 : options.proto.physical.startpointTLI = startpointTLI;
467 [ + - ]: 174 : if (walrcv_startstreaming(wrconn, &options))
468 : : {
469 [ + + ]: 173 : if (first_stream)
470 [ + - ]: 160 : ereport(LOG,
471 : : errmsg("started streaming WAL from primary at %X/%08X on timeline %u",
472 : : LSN_FORMAT_ARGS(startpoint), startpointTLI));
473 : : else
474 [ + - ]: 13 : ereport(LOG,
475 : : errmsg("restarted WAL streaming at %X/%08X on timeline %u",
476 : : LSN_FORMAT_ARGS(startpoint), startpointTLI));
477 : 173 : first_stream = false;
478 : :
479 : : /*
480 : : * Switch to STREAMING after a successful connection if current
481 : : * state is CONNECTING. This switch happens after an initial
482 : : * startup, or after a restart as determined by
483 : : * WalRcvWaitForStartPosition().
484 : : */
485 : 173 : SpinLockAcquire(&walrcv->mutex);
486 [ + - ]: 173 : if (walrcv->walRcvState == WALRCV_CONNECTING)
487 : 173 : walrcv->walRcvState = WALRCV_STREAMING;
488 : 173 : SpinLockRelease(&walrcv->mutex);
489 : :
490 : : /* Initialize LogstreamResult for processing messages */
491 : 173 : LogstreamResult.Write = LogstreamResult.Flush = GetXLogReplayRecPtr(NULL);
492 : :
493 : : /* Initialize nap wakeup times. */
494 : 173 : now = GetCurrentTimestamp();
495 [ + + ]: 865 : for (int i = 0; i < NUM_WALRCV_WAKEUPS; ++i)
496 : 692 : WalRcvComputeNextWakeup(i, now);
497 : :
498 : : /* Send initial reply/feedback messages. */
499 : 173 : XLogWalRcvSendReply(true, false, false);
500 : 173 : XLogWalRcvSendHSFeedback(true);
501 : :
502 : : /* Loop until end-of-streaming or error */
503 : : for (;;)
504 : 60327 : {
505 : : char *buf;
506 : : int len;
507 : 60500 : bool endofwal = false;
508 : 60500 : pgsocket wait_fd = PGINVALID_SOCKET;
509 : : int rc;
510 : : TimestampTz nextWakeup;
511 : : long nap;
512 : :
513 : : /*
514 : : * Exit walreceiver if we're not in recovery. This should not
515 : : * happen, but cross-check the status here.
516 : : */
517 [ - + ]: 60500 : if (!RecoveryInProgress())
518 [ # # ]: 0 : ereport(FATAL,
519 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
520 : : errmsg("cannot continue WAL streaming, recovery has already ended")));
521 : :
522 : : /* Process any requests or signals received recently */
523 [ + + ]: 60500 : CHECK_FOR_INTERRUPTS();
524 : :
525 [ + + ]: 60500 : if (ConfigReloadPending)
526 : : {
527 : 30 : ConfigReloadPending = false;
528 : 30 : ProcessConfigFile(PGC_SIGHUP);
529 : : /* recompute wakeup times */
530 : 30 : now = GetCurrentTimestamp();
531 [ + + ]: 150 : for (int i = 0; i < NUM_WALRCV_WAKEUPS; ++i)
532 : 120 : WalRcvComputeNextWakeup(i, now);
533 : 30 : XLogWalRcvSendHSFeedback(true);
534 : : }
535 : :
536 : : /* See if we can read data immediately */
537 : 60500 : len = walrcv_receive(wrconn, &buf, &wait_fd);
538 [ + + ]: 60467 : if (len != 0)
539 : : {
540 : : /*
541 : : * Process the received data, and any subsequent data we
542 : : * can read without blocking.
543 : : */
544 : : for (;;)
545 : : {
546 [ + + ]: 152578 : if (len > 0)
547 : : {
548 : : /*
549 : : * Something was received from primary, so adjust
550 : : * the ping and terminate wakeup times.
551 : : */
552 : 108793 : now = GetCurrentTimestamp();
553 : 108793 : WalRcvComputeNextWakeup(WALRCV_WAKEUP_TERMINATE,
554 : : now);
555 : 108793 : WalRcvComputeNextWakeup(WALRCV_WAKEUP_PING, now);
556 : 108793 : XLogWalRcvProcessMsg(buf[0], &buf[1], len - 1,
557 : : startpointTLI);
558 : : }
559 [ + + ]: 43785 : else if (len == 0)
560 : 43738 : break;
561 [ + - ]: 47 : else if (len < 0)
562 : : {
563 [ + - ]: 47 : ereport(LOG,
564 : : (errmsg("replication terminated by primary server"),
565 : : errdetail("End of WAL reached on timeline %u at %X/%08X.",
566 : : startpointTLI,
567 : : LSN_FORMAT_ARGS(LogstreamResult.Write))));
568 : 47 : endofwal = true;
569 : 47 : break;
570 : : }
571 : 108793 : len = walrcv_receive(wrconn, &buf, &wait_fd);
572 : : }
573 : :
574 : : /* Let the primary know that we received some data. */
575 : 43785 : XLogWalRcvSendReply(false, false, false);
576 : :
577 : : /*
578 : : * If we've written some records, flush them to disk and
579 : : * let the startup process and primary server know about
580 : : * them.
581 : : */
582 : 43785 : XLogWalRcvFlush(false, startpointTLI);
583 : : }
584 : :
585 : : /* Check if we need to exit the streaming loop. */
586 [ + + ]: 60466 : if (endofwal)
587 : 46 : break;
588 : :
589 : : /* Find the soonest wakeup time, to limit our nap. */
590 : 60420 : nextWakeup = TIMESTAMP_INFINITY;
591 [ + + ]: 302100 : for (int i = 0; i < NUM_WALRCV_WAKEUPS; ++i)
592 : 241680 : nextWakeup = Min(wakeup[i], nextWakeup);
593 : :
594 : : /* Calculate the nap time, clamping as necessary. */
595 : 60420 : now = GetCurrentTimestamp();
596 : 60420 : nap = TimestampDifferenceMilliseconds(now, nextWakeup);
597 : :
598 : : /*
599 : : * Ideally we would reuse a WaitEventSet object repeatedly
600 : : * here to avoid the overheads of WaitLatchOrSocket on epoll
601 : : * systems, but we can't be sure that libpq (or any other
602 : : * walreceiver implementation) has the same socket (even if
603 : : * the fd is the same number, it may have been closed and
604 : : * reopened since the last time). In future, if there is a
605 : : * function for removing sockets from WaitEventSet, then we
606 : : * could add and remove just the socket each time, potentially
607 : : * avoiding some system calls.
608 : : */
609 : : Assert(wait_fd != PGINVALID_SOCKET);
610 : 60420 : rc = WaitLatchOrSocket(MyLatch,
611 : : WL_EXIT_ON_PM_DEATH | WL_SOCKET_READABLE |
612 : : WL_TIMEOUT | WL_LATCH_SET,
613 : : wait_fd,
614 : : nap,
615 : : WAIT_EVENT_WAL_RECEIVER_MAIN);
616 [ + + ]: 60420 : if (rc & WL_LATCH_SET)
617 : : {
618 : 14338 : ResetLatch(MyLatch);
619 [ + + ]: 14338 : CHECK_FOR_INTERRUPTS();
620 : :
621 [ + + ]: 14245 : if (walrcv->apply_reply_requested)
622 : : {
623 : : /*
624 : : * The recovery process has asked us to send apply
625 : : * feedback now. Make sure the flag is really set to
626 : : * false in shared memory before sending the reply, so
627 : : * we don't miss a new request for a reply.
628 : : */
629 : 14172 : walrcv->apply_reply_requested = false;
630 : 14172 : pg_memory_barrier();
631 : 14172 : XLogWalRcvSendReply(false, false, true);
632 : : }
633 : : }
634 [ + + ]: 60327 : if (rc & WL_TIMEOUT)
635 : : {
636 : : /*
637 : : * We didn't receive anything new. If we haven't heard
638 : : * anything from the server for more than
639 : : * wal_receiver_timeout / 2, ping the server. Also, if
640 : : * it's been longer than wal_receiver_status_interval
641 : : * since the last update we sent, send a status update to
642 : : * the primary anyway, to report any progress in applying
643 : : * WAL.
644 : : */
645 : 6 : bool requestReply = false;
646 : :
647 : : /*
648 : : * Report pending statistics to the cumulative stats
649 : : * system. This location is useful for the report as it
650 : : * is not within a tight loop in the WAL receiver, to
651 : : * avoid bloating pgstats with requests, while also making
652 : : * sure that the reports happen each time a status update
653 : : * is sent.
654 : : */
655 : 6 : pgstat_report_wal(false);
656 : :
657 : : /*
658 : : * Check if time since last receive from primary has
659 : : * reached the configured limit.
660 : : */
661 : 6 : now = GetCurrentTimestamp();
662 [ - + ]: 6 : if (now >= wakeup[WALRCV_WAKEUP_TERMINATE])
663 [ # # ]: 0 : ereport(ERROR,
664 : : (errcode(ERRCODE_CONNECTION_FAILURE),
665 : : errmsg("terminating walreceiver due to timeout")));
666 : :
667 : : /*
668 : : * If we didn't receive anything new for half of receiver
669 : : * replication timeout, then ping the server.
670 : : */
671 [ - + ]: 6 : if (now >= wakeup[WALRCV_WAKEUP_PING])
672 : : {
673 : 0 : requestReply = true;
674 : 0 : wakeup[WALRCV_WAKEUP_PING] = TIMESTAMP_INFINITY;
675 : : }
676 : :
677 : 6 : XLogWalRcvSendReply(requestReply, requestReply, false);
678 : 6 : XLogWalRcvSendHSFeedback(false);
679 : : }
680 : : }
681 : :
682 : : /*
683 : : * The backend finished streaming. Exit streaming COPY-mode from
684 : : * our side, too.
685 : : */
686 : 46 : walrcv_endstreaming(wrconn, &primaryTLI);
687 : :
688 : : /*
689 : : * If the server had switched to a new timeline that we didn't
690 : : * know about when we began streaming, fetch its timeline history
691 : : * file now.
692 : : */
693 : 13 : WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
694 : : }
695 : : else
696 [ # # ]: 0 : ereport(LOG,
697 : : (errmsg("primary server contains no more WAL on requested timeline %u",
698 : : startpointTLI)));
699 : :
700 : : /*
701 : : * End of WAL reached on the requested timeline. Close the last
702 : : * segment, and await for new orders from the startup process.
703 : : */
704 [ + + ]: 13 : if (recvFile >= 0)
705 : : {
706 : : char xlogfname[MAXFNAMELEN];
707 : :
708 : 12 : XLogWalRcvFlush(false, startpointTLI);
709 : 12 : XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
710 [ - + ]: 12 : if (close(recvFile) != 0)
711 [ # # ]: 0 : ereport(PANIC,
712 : : (errcode_for_file_access(),
713 : : errmsg("could not close WAL segment %s: %m",
714 : : xlogfname)));
715 : :
716 : : /*
717 : : * Create .done file forcibly to prevent the streamed segment from
718 : : * being archived later.
719 : : */
720 [ + - ]: 12 : if (XLogArchiveMode != ARCHIVE_MODE_ALWAYS)
721 : 12 : XLogArchiveForceDone(xlogfname);
722 : : else
723 : 0 : XLogArchiveNotify(xlogfname);
724 : : }
725 : 13 : recvFile = -1;
726 : :
727 [ + + ]: 13 : elog(DEBUG1, "walreceiver ended streaming and awaits new instructions");
728 : 13 : WalRcvWaitForStartPosition(&startpoint, &startpointTLI);
729 : : }
730 : : /* not reached */
731 : : }
732 : :
733 : : /*
734 : : * Wait for startup process to set receiveStart and receiveStartTLI.
735 : : */
736 : : static void
737 : 13 : WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI)
738 : : {
739 : 13 : WalRcvData *walrcv = WalRcv;
740 : : int state;
741 : :
742 : 13 : SpinLockAcquire(&walrcv->mutex);
743 : 13 : state = walrcv->walRcvState;
744 [ - + - - ]: 13 : if (state != WALRCV_STREAMING && state != WALRCV_CONNECTING)
745 : : {
746 : 0 : SpinLockRelease(&walrcv->mutex);
747 [ # # ]: 0 : if (state == WALRCV_STOPPING)
748 : 0 : proc_exit(0);
749 : : else
750 [ # # ]: 0 : elog(FATAL, "unexpected walreceiver state");
751 : : }
752 : 13 : walrcv->walRcvState = WALRCV_WAITING;
753 : 13 : walrcv->receiveStart = InvalidXLogRecPtr;
754 : 13 : walrcv->receiveStartTLI = 0;
755 : 13 : SpinLockRelease(&walrcv->mutex);
756 : :
757 : 13 : set_ps_display("idle");
758 : :
759 : : /*
760 : : * nudge startup process to notice that we've stopped streaming and are
761 : : * now waiting for instructions.
762 : : */
763 : 13 : WakeupRecovery();
764 : : for (;;)
765 : : {
766 : 26 : ResetLatch(MyLatch);
767 : :
768 [ - + ]: 26 : CHECK_FOR_INTERRUPTS();
769 : :
770 : 26 : SpinLockAcquire(&walrcv->mutex);
771 : : Assert(walrcv->walRcvState == WALRCV_RESTARTING ||
772 : : walrcv->walRcvState == WALRCV_WAITING ||
773 : : walrcv->walRcvState == WALRCV_STOPPING);
774 [ + + ]: 26 : if (walrcv->walRcvState == WALRCV_RESTARTING)
775 : : {
776 : : /*
777 : : * No need to handle changes in primary_conninfo or
778 : : * primary_slot_name here. Startup process will signal us to
779 : : * terminate in case those change.
780 : : */
781 : 13 : *startpoint = walrcv->receiveStart;
782 : 13 : *startpointTLI = walrcv->receiveStartTLI;
783 : 13 : walrcv->walRcvState = WALRCV_CONNECTING;
784 : 13 : SpinLockRelease(&walrcv->mutex);
785 : 13 : break;
786 : : }
787 [ - + ]: 13 : if (walrcv->walRcvState == WALRCV_STOPPING)
788 : : {
789 : : /*
790 : : * We should've received SIGTERM if the startup process wants us
791 : : * to die, but might as well check it here too.
792 : : */
793 : 0 : SpinLockRelease(&walrcv->mutex);
794 : 0 : proc_exit(1);
795 : : }
796 : 13 : SpinLockRelease(&walrcv->mutex);
797 : :
798 : 13 : (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
799 : : WAIT_EVENT_WAL_RECEIVER_WAIT_START);
800 : : }
801 : :
802 [ + - ]: 13 : if (update_process_title)
803 : : {
804 : : char activitymsg[50];
805 : :
806 : 13 : snprintf(activitymsg, sizeof(activitymsg), "restarting at %X/%08X",
807 : 13 : LSN_FORMAT_ARGS(*startpoint));
808 : 13 : set_ps_display(activitymsg);
809 : : }
810 : 13 : }
811 : :
812 : : /*
813 : : * Fetch any missing timeline history files between 'first' and 'last'
814 : : * (inclusive) from the server.
815 : : */
816 : : static void
817 : 187 : WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
818 : : {
819 : : TimeLineID tli;
820 : :
821 [ + + ]: 397 : for (tli = first; tli <= last; tli++)
822 : : {
823 : : /* there's no history file for timeline 1 */
824 [ + + + + ]: 210 : if (tli != 1 && !existsTimeLineHistory(tli))
825 : : {
826 : : char *fname;
827 : : char *content;
828 : : size_t len;
829 : : char expectedfname[MAXFNAMELEN];
830 : :
831 [ + - ]: 12 : ereport(LOG,
832 : : (errmsg("fetching timeline history file for timeline %u from primary server",
833 : : tli)));
834 : :
835 : 12 : walrcv_readtimelinehistoryfile(wrconn, tli, &fname, &content, &len);
836 : :
837 : : /*
838 : : * Check that the filename on the primary matches what we
839 : : * calculated ourselves. This is just a sanity check, it should
840 : : * always match.
841 : : */
842 : 12 : TLHistoryFileName(expectedfname, tli);
843 [ - + ]: 12 : if (strcmp(fname, expectedfname) != 0)
844 [ # # ]: 0 : ereport(ERROR,
845 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
846 : : errmsg_internal("primary reported unexpected file name for timeline history file of timeline %u",
847 : : tli)));
848 : :
849 : : /*
850 : : * Write the file to pg_wal.
851 : : */
852 : 12 : writeTimeLineHistoryFile(tli, content, len);
853 : :
854 : : /*
855 : : * Mark the streamed history file as ready for archiving if
856 : : * archive_mode is always.
857 : : */
858 [ + - ]: 12 : if (XLogArchiveMode != ARCHIVE_MODE_ALWAYS)
859 : 12 : XLogArchiveForceDone(fname);
860 : : else
861 : 0 : XLogArchiveNotify(fname);
862 : :
863 : 12 : pfree(fname);
864 : 12 : pfree(content);
865 : : }
866 : : }
867 : 187 : }
868 : :
869 : : /*
870 : : * Mark us as STOPPED in shared memory at exit.
871 : : */
872 : : static void
873 : 280 : WalRcvDie(int code, Datum arg)
874 : : {
875 : 280 : WalRcvData *walrcv = WalRcv;
876 : 280 : TimeLineID *startpointTLI_p = (TimeLineID *) DatumGetPointer(arg);
877 : :
878 : : Assert(*startpointTLI_p != 0);
879 : :
880 : : /* Ensure that all WAL records received are flushed to disk */
881 : 280 : XLogWalRcvFlush(true, *startpointTLI_p);
882 : :
883 : : /* Mark ourselves inactive in shared memory */
884 : 280 : SpinLockAcquire(&walrcv->mutex);
885 : : Assert(walrcv->walRcvState == WALRCV_STREAMING ||
886 : : walrcv->walRcvState == WALRCV_CONNECTING ||
887 : : walrcv->walRcvState == WALRCV_RESTARTING ||
888 : : walrcv->walRcvState == WALRCV_STARTING ||
889 : : walrcv->walRcvState == WALRCV_WAITING ||
890 : : walrcv->walRcvState == WALRCV_STOPPING);
891 : : Assert(walrcv->pid == MyProcPid);
892 : 280 : walrcv->walRcvState = WALRCV_STOPPED;
893 : 280 : walrcv->pid = 0;
894 : 280 : walrcv->procno = INVALID_PROC_NUMBER;
895 : 280 : walrcv->ready_to_display = false;
896 : 280 : SpinLockRelease(&walrcv->mutex);
897 : :
898 : 280 : ConditionVariableBroadcast(&walrcv->walRcvStoppedCV);
899 : :
900 : : /* Terminate the connection gracefully. */
901 [ + + ]: 280 : if (wrconn != NULL)
902 : 161 : walrcv_disconnect(wrconn);
903 : :
904 : : /* Wake up the startup process to notice promptly that we're gone */
905 : 280 : WakeupRecovery();
906 : 280 : }
907 : :
908 : : /*
909 : : * Accept the message from XLOG stream, and process it.
910 : : */
911 : : static void
912 : 108793 : XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len, TimeLineID tli)
913 : : {
914 : : int hdrlen;
915 : : XLogRecPtr dataStart;
916 : : XLogRecPtr walEnd;
917 : : TimestampTz sendTime;
918 : : bool replyRequested;
919 : :
920 [ + + - ]: 108793 : switch (type)
921 : : {
922 : 108613 : case PqReplMsg_WALData:
923 : : {
924 : : StringInfoData incoming_message;
925 : :
926 : 108613 : hdrlen = sizeof(int64) + sizeof(int64) + sizeof(int64);
927 [ - + ]: 108613 : if (len < hdrlen)
928 [ # # ]: 0 : ereport(ERROR,
929 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
930 : : errmsg_internal("invalid WAL message received from primary")));
931 : :
932 : : /* initialize a StringInfo with the given buffer */
933 : 108613 : initReadOnlyStringInfo(&incoming_message, buf, hdrlen);
934 : :
935 : : /* read the fields */
936 : 108613 : dataStart = pq_getmsgint64(&incoming_message);
937 : 108613 : walEnd = pq_getmsgint64(&incoming_message);
938 : 108613 : sendTime = pq_getmsgint64(&incoming_message);
939 : 108613 : ProcessWalSndrMessage(walEnd, sendTime);
940 : :
941 : 108613 : buf += hdrlen;
942 : 108613 : len -= hdrlen;
943 : 108613 : XLogWalRcvWrite(buf, len, dataStart, tli);
944 : 108613 : break;
945 : : }
946 : 180 : case PqReplMsg_Keepalive:
947 : : {
948 : : StringInfoData incoming_message;
949 : :
950 : 180 : hdrlen = sizeof(int64) + sizeof(int64) + sizeof(char);
951 [ - + ]: 180 : if (len != hdrlen)
952 [ # # ]: 0 : ereport(ERROR,
953 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
954 : : errmsg_internal("invalid keepalive message received from primary")));
955 : :
956 : : /* initialize a StringInfo with the given buffer */
957 : 180 : initReadOnlyStringInfo(&incoming_message, buf, hdrlen);
958 : :
959 : : /* read the fields */
960 : 180 : walEnd = pq_getmsgint64(&incoming_message);
961 : 180 : sendTime = pq_getmsgint64(&incoming_message);
962 : 180 : replyRequested = pq_getmsgbyte(&incoming_message);
963 : :
964 : 180 : ProcessWalSndrMessage(walEnd, sendTime);
965 : :
966 : : /* If the primary requested a reply, send one immediately */
967 [ + - ]: 180 : if (replyRequested)
968 : 180 : XLogWalRcvSendReply(true, false, false);
969 : 180 : break;
970 : : }
971 : 0 : default:
972 [ # # ]: 0 : ereport(ERROR,
973 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
974 : : errmsg_internal("invalid replication message type %d",
975 : : type)));
976 : : }
977 : 108793 : }
978 : :
979 : : /*
980 : : * Write XLOG data to disk.
981 : : */
982 : : static void
983 : 108613 : XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr, TimeLineID tli)
984 : : {
985 : : int startoff;
986 : : ssize_t byteswritten;
987 : : instr_time start;
988 : :
989 : : Assert(tli != 0);
990 : :
991 [ + + ]: 217680 : while (nbytes > 0)
992 : : {
993 : : int segbytes;
994 : :
995 : : /* Close the current segment if it's completed */
996 [ + + + + ]: 109067 : if (recvFile >= 0 && !XLByteInSeg(recptr, recvSegNo, wal_segment_size))
997 : 454 : XLogWalRcvClose(recptr, tli);
998 : :
999 [ + + ]: 109067 : if (recvFile < 0)
1000 : : {
1001 : : /* Create/use new log file */
1002 : 913 : XLByteToSeg(recptr, recvSegNo, wal_segment_size);
1003 : 913 : recvFile = XLogFileInit(recvSegNo, tli);
1004 : 913 : recvFileTLI = tli;
1005 : : }
1006 : :
1007 : : /* Calculate the start offset of the received logs */
1008 : 109067 : startoff = XLogSegmentOffset(recptr, wal_segment_size);
1009 : :
1010 [ + + ]: 109067 : if (startoff + nbytes > wal_segment_size)
1011 : 454 : segbytes = wal_segment_size - startoff;
1012 : : else
1013 : 108613 : segbytes = nbytes;
1014 : :
1015 : : /* OK to write the logs */
1016 : 109067 : errno = 0;
1017 : :
1018 : : /*
1019 : : * Measure I/O timing to write WAL data, for pg_stat_io.
1020 : : */
1021 : 109067 : start = pgstat_prepare_io_time(track_wal_io_timing);
1022 : :
1023 : 109067 : pgstat_report_wait_start(WAIT_EVENT_WAL_WRITE);
1024 : 109067 : byteswritten = pg_pwrite(recvFile, buf, segbytes, (pgoff_t) startoff);
1025 : 109067 : pgstat_report_wait_end();
1026 : :
1027 [ - + ]: 109067 : if (byteswritten <= 0)
1028 : : {
1029 : : char xlogfname[MAXFNAMELEN];
1030 : : int save_errno;
1031 : :
1032 : : /* if write didn't set errno, assume no disk space */
1033 [ # # ]: 0 : if (errno == 0)
1034 : 0 : errno = ENOSPC;
1035 : :
1036 : 0 : save_errno = errno;
1037 : 0 : XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
1038 : 0 : errno = save_errno;
1039 [ # # ]: 0 : ereport(PANIC,
1040 : : (errcode_for_file_access(),
1041 : : errmsg("could not write to WAL segment %s "
1042 : : "at offset %d, length %d: %m",
1043 : : xlogfname, startoff, segbytes)));
1044 : : }
1045 : :
1046 : 109067 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL,
1047 : : IOOP_WRITE, start, 1, byteswritten);
1048 : :
1049 : : /* Update state for write */
1050 : 109067 : recptr += byteswritten;
1051 : :
1052 : 109067 : nbytes -= byteswritten;
1053 : 109067 : buf += byteswritten;
1054 : :
1055 : 109067 : LogstreamResult.Write = recptr;
1056 : : }
1057 : :
1058 : : /* Update shared-memory status */
1059 : 108613 : pg_atomic_write_membarrier_u64(&WalRcv->writtenUpto, LogstreamResult.Write);
1060 : :
1061 : : /*
1062 : : * Wake up processes waiting for standby write LSN to reach current write
1063 : : * position.
1064 : : */
1065 : 108613 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE, LogstreamResult.Write);
1066 : :
1067 : : /*
1068 : : * Close the current segment if it's fully written up in the last cycle of
1069 : : * the loop, to create its archive notification file soon. Otherwise WAL
1070 : : * archiving of the segment will be delayed until any data in the next
1071 : : * segment is received and written.
1072 : : */
1073 [ + - + + ]: 108613 : if (recvFile >= 0 && !XLByteInSeg(recptr, recvSegNo, wal_segment_size))
1074 : 308 : XLogWalRcvClose(recptr, tli);
1075 : 108613 : }
1076 : :
1077 : : /*
1078 : : * Flush the log to disk.
1079 : : *
1080 : : * If we're in the midst of dying, it's unwise to do anything that might throw
1081 : : * an error, so we skip sending a reply in that case.
1082 : : */
1083 : : static void
1084 : 44839 : XLogWalRcvFlush(bool dying, TimeLineID tli)
1085 : : {
1086 : : Assert(tli != 0);
1087 : :
1088 [ + + ]: 44839 : if (LogstreamResult.Flush < LogstreamResult.Write)
1089 : : {
1090 : 44149 : WalRcvData *walrcv = WalRcv;
1091 : :
1092 : 44149 : issue_xlog_fsync(recvFile, recvSegNo, tli);
1093 : :
1094 : 44149 : LogstreamResult.Flush = LogstreamResult.Write;
1095 : :
1096 : : /* Update shared-memory status */
1097 : 44149 : SpinLockAcquire(&walrcv->mutex);
1098 [ + - ]: 44149 : if (walrcv->flushedUpto < LogstreamResult.Flush)
1099 : : {
1100 : 44149 : walrcv->latestChunkStart = walrcv->flushedUpto;
1101 : 44149 : walrcv->flushedUpto = LogstreamResult.Flush;
1102 : 44149 : walrcv->receivedTLI = tli;
1103 : : }
1104 : 44149 : SpinLockRelease(&walrcv->mutex);
1105 : :
1106 : : /*
1107 : : * Wake up processes waiting for standby flush LSN to reach current
1108 : : * flush position.
1109 : : */
1110 : 44149 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH, LogstreamResult.Flush);
1111 : :
1112 : : /* Signal the startup process and walsender that new WAL has arrived */
1113 : 44149 : WakeupRecovery();
1114 [ + - + - ]: 44149 : if (AllowCascadeReplication())
1115 : 44149 : WalSndWakeup(true, false);
1116 : :
1117 : : /* Report XLOG streaming progress in PS display */
1118 [ + - ]: 44149 : if (update_process_title)
1119 : : {
1120 : : char activitymsg[50];
1121 : :
1122 : 44149 : snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%08X",
1123 : 44149 : LSN_FORMAT_ARGS(LogstreamResult.Write));
1124 : 44149 : set_ps_display(activitymsg);
1125 : : }
1126 : :
1127 : : /* Also let the primary know that we made some progress */
1128 [ + - ]: 44149 : if (!dying)
1129 : : {
1130 : 44149 : XLogWalRcvSendReply(false, false, false);
1131 : 44148 : XLogWalRcvSendHSFeedback(false);
1132 : : }
1133 : : }
1134 : 44838 : }
1135 : :
1136 : : /*
1137 : : * Close the current segment.
1138 : : *
1139 : : * Flush the segment to disk before closing it. Otherwise we have to
1140 : : * reopen and fsync it later.
1141 : : *
1142 : : * Create an archive notification file since the segment is known completed.
1143 : : */
1144 : : static void
1145 : 762 : XLogWalRcvClose(XLogRecPtr recptr, TimeLineID tli)
1146 : : {
1147 : : char xlogfname[MAXFNAMELEN];
1148 : :
1149 : : Assert(recvFile >= 0 && !XLByteInSeg(recptr, recvSegNo, wal_segment_size));
1150 : : Assert(tli != 0);
1151 : :
1152 : : /*
1153 : : * fsync() and close current file before we switch to next one. We would
1154 : : * otherwise have to reopen this file to fsync it later
1155 : : */
1156 : 762 : XLogWalRcvFlush(false, tli);
1157 : :
1158 : 762 : XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
1159 : :
1160 : : /*
1161 : : * XLOG segment files will be re-read by recovery in startup process soon,
1162 : : * so we don't advise the OS to release cache pages associated with the
1163 : : * file like XLogFileClose() does.
1164 : : */
1165 [ - + ]: 762 : if (close(recvFile) != 0)
1166 [ # # ]: 0 : ereport(PANIC,
1167 : : (errcode_for_file_access(),
1168 : : errmsg("could not close WAL segment %s: %m",
1169 : : xlogfname)));
1170 : :
1171 : : /*
1172 : : * Create .done file forcibly to prevent the streamed segment from being
1173 : : * archived later.
1174 : : */
1175 [ + - ]: 762 : if (XLogArchiveMode != ARCHIVE_MODE_ALWAYS)
1176 : 762 : XLogArchiveForceDone(xlogfname);
1177 : : else
1178 : 0 : XLogArchiveNotify(xlogfname);
1179 : :
1180 : 762 : recvFile = -1;
1181 : 762 : }
1182 : :
1183 : : /*
1184 : : * Send reply message to primary, indicating our current WAL locations and
1185 : : * time.
1186 : : *
1187 : : * The message is sent if 'force' is set, if enough time has passed since the
1188 : : * last update to reach wal_receiver_status_interval, or if WAL locations have
1189 : : * advanced since the previous status update. If wal_receiver_status_interval
1190 : : * is disabled and 'force' is false, this function does nothing. Set 'force' to
1191 : : * send the message unconditionally.
1192 : : *
1193 : : * Whether WAL locations are considered "advanced" depends on 'checkApply'.
1194 : : * If 'checkApply' is false, only the write and flush locations are checked.
1195 : : * This should be used when the call is triggered by write/flush activity
1196 : : * (e.g., after walreceiver writes or flushes WAL), and avoids the
1197 : : * apply-location check, which requires a spinlock. If 'checkApply' is true,
1198 : : * the apply location is also considered. This should be used when the apply
1199 : : * location is expected to advance (e.g., when the startup process requests
1200 : : * an apply notification).
1201 : : *
1202 : : * If 'requestReply' is true, requests the server to reply immediately upon
1203 : : * receiving this message. This is used for heartbeats, when approaching
1204 : : * wal_receiver_timeout.
1205 : : */
1206 : : static void
1207 : 102465 : XLogWalRcvSendReply(bool force, bool requestReply, bool checkApply)
1208 : : {
1209 : : static XLogRecPtr writePtr = InvalidXLogRecPtr;
1210 : : static XLogRecPtr flushPtr = InvalidXLogRecPtr;
1211 : : static XLogRecPtr applyPtr = InvalidXLogRecPtr;
1212 : 102465 : XLogRecPtr latestApplyPtr = InvalidXLogRecPtr;
1213 : : TimestampTz now;
1214 : :
1215 : : /*
1216 : : * If the user doesn't want status to be reported to the primary, be sure
1217 : : * to exit before doing anything at all.
1218 : : */
1219 [ + + - + ]: 102465 : if (!force && wal_receiver_status_interval <= 0)
1220 : 0 : return;
1221 : :
1222 : : /* Get current timestamp. */
1223 : 102465 : now = GetCurrentTimestamp();
1224 : :
1225 : : /*
1226 : : * We can compare the write and flush positions to the last message we
1227 : : * sent without taking any lock, but the apply position requires a spin
1228 : : * lock, so we don't check that unless it is expected to advance since the
1229 : : * previous update, i.e., when 'checkApply' is true.
1230 : : */
1231 [ + + + + ]: 102465 : if (!force && now < wakeup[WALRCV_WAKEUP_REPLY])
1232 : : {
1233 [ + + ]: 102111 : if (checkApply)
1234 : 14172 : latestApplyPtr = GetXLogReplayRecPtr(NULL);
1235 : :
1236 [ + + ]: 102111 : if (writePtr == LogstreamResult.Write
1237 [ + + ]: 57849 : && flushPtr == LogstreamResult.Flush
1238 [ + + + + ]: 14462 : && (!checkApply || applyPtr == latestApplyPtr))
1239 : 3453 : return;
1240 : : }
1241 : :
1242 : : /* Make sure we wake up when it's time to send another reply. */
1243 : 99012 : WalRcvComputeNextWakeup(WALRCV_WAKEUP_REPLY, now);
1244 : :
1245 : : /* Construct a new message */
1246 : 99012 : writePtr = LogstreamResult.Write;
1247 : 99012 : flushPtr = LogstreamResult.Flush;
1248 : 99012 : applyPtr = XLogRecPtrIsValid(latestApplyPtr) ?
1249 [ + + ]: 99012 : latestApplyPtr : GetXLogReplayRecPtr(NULL);
1250 : :
1251 : 99012 : resetStringInfo(&reply_message);
1252 : 99012 : pq_sendbyte(&reply_message, PqReplMsg_StandbyStatusUpdate);
1253 : 99012 : pq_sendint64(&reply_message, writePtr);
1254 : 99012 : pq_sendint64(&reply_message, flushPtr);
1255 : 99012 : pq_sendint64(&reply_message, applyPtr);
1256 : 99012 : pq_sendint64(&reply_message, GetCurrentTimestamp());
1257 : 99012 : pq_sendbyte(&reply_message, requestReply ? 1 : 0);
1258 : :
1259 : : /* Send it */
1260 [ + + - + ]: 99012 : elog(DEBUG2, "sending write %X/%08X flush %X/%08X apply %X/%08X%s",
1261 : : LSN_FORMAT_ARGS(writePtr),
1262 : : LSN_FORMAT_ARGS(flushPtr),
1263 : : LSN_FORMAT_ARGS(applyPtr),
1264 : : requestReply ? " (reply requested)" : "");
1265 : :
1266 : 99012 : walrcv_send(wrconn, reply_message.data, reply_message.len);
1267 : : }
1268 : :
1269 : : /*
1270 : : * Send hot standby feedback message to primary, plus the current time,
1271 : : * in case they don't have a watch.
1272 : : *
1273 : : * If the user disables feedback, send one final message to tell sender
1274 : : * to forget about the xmin on this standby. We also send this message
1275 : : * on first connect because a previous connection might have set xmin
1276 : : * on a replication slot. (If we're not using a slot it's harmless to
1277 : : * send a feedback message explicitly setting InvalidTransactionId).
1278 : : */
1279 : : static void
1280 : 44357 : XLogWalRcvSendHSFeedback(bool immed)
1281 : : {
1282 : : TimestampTz now;
1283 : : FullTransactionId nextFullXid;
1284 : : TransactionId nextXid;
1285 : : uint32 xmin_epoch,
1286 : : catalog_xmin_epoch;
1287 : : TransactionId xmin,
1288 : : catalog_xmin;
1289 : :
1290 : : /* initially true so we always send at least one feedback message */
1291 : : static bool primary_has_standby_xmin = true;
1292 : :
1293 : : /*
1294 : : * If the user doesn't want status to be reported to the primary, be sure
1295 : : * to exit before doing anything at all.
1296 : : */
1297 [ + - + + ]: 44357 : if ((wal_receiver_status_interval <= 0 || !hot_standby_feedback) &&
1298 [ + + ]: 43780 : !primary_has_standby_xmin)
1299 : 44171 : return;
1300 : :
1301 : : /* Get current timestamp. */
1302 : 746 : now = GetCurrentTimestamp();
1303 : :
1304 : : /* Send feedback at most once per wal_receiver_status_interval. */
1305 [ + + + + ]: 746 : if (!immed && now < wakeup[WALRCV_WAKEUP_HSFEEDBACK])
1306 : 559 : return;
1307 : :
1308 : : /* Make sure we wake up when it's time to send feedback again. */
1309 : 187 : WalRcvComputeNextWakeup(WALRCV_WAKEUP_HSFEEDBACK, now);
1310 : :
1311 : : /*
1312 : : * If Hot Standby is not yet accepting connections there is nothing to
1313 : : * send. Check this after the interval has expired to reduce number of
1314 : : * calls.
1315 : : *
1316 : : * Bailing out here also ensures that we don't send feedback until we've
1317 : : * read our own replication slot state, so we don't tell the primary to
1318 : : * discard needed xmin or catalog_xmin from any slots that may exist on
1319 : : * this replica.
1320 : : */
1321 [ + + ]: 187 : if (!HotStandbyActive())
1322 : 1 : return;
1323 : :
1324 : : /*
1325 : : * Make the expensive call to get the oldest xmin once we are certain
1326 : : * everything else has been checked.
1327 : : */
1328 [ + + ]: 186 : if (hot_standby_feedback)
1329 : : {
1330 : 56 : GetReplicationHorizons(&xmin, &catalog_xmin);
1331 : : }
1332 : : else
1333 : : {
1334 : 130 : xmin = InvalidTransactionId;
1335 : 130 : catalog_xmin = InvalidTransactionId;
1336 : : }
1337 : :
1338 : : /*
1339 : : * Get epoch and adjust if nextXid and oldestXmin are different sides of
1340 : : * the epoch boundary.
1341 : : */
1342 : 186 : nextFullXid = ReadNextFullTransactionId();
1343 : 186 : nextXid = XidFromFullTransactionId(nextFullXid);
1344 : 186 : xmin_epoch = EpochFromFullTransactionId(nextFullXid);
1345 : 186 : catalog_xmin_epoch = xmin_epoch;
1346 [ - + ]: 186 : if (nextXid < xmin)
1347 : 0 : xmin_epoch--;
1348 [ - + ]: 186 : if (nextXid < catalog_xmin)
1349 : 0 : catalog_xmin_epoch--;
1350 : :
1351 [ + + ]: 186 : elog(DEBUG2, "sending hot standby feedback xmin %u epoch %u catalog_xmin %u catalog_xmin_epoch %u",
1352 : : xmin, xmin_epoch, catalog_xmin, catalog_xmin_epoch);
1353 : :
1354 : : /* Construct the message and send it. */
1355 : 186 : resetStringInfo(&reply_message);
1356 : 186 : pq_sendbyte(&reply_message, PqReplMsg_HotStandbyFeedback);
1357 : 186 : pq_sendint64(&reply_message, GetCurrentTimestamp());
1358 : 186 : pq_sendint32(&reply_message, xmin);
1359 : 186 : pq_sendint32(&reply_message, xmin_epoch);
1360 : 186 : pq_sendint32(&reply_message, catalog_xmin);
1361 : 186 : pq_sendint32(&reply_message, catalog_xmin_epoch);
1362 : 186 : walrcv_send(wrconn, reply_message.data, reply_message.len);
1363 [ + + - + ]: 186 : if (TransactionIdIsValid(xmin) || TransactionIdIsValid(catalog_xmin))
1364 : 56 : primary_has_standby_xmin = true;
1365 : : else
1366 : 130 : primary_has_standby_xmin = false;
1367 : : }
1368 : :
1369 : : /*
1370 : : * Update shared memory status upon receiving a message from primary.
1371 : : *
1372 : : * 'walEnd' and 'sendTime' are the end-of-WAL and timestamp of the latest
1373 : : * message, reported by primary.
1374 : : */
1375 : : static void
1376 : 108793 : ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime)
1377 : : {
1378 : 108793 : WalRcvData *walrcv = WalRcv;
1379 : 108793 : TimestampTz lastMsgReceiptTime = GetCurrentTimestamp();
1380 : :
1381 : : /* Update shared-memory status */
1382 : 108793 : SpinLockAcquire(&walrcv->mutex);
1383 [ + + ]: 108793 : if (walrcv->latestWalEnd < walEnd)
1384 : 23358 : walrcv->latestWalEndTime = sendTime;
1385 : 108793 : walrcv->latestWalEnd = walEnd;
1386 : 108793 : walrcv->lastMsgSendTime = sendTime;
1387 : 108793 : walrcv->lastMsgReceiptTime = lastMsgReceiptTime;
1388 : 108793 : SpinLockRelease(&walrcv->mutex);
1389 : :
1390 [ + + ]: 108793 : if (message_level_is_interesting(DEBUG2))
1391 : : {
1392 : : char *sendtime;
1393 : : char *receipttime;
1394 : : int applyDelay;
1395 : :
1396 : : /* Copy because timestamptz_to_str returns a static buffer */
1397 : 409 : sendtime = pstrdup(timestamptz_to_str(sendTime));
1398 : 409 : receipttime = pstrdup(timestamptz_to_str(lastMsgReceiptTime));
1399 : 409 : applyDelay = GetReplicationApplyDelay();
1400 : :
1401 : : /* apply delay is not available */
1402 [ + + ]: 409 : if (applyDelay == -1)
1403 [ + - ]: 1 : elog(DEBUG2, "sendtime %s receipttime %s replication apply delay (N/A) transfer latency %d ms",
1404 : : sendtime,
1405 : : receipttime,
1406 : : GetReplicationTransferLatency());
1407 : : else
1408 [ + - ]: 408 : elog(DEBUG2, "sendtime %s receipttime %s replication apply delay %d ms transfer latency %d ms",
1409 : : sendtime,
1410 : : receipttime,
1411 : : applyDelay,
1412 : : GetReplicationTransferLatency());
1413 : :
1414 : 409 : pfree(sendtime);
1415 : 409 : pfree(receipttime);
1416 : : }
1417 : 108793 : }
1418 : :
1419 : : /*
1420 : : * Compute the next wakeup time for a given wakeup reason. Can be called to
1421 : : * initialize a wakeup time, to adjust it for the next wakeup, or to
1422 : : * reinitialize it when GUCs have changed. We ask the caller to pass in the
1423 : : * value of "now" because this frequently avoids multiple calls of
1424 : : * GetCurrentTimestamp(). It had better be a reasonably up-to-date value
1425 : : * though.
1426 : : */
1427 : : static void
1428 : 317597 : WalRcvComputeNextWakeup(WalRcvWakeupReason reason, TimestampTz now)
1429 : : {
1430 [ + + + + : 317597 : switch (reason)
- ]
1431 : : {
1432 : 108996 : case WALRCV_WAKEUP_TERMINATE:
1433 [ - + ]: 108996 : if (wal_receiver_timeout <= 0)
1434 : 0 : wakeup[reason] = TIMESTAMP_INFINITY;
1435 : : else
1436 : 108996 : wakeup[reason] = TimestampTzPlusMilliseconds(now, wal_receiver_timeout);
1437 : 108996 : break;
1438 : 108996 : case WALRCV_WAKEUP_PING:
1439 [ - + ]: 108996 : if (wal_receiver_timeout <= 0)
1440 : 0 : wakeup[reason] = TIMESTAMP_INFINITY;
1441 : : else
1442 : 108996 : wakeup[reason] = TimestampTzPlusMilliseconds(now, wal_receiver_timeout / 2);
1443 : 108996 : break;
1444 : 390 : case WALRCV_WAKEUP_HSFEEDBACK:
1445 [ + + - + ]: 390 : if (!hot_standby_feedback || wal_receiver_status_interval <= 0)
1446 : 283 : wakeup[reason] = TIMESTAMP_INFINITY;
1447 : : else
1448 : 107 : wakeup[reason] = TimestampTzPlusSeconds(now, wal_receiver_status_interval);
1449 : 390 : break;
1450 : 99215 : case WALRCV_WAKEUP_REPLY:
1451 [ - + ]: 99215 : if (wal_receiver_status_interval <= 0)
1452 : 0 : wakeup[reason] = TIMESTAMP_INFINITY;
1453 : : else
1454 : 99215 : wakeup[reason] = TimestampTzPlusSeconds(now, wal_receiver_status_interval);
1455 : 99215 : break;
1456 : : /* there's intentionally no default: here */
1457 : : }
1458 : 317597 : }
1459 : :
1460 : : /*
1461 : : * Wake up the walreceiver main loop.
1462 : : *
1463 : : * This is called by the startup process whenever interesting xlog records
1464 : : * are applied, so that walreceiver can check if it needs to send an apply
1465 : : * notification back to the primary which may be waiting in a COMMIT with
1466 : : * synchronous_commit = remote_apply.
1467 : : */
1468 : : void
1469 : 14103 : WalRcvRequestApplyReply(void)
1470 : : {
1471 : : ProcNumber procno;
1472 : :
1473 : 14103 : WalRcv->apply_reply_requested = true;
1474 : : /* fetching the proc number is probably atomic, but don't rely on it */
1475 : 14103 : SpinLockAcquire(&WalRcv->mutex);
1476 : 14103 : procno = WalRcv->procno;
1477 : 14103 : SpinLockRelease(&WalRcv->mutex);
1478 [ + + ]: 14103 : if (procno != INVALID_PROC_NUMBER)
1479 : 13899 : SetLatch(&GetPGProcByNumber(procno)->procLatch);
1480 : 14103 : }
1481 : :
1482 : : /*
1483 : : * Return a string constant representing the state. This is used
1484 : : * in system functions and views, and should *not* be translated.
1485 : : */
1486 : : static const char *
1487 : 18 : WalRcvGetStateString(WalRcvState state)
1488 : : {
1489 [ - - - + : 18 : switch (state)
- - - - ]
1490 : : {
1491 : 0 : case WALRCV_STOPPED:
1492 : 0 : return "stopped";
1493 : 0 : case WALRCV_STARTING:
1494 : 0 : return "starting";
1495 : 0 : case WALRCV_CONNECTING:
1496 : 0 : return "connecting";
1497 : 18 : case WALRCV_STREAMING:
1498 : 18 : return "streaming";
1499 : 0 : case WALRCV_WAITING:
1500 : 0 : return "waiting";
1501 : 0 : case WALRCV_RESTARTING:
1502 : 0 : return "restarting";
1503 : 0 : case WALRCV_STOPPING:
1504 : 0 : return "stopping";
1505 : : }
1506 : 0 : return "UNKNOWN";
1507 : : }
1508 : :
1509 : : /*
1510 : : * Returns activity of WAL receiver, including pid, state and xlog locations
1511 : : * received from the WAL sender of another server.
1512 : : */
1513 : : Datum
1514 : 30 : pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
1515 : : {
1516 : : TupleDesc tupdesc;
1517 : : Datum *values;
1518 : : bool *nulls;
1519 : : int pid;
1520 : : bool ready_to_display;
1521 : : WalRcvState state;
1522 : : XLogRecPtr receive_start_lsn;
1523 : : TimeLineID receive_start_tli;
1524 : : XLogRecPtr written_lsn;
1525 : : XLogRecPtr flushed_lsn;
1526 : : TimeLineID received_tli;
1527 : : TimestampTz last_send_time;
1528 : : TimestampTz last_receipt_time;
1529 : : XLogRecPtr latest_end_lsn;
1530 : : TimestampTz latest_end_time;
1531 : : char sender_host[NI_MAXHOST];
1532 : 30 : int sender_port = 0;
1533 : : char slotname[NAMEDATALEN];
1534 : : char conninfo[MAXCONNINFO];
1535 : :
1536 : : /* Take a lock to ensure value consistency */
1537 : 30 : SpinLockAcquire(&WalRcv->mutex);
1538 : 30 : pid = (int) WalRcv->pid;
1539 : 30 : ready_to_display = WalRcv->ready_to_display;
1540 : 30 : state = WalRcv->walRcvState;
1541 : 30 : receive_start_lsn = WalRcv->receiveStart;
1542 : 30 : receive_start_tli = WalRcv->receiveStartTLI;
1543 : 30 : flushed_lsn = WalRcv->flushedUpto;
1544 : 30 : received_tli = WalRcv->receivedTLI;
1545 : 30 : last_send_time = WalRcv->lastMsgSendTime;
1546 : 30 : last_receipt_time = WalRcv->lastMsgReceiptTime;
1547 : 30 : latest_end_lsn = WalRcv->latestWalEnd;
1548 : 30 : latest_end_time = WalRcv->latestWalEndTime;
1549 : 30 : strlcpy(slotname, WalRcv->slotname, sizeof(slotname));
1550 : 30 : strlcpy(sender_host, WalRcv->sender_host, sizeof(sender_host));
1551 : 30 : sender_port = WalRcv->sender_port;
1552 : 30 : strlcpy(conninfo, WalRcv->conninfo, sizeof(conninfo));
1553 : 30 : SpinLockRelease(&WalRcv->mutex);
1554 : :
1555 : : /*
1556 : : * No WAL receiver (or not ready yet), just return a tuple with NULL
1557 : : * values
1558 : : */
1559 [ + + - + ]: 30 : if (pid == 0 || !ready_to_display)
1560 : 12 : PG_RETURN_NULL();
1561 : :
1562 : : /*
1563 : : * Read "writtenUpto" without holding a spinlock. Note that it may not be
1564 : : * consistent with the other shared variables of the WAL receiver
1565 : : * protected by a spinlock, but this should not be used for data integrity
1566 : : * checks.
1567 : : */
1568 : 18 : written_lsn = pg_atomic_read_u64(&WalRcv->writtenUpto);
1569 : :
1570 : : /* determine result type */
1571 [ - + ]: 18 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1572 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
1573 : :
1574 : 18 : values = palloc0_array(Datum, tupdesc->natts);
1575 : 18 : nulls = palloc0_array(bool, tupdesc->natts);
1576 : :
1577 : : /* Fetch values */
1578 : 18 : values[0] = Int32GetDatum(pid);
1579 : :
1580 [ - + ]: 18 : if (!has_privs_of_role(GetUserId(), ROLE_PG_READ_ALL_STATS))
1581 : : {
1582 : : /*
1583 : : * Only superusers and roles with privileges of pg_read_all_stats can
1584 : : * see details. Other users only get the pid value to know whether it
1585 : : * is a WAL receiver, but no details.
1586 : : */
1587 : 0 : memset(&nulls[1], true, sizeof(bool) * (tupdesc->natts - 1));
1588 : : }
1589 : : else
1590 : : {
1591 : 18 : values[1] = CStringGetTextDatum(WalRcvGetStateString(state));
1592 : :
1593 [ - + ]: 18 : if (!XLogRecPtrIsValid(receive_start_lsn))
1594 : 0 : nulls[2] = true;
1595 : : else
1596 : 18 : values[2] = LSNGetDatum(receive_start_lsn);
1597 : 18 : values[3] = Int32GetDatum(receive_start_tli);
1598 [ - + ]: 18 : if (!XLogRecPtrIsValid(written_lsn))
1599 : 0 : nulls[4] = true;
1600 : : else
1601 : 18 : values[4] = LSNGetDatum(written_lsn);
1602 [ - + ]: 18 : if (!XLogRecPtrIsValid(flushed_lsn))
1603 : 0 : nulls[5] = true;
1604 : : else
1605 : 18 : values[5] = LSNGetDatum(flushed_lsn);
1606 : 18 : values[6] = Int32GetDatum(received_tli);
1607 [ - + ]: 18 : if (last_send_time == 0)
1608 : 0 : nulls[7] = true;
1609 : : else
1610 : 18 : values[7] = TimestampTzGetDatum(last_send_time);
1611 [ - + ]: 18 : if (last_receipt_time == 0)
1612 : 0 : nulls[8] = true;
1613 : : else
1614 : 18 : values[8] = TimestampTzGetDatum(last_receipt_time);
1615 [ - + ]: 18 : if (!XLogRecPtrIsValid(latest_end_lsn))
1616 : 0 : nulls[9] = true;
1617 : : else
1618 : 18 : values[9] = LSNGetDatum(latest_end_lsn);
1619 [ - + ]: 18 : if (latest_end_time == 0)
1620 : 0 : nulls[10] = true;
1621 : : else
1622 : 18 : values[10] = TimestampTzGetDatum(latest_end_time);
1623 [ + + ]: 18 : if (*slotname == '\0')
1624 : 16 : nulls[11] = true;
1625 : : else
1626 : 2 : values[11] = CStringGetTextDatum(slotname);
1627 [ - + ]: 18 : if (*sender_host == '\0')
1628 : 0 : nulls[12] = true;
1629 : : else
1630 : 18 : values[12] = CStringGetTextDatum(sender_host);
1631 [ - + ]: 18 : if (sender_port == 0)
1632 : 0 : nulls[13] = true;
1633 : : else
1634 : 18 : values[13] = Int32GetDatum(sender_port);
1635 [ - + ]: 18 : if (*conninfo == '\0')
1636 : 0 : nulls[14] = true;
1637 : : else
1638 : 18 : values[14] = CStringGetTextDatum(conninfo);
1639 : : }
1640 : :
1641 : : /* Returns the record as Datum */
1642 : 18 : PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
1643 : : }
|