Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * walsender.c
4 : : *
5 : : * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
6 : : * care of sending XLOG from the primary server to a single recipient.
7 : : * (Note that there can be more than one walsender process concurrently.)
8 : : * It is started by the postmaster when the walreceiver of a standby server
9 : : * connects to the primary server and requests XLOG streaming replication.
10 : : *
11 : : * A walsender is similar to a regular backend, ie. there is a one-to-one
12 : : * relationship between a connection and a walsender process, but instead
13 : : * of processing SQL queries, it understands a small set of special
14 : : * replication-mode commands. The START_REPLICATION command begins streaming
15 : : * WAL to the client. While streaming, the walsender keeps reading XLOG
16 : : * records from the disk and sends them to the standby server over the
17 : : * COPY protocol, until either side ends the replication by exiting COPY
18 : : * mode (or until the connection is closed).
19 : : *
20 : : * Normal termination is by SIGTERM, which instructs the walsender to
21 : : * close the connection and exit(0) at the next convenient moment. Emergency
22 : : * termination is by SIGQUIT; like any backend, the walsender will simply
23 : : * abort and exit on SIGQUIT. A close of the connection and a FATAL error
24 : : * are treated as not a crash but approximately normal termination;
25 : : * the walsender will exit quickly without sending any more XLOG records.
26 : : *
27 : : * If the server is shut down, checkpointer sends us
28 : : * PROCSIG_WALSND_INIT_STOPPING after all regular backends have exited. If
29 : : * the backend is idle or runs an SQL query this causes the backend to
30 : : * shutdown, if logical replication is in progress all existing WAL records
31 : : * are processed followed by a shutdown. Otherwise this causes the walsender
32 : : * to switch to the "stopping" state. In this state, the walsender will reject
33 : : * any further replication commands. The checkpointer begins the shutdown
34 : : * checkpoint once all walsenders are confirmed as stopping. When the shutdown
35 : : * checkpoint finishes, the postmaster sends us SIGUSR2. This instructs
36 : : * walsender to send any outstanding WAL, including the shutdown checkpoint
37 : : * record, wait for it to be replicated to the standby, and then exit.
38 : : * This waiting time can be limited by the wal_sender_shutdown_timeout
39 : : * parameter.
40 : : *
41 : : *
42 : : * Portions Copyright (c) 2010-2026, PostgreSQL Global Development Group
43 : : *
44 : : * IDENTIFICATION
45 : : * src/backend/replication/walsender.c
46 : : *
47 : : *-------------------------------------------------------------------------
48 : : */
49 : : #include "postgres.h"
50 : :
51 : : #include <signal.h>
52 : : #include <unistd.h>
53 : :
54 : : #include "access/timeline.h"
55 : : #include "access/transam.h"
56 : : #include "access/twophase.h"
57 : : #include "access/xact.h"
58 : : #include "access/xlog_internal.h"
59 : : #include "access/xlogreader.h"
60 : : #include "access/xlogrecovery.h"
61 : : #include "access/xlogutils.h"
62 : : #include "backup/basebackup.h"
63 : : #include "backup/basebackup_incremental.h"
64 : : #include "catalog/pg_authid.h"
65 : : #include "catalog/pg_type.h"
66 : : #include "commands/defrem.h"
67 : : #include "funcapi.h"
68 : : #include "libpq/libpq.h"
69 : : #include "libpq/pqformat.h"
70 : : #include "libpq/protocol.h"
71 : : #include "miscadmin.h"
72 : : #include "nodes/replnodes.h"
73 : : #include "pgstat.h"
74 : : #include "postmaster/interrupt.h"
75 : : #include "replication/decode.h"
76 : : #include "replication/logical.h"
77 : : #include "replication/slotsync.h"
78 : : #include "replication/slot.h"
79 : : #include "replication/snapbuild.h"
80 : : #include "replication/syncrep.h"
81 : : #include "replication/walreceiver.h"
82 : : #include "replication/walsender.h"
83 : : #include "replication/walsender_private.h"
84 : : #include "storage/condition_variable.h"
85 : : #include "storage/aio_subsys.h"
86 : : #include "storage/fd.h"
87 : : #include "storage/ipc.h"
88 : : #include "storage/pmsignal.h"
89 : : #include "storage/proc.h"
90 : : #include "storage/procarray.h"
91 : : #include "storage/subsystems.h"
92 : : #include "tcop/dest.h"
93 : : #include "tcop/tcopprot.h"
94 : : #include "utils/acl.h"
95 : : #include "utils/builtins.h"
96 : : #include "utils/guc.h"
97 : : #include "utils/lsyscache.h"
98 : : #include "utils/memutils.h"
99 : : #include "utils/pg_lsn.h"
100 : : #include "utils/pgstat_internal.h"
101 : : #include "utils/ps_status.h"
102 : : #include "utils/timeout.h"
103 : : #include "utils/timestamp.h"
104 : : #include "utils/wait_event.h"
105 : :
106 : : /* Minimum interval used by walsender for stats flushes, in ms */
107 : : #define WALSENDER_STATS_FLUSH_INTERVAL 1000
108 : :
109 : : /*
110 : : * Maximum data payload in a WAL data message. Must be >= XLOG_BLCKSZ.
111 : : *
112 : : * We don't have a good idea of what a good value would be; there's some
113 : : * overhead per message in both walsender and walreceiver, but on the other
114 : : * hand sending large batches makes walsender less responsive to signals
115 : : * because signals are checked only between messages. 128kB (with
116 : : * default 8k blocks) seems like a reasonable guess for now.
117 : : */
118 : : #define MAX_SEND_SIZE (XLOG_BLCKSZ * 16)
119 : :
120 : : /* Array of WalSnds in shared memory */
121 : : WalSndCtlData *WalSndCtl = NULL;
122 : :
123 : : static void WalSndShmemRequest(void *arg);
124 : : static void WalSndShmemInit(void *arg);
125 : :
126 : : const ShmemCallbacks WalSndShmemCallbacks = {
127 : : .request_fn = WalSndShmemRequest,
128 : : .init_fn = WalSndShmemInit,
129 : : };
130 : :
131 : : /* My slot in the shared memory array */
132 : : WalSnd *MyWalSnd = NULL;
133 : :
134 : : /* Global state */
135 : : bool am_walsender = false; /* Am I a walsender process? */
136 : : bool am_cascading_walsender = false; /* Am I cascading WAL to another
137 : : * standby? */
138 : : bool am_db_walsender = false; /* Connected to a database? */
139 : :
140 : : /* GUC variables */
141 : : int max_wal_senders = 10; /* the maximum number of concurrent
142 : : * walsenders */
143 : : int wal_sender_timeout = 60 * 1000; /* maximum time to send one WAL
144 : : * data message */
145 : :
146 : : int wal_sender_shutdown_timeout = -1; /* maximum time to wait during
147 : : * shutdown for WAL
148 : : * replication */
149 : :
150 : : bool log_replication_commands = false;
151 : :
152 : : /*
153 : : * State for WalSndWakeupRequest
154 : : */
155 : : bool wake_wal_senders = false;
156 : :
157 : : /*
158 : : * xlogreader used for replication. Note that a WAL sender doing physical
159 : : * replication does not need xlogreader to read WAL, but it needs one to
160 : : * keep a state of its work.
161 : : */
162 : : static XLogReaderState *xlogreader = NULL;
163 : :
164 : : /*
165 : : * If the UPLOAD_MANIFEST command is used to provide a backup manifest in
166 : : * preparation for an incremental backup, uploaded_manifest will be point
167 : : * to an object containing information about its contexts, and
168 : : * uploaded_manifest_mcxt will point to the memory context that contains
169 : : * that object and all of its subordinate data. Otherwise, both values will
170 : : * be NULL.
171 : : */
172 : : static IncrementalBackupInfo *uploaded_manifest = NULL;
173 : : static MemoryContext uploaded_manifest_mcxt = NULL;
174 : :
175 : : /*
176 : : * These variables keep track of the state of the timeline we're currently
177 : : * sending. sendTimeLine identifies the timeline. If sendTimeLineIsHistoric,
178 : : * the timeline is not the latest timeline on this server, and the server's
179 : : * history forked off from that timeline at sendTimeLineValidUpto.
180 : : */
181 : : static TimeLineID sendTimeLine = 0;
182 : : static TimeLineID sendTimeLineNextTLI = 0;
183 : : static bool sendTimeLineIsHistoric = false;
184 : : static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
185 : :
186 : : /*
187 : : * How far have we sent WAL already? This is also advertised in
188 : : * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
189 : : */
190 : : static XLogRecPtr sentPtr = InvalidXLogRecPtr;
191 : :
192 : : /* Buffers for constructing outgoing messages and processing reply messages. */
193 : : static StringInfoData output_message;
194 : : static StringInfoData reply_message;
195 : : static StringInfoData tmpbuf;
196 : :
197 : : /* Timestamp of last ProcessRepliesIfAny(). */
198 : : static TimestampTz last_processing = 0;
199 : :
200 : : /*
201 : : * Timestamp of last ProcessRepliesIfAny() that saw a reply from the
202 : : * standby. Set to 0 if wal_sender_timeout doesn't need to be active.
203 : : */
204 : : static TimestampTz last_reply_timestamp = 0;
205 : :
206 : : /* Have we sent a heartbeat message asking for reply, since last reply? */
207 : : static bool waiting_for_ping_response = false;
208 : :
209 : : /* Timestamp when walsender received the shutdown request */
210 : : static TimestampTz shutdown_request_timestamp = 0;
211 : :
212 : : /*
213 : : * Set after queueing the CommandComplete message that ends WAL streaming
214 : : * during shutdown. This prevents WalSndDone() and WalSndDoneImmediate()
215 : : * from queueing the same message twice.
216 : : */
217 : : static bool shutdown_stream_done_queued = false;
218 : :
219 : : /*
220 : : * While streaming WAL in Copy mode, streamingDoneSending is set to true
221 : : * after we have sent CopyDone. We should not send any more CopyData messages
222 : : * after that. streamingDoneReceiving is set to true when we receive CopyDone
223 : : * from the other end. When both become true, it's time to exit Copy mode.
224 : : */
225 : : static bool streamingDoneSending;
226 : : static bool streamingDoneReceiving;
227 : :
228 : : /* Are we there yet? */
229 : : static bool WalSndCaughtUp = false;
230 : :
231 : : /* Flags set by signal handlers for later service in main loop */
232 : : static volatile sig_atomic_t got_SIGUSR2 = false;
233 : : static volatile sig_atomic_t got_STOPPING = false;
234 : :
235 : : /*
236 : : * This is set while we are streaming. When not set
237 : : * PROCSIG_WALSND_INIT_STOPPING signal will be handled like SIGTERM. When set,
238 : : * the main loop is responsible for checking got_STOPPING and terminating when
239 : : * it's set (after streaming any remaining WAL).
240 : : */
241 : : static volatile sig_atomic_t replication_active = false;
242 : :
243 : : static LogicalDecodingContext *logical_decoding_ctx = NULL;
244 : :
245 : : /* A sample associating a WAL location with the time it was written. */
246 : : typedef struct
247 : : {
248 : : XLogRecPtr lsn;
249 : : TimestampTz time;
250 : : } WalTimeSample;
251 : :
252 : : /* The size of our buffer of time samples. */
253 : : #define LAG_TRACKER_BUFFER_SIZE 8192
254 : :
255 : : /* A mechanism for tracking replication lag. */
256 : : typedef struct
257 : : {
258 : : XLogRecPtr last_lsn;
259 : : WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE];
260 : : int write_head;
261 : : int read_heads[NUM_SYNC_REP_WAIT_MODE];
262 : : WalTimeSample last_read[NUM_SYNC_REP_WAIT_MODE];
263 : :
264 : : /*
265 : : * Overflow entries for read heads that collide with the write head.
266 : : *
267 : : * When the cyclic buffer fills (write head is about to collide with a
268 : : * read head), we save that read head's current sample here and mark it as
269 : : * using overflow (read_heads[i] = -1). This allows the write head to
270 : : * continue advancing while the overflowed mode continues lag computation
271 : : * using the saved sample.
272 : : *
273 : : * Once the standby's reported LSN advances past the overflow entry's LSN,
274 : : * we transition back to normal buffer-based tracking.
275 : : */
276 : : WalTimeSample overflowed[NUM_SYNC_REP_WAIT_MODE];
277 : : } LagTracker;
278 : :
279 : : static LagTracker *lag_tracker;
280 : :
281 : : /* Signal handlers */
282 : : static void WalSndLastCycleHandler(SIGNAL_ARGS);
283 : :
284 : : /* Prototypes for private functions */
285 : : typedef void (*WalSndSendDataCallback) (void);
286 : : static void WalSndLoop(WalSndSendDataCallback send_data);
287 : : static void InitWalSenderSlot(void);
288 : : static void WalSndKill(int code, Datum arg);
289 : : pg_noreturn static void WalSndShutdown(void);
290 : : static void XLogSendPhysical(void);
291 : : static void XLogSendLogical(void);
292 : : pg_noreturn static void WalSndDoneImmediate(void);
293 : : static void WalSndDone(WalSndSendDataCallback send_data);
294 : : static void IdentifySystem(void);
295 : : static void UploadManifest(void);
296 : : static bool HandleUploadManifestPacket(StringInfo buf, off_t *offset,
297 : : IncrementalBackupInfo *ib);
298 : : static void ReadReplicationSlot(ReadReplicationSlotCmd *cmd);
299 : : static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd);
300 : : static void DropReplicationSlot(DropReplicationSlotCmd *cmd);
301 : : static void StartReplication(StartReplicationCmd *cmd);
302 : : static void StartLogicalReplication(StartReplicationCmd *cmd);
303 : : static void ProcessStandbyMessage(void);
304 : : static void ProcessStandbyReplyMessage(void);
305 : : static void ProcessStandbyHSFeedbackMessage(void);
306 : : static void ProcessStandbyPSRequestMessage(void);
307 : : static void ProcessRepliesIfAny(void);
308 : : static void ProcessPendingWrites(void);
309 : : static void WalSndKeepalive(bool requestReply, XLogRecPtr writePtr);
310 : : static void WalSndKeepaliveIfNecessary(void);
311 : : static void WalSndCheckTimeOut(void);
312 : : static void WalSndCheckShutdownTimeout(void);
313 : : static long WalSndComputeSleeptime(TimestampTz now);
314 : : static void WalSndWait(uint32 socket_events, long timeout, uint32 wait_event);
315 : : static void WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
316 : : static void WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
317 : : static void WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
318 : : bool skipped_xact);
319 : : static XLogRecPtr WalSndWaitForWal(XLogRecPtr loc);
320 : : static void LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time);
321 : : static TimeOffset LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now);
322 : : static bool TransactionIdInRecentPast(TransactionId xid, uint32 epoch);
323 : :
324 : : static void WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
325 : : TimeLineID *tli_p);
326 : :
327 : :
328 : : /* Initialize walsender process before entering the main command loop */
329 : : void
330 : 1358 : InitWalSender(void)
331 : : {
332 : 1358 : am_cascading_walsender = RecoveryInProgress();
333 : :
334 : : /* Create a per-walsender data structure in shared memory */
335 : 1358 : InitWalSenderSlot();
336 : :
337 : : /* need resource owner for e.g. basebackups */
338 : 1358 : CreateAuxProcessResourceOwner();
339 : :
340 : : /*
341 : : * Let postmaster know that we're a WAL sender. Once we've declared us as
342 : : * a WAL sender process, postmaster will let us outlive the bgwriter and
343 : : * kill us last in the shutdown sequence, so we get a chance to stream all
344 : : * remaining WAL at shutdown, including the shutdown checkpoint. Note that
345 : : * there's no going back, and we mustn't write any WAL records after this.
346 : : */
347 : 1358 : MarkPostmasterChildWalSender();
348 : 1358 : SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
349 : :
350 : : /*
351 : : * If the client didn't specify a database to connect to, show in PGPROC
352 : : * that our advertised xmin should affect vacuum horizons in all
353 : : * databases. This allows physical replication clients to send hot
354 : : * standby feedback that will delay vacuum cleanup in all databases.
355 : : */
356 [ + + ]: 1358 : if (MyDatabaseId == InvalidOid)
357 : : {
358 : : Assert(MyProc->xmin == InvalidTransactionId);
359 : 532 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
360 : 532 : MyProc->statusFlags |= PROC_AFFECTS_ALL_HORIZONS;
361 : 532 : ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
362 : 532 : LWLockRelease(ProcArrayLock);
363 : : }
364 : :
365 : : /* Initialize empty timestamp buffer for lag tracking. */
366 : 1358 : lag_tracker = MemoryContextAllocZero(TopMemoryContext, sizeof(LagTracker));
367 : 1358 : }
368 : :
369 : : /*
370 : : * Clean up after an error.
371 : : *
372 : : * WAL sender processes don't use transactions like regular backends do.
373 : : * This function does any cleanup required after an error in a WAL sender
374 : : * process, similar to what transaction abort does in a regular backend.
375 : : */
376 : : void
377 : 52 : WalSndErrorCleanup(void)
378 : : {
379 : 52 : LWLockReleaseAll();
380 : 52 : ConditionVariableCancelSleep();
381 : 52 : pgstat_report_wait_end();
382 : 52 : pgaio_error_cleanup();
383 : :
384 [ + + + + ]: 52 : if (xlogreader != NULL && xlogreader->seg.ws_file >= 0)
385 : 6 : wal_segment_close(xlogreader);
386 : :
387 [ + + ]: 52 : if (MyReplicationSlot != NULL)
388 : 17 : ReplicationSlotRelease();
389 : :
390 : 52 : ReplicationSlotCleanup(false);
391 : :
392 : 52 : replication_active = false;
393 : :
394 : : /*
395 : : * If there is a transaction in progress, it will clean up our
396 : : * ResourceOwner, but if a replication command set up a resource owner
397 : : * without a transaction, we've got to clean that up now.
398 : : */
399 [ + + ]: 52 : if (!IsTransactionOrTransactionBlock())
400 : 51 : ReleaseAuxProcessResources(false);
401 : :
402 [ + - - + ]: 52 : if (got_STOPPING || got_SIGUSR2)
403 : 0 : proc_exit(0);
404 : :
405 : : /* Revert back to startup state */
406 : 52 : WalSndSetState(WALSNDSTATE_STARTUP);
407 : 52 : }
408 : :
409 : : /*
410 : : * Handle a client's connection abort in an orderly manner.
411 : : */
412 : : static void
413 : 8 : WalSndShutdown(void)
414 : : {
415 : : /*
416 : : * Reset whereToSendOutput to prevent ereport from attempting to send any
417 : : * more messages to the standby.
418 : : */
419 [ + - ]: 8 : if (whereToSendOutput == DestRemote)
420 : 8 : whereToSendOutput = DestNone;
421 : :
422 : 8 : proc_exit(0);
423 : : }
424 : :
425 : : /*
426 : : * Handle the IDENTIFY_SYSTEM command.
427 : : */
428 : : static void
429 : 868 : IdentifySystem(void)
430 : : {
431 : : char sysid[32];
432 : : char xloc[MAXFNAMELEN];
433 : : XLogRecPtr logptr;
434 : 868 : char *dbname = NULL;
435 : : DestReceiver *dest;
436 : : TupOutputState *tstate;
437 : : TupleDesc tupdesc;
438 : : Datum values[4];
439 : 868 : bool nulls[4] = {0};
440 : : TimeLineID currTLI;
441 : :
442 : : /*
443 : : * Reply with a result set with one row, four columns. First col is system
444 : : * ID, second is timeline ID, third is current xlog location and the
445 : : * fourth contains the database name if we are connected to one.
446 : : */
447 : :
448 : 868 : snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
449 : : GetSystemIdentifier());
450 : :
451 : 868 : am_cascading_walsender = RecoveryInProgress();
452 [ + + ]: 868 : if (am_cascading_walsender)
453 : 75 : logptr = GetStandbyFlushRecPtr(&currTLI);
454 : : else
455 : 793 : logptr = GetFlushRecPtr(&currTLI);
456 : :
457 : 868 : snprintf(xloc, sizeof(xloc), "%X/%08X", LSN_FORMAT_ARGS(logptr));
458 : :
459 [ + + ]: 868 : if (MyDatabaseId != InvalidOid)
460 : : {
461 : 322 : MemoryContext cur = CurrentMemoryContext;
462 : :
463 : : /* syscache access needs a transaction env. */
464 : 322 : StartTransactionCommand();
465 : 322 : dbname = get_database_name(MyDatabaseId);
466 : : /* copy dbname out of TX context */
467 : 322 : dbname = MemoryContextStrdup(cur, dbname);
468 : 322 : CommitTransactionCommand();
469 : : }
470 : :
471 : 868 : dest = CreateDestReceiver(DestRemoteSimple);
472 : :
473 : : /* need a tuple descriptor representing four columns */
474 : 868 : tupdesc = CreateTemplateTupleDesc(4);
475 : 868 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "systemid",
476 : : TEXTOID, -1, 0);
477 : 868 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "timeline",
478 : : INT8OID, -1, 0);
479 : 868 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "xlogpos",
480 : : TEXTOID, -1, 0);
481 : 868 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "dbname",
482 : : TEXTOID, -1, 0);
483 : 868 : TupleDescFinalize(tupdesc);
484 : :
485 : : /* prepare for projection of tuples */
486 : 868 : tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
487 : :
488 : : /* column 1: system identifier */
489 : 868 : values[0] = CStringGetTextDatum(sysid);
490 : :
491 : : /* column 2: timeline */
492 : 868 : values[1] = Int64GetDatum(currTLI);
493 : :
494 : : /* column 3: wal location */
495 : 868 : values[2] = CStringGetTextDatum(xloc);
496 : :
497 : : /* column 4: database name, or NULL if none */
498 [ + + ]: 868 : if (dbname)
499 : 322 : values[3] = CStringGetTextDatum(dbname);
500 : : else
501 : 546 : nulls[3] = true;
502 : :
503 : : /* send it to dest */
504 : 868 : do_tup_output(tstate, values, nulls);
505 : :
506 : 868 : end_tup_output(tstate);
507 : 868 : }
508 : :
509 : : /* Handle READ_REPLICATION_SLOT command */
510 : : static void
511 : 6 : ReadReplicationSlot(ReadReplicationSlotCmd *cmd)
512 : : {
513 : : #define READ_REPLICATION_SLOT_COLS 3
514 : : ReplicationSlot *slot;
515 : : DestReceiver *dest;
516 : : TupOutputState *tstate;
517 : : TupleDesc tupdesc;
518 : 6 : Datum values[READ_REPLICATION_SLOT_COLS] = {0};
519 : : bool nulls[READ_REPLICATION_SLOT_COLS];
520 : :
521 : 6 : tupdesc = CreateTemplateTupleDesc(READ_REPLICATION_SLOT_COLS);
522 : 6 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "slot_type",
523 : : TEXTOID, -1, 0);
524 : 6 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "restart_lsn",
525 : : TEXTOID, -1, 0);
526 : : /* TimeLineID is unsigned, so int4 is not wide enough. */
527 : 6 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "restart_tli",
528 : : INT8OID, -1, 0);
529 : 6 : TupleDescFinalize(tupdesc);
530 : :
531 : 6 : memset(nulls, true, READ_REPLICATION_SLOT_COLS * sizeof(bool));
532 : :
533 : 6 : LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
534 : 6 : slot = SearchNamedReplicationSlot(cmd->slotname, false);
535 [ + + - + ]: 6 : if (slot == NULL || !slot->in_use)
536 : : {
537 : 2 : LWLockRelease(ReplicationSlotControlLock);
538 : : }
539 : : else
540 : : {
541 : : ReplicationSlot slot_contents;
542 : 4 : int i = 0;
543 : :
544 : : /* Copy slot contents while holding spinlock */
545 : 4 : SpinLockAcquire(&slot->mutex);
546 : 4 : slot_contents = *slot;
547 : 4 : SpinLockRelease(&slot->mutex);
548 : 4 : LWLockRelease(ReplicationSlotControlLock);
549 : :
550 [ + + ]: 4 : if (OidIsValid(slot_contents.data.database))
551 [ + - ]: 1 : ereport(ERROR,
552 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
553 : : errmsg("cannot use %s with a logical replication slot",
554 : : "READ_REPLICATION_SLOT"));
555 : :
556 : : /* slot type */
557 : 3 : values[i] = CStringGetTextDatum("physical");
558 : 3 : nulls[i] = false;
559 : 3 : i++;
560 : :
561 : : /* start LSN */
562 [ + - ]: 3 : if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
563 : : {
564 : : char xloc[64];
565 : :
566 : 3 : snprintf(xloc, sizeof(xloc), "%X/%08X",
567 : 3 : LSN_FORMAT_ARGS(slot_contents.data.restart_lsn));
568 : 3 : values[i] = CStringGetTextDatum(xloc);
569 : 3 : nulls[i] = false;
570 : : }
571 : 3 : i++;
572 : :
573 : : /* timeline this WAL was produced on */
574 [ + - ]: 3 : if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
575 : : {
576 : : TimeLineID slots_position_timeline;
577 : : TimeLineID current_timeline;
578 : 3 : List *timeline_history = NIL;
579 : :
580 : : /*
581 : : * While in recovery, use as timeline the currently-replaying one
582 : : * to get the LSN position's history.
583 : : */
584 [ - + ]: 3 : if (RecoveryInProgress())
585 : 0 : (void) GetXLogReplayRecPtr(¤t_timeline);
586 : : else
587 : 3 : current_timeline = GetWALInsertionTimeLine();
588 : :
589 : 3 : timeline_history = readTimeLineHistory(current_timeline);
590 : 3 : slots_position_timeline = tliOfPointInHistory(slot_contents.data.restart_lsn,
591 : : timeline_history);
592 : 3 : values[i] = Int64GetDatum((int64) slots_position_timeline);
593 : 3 : nulls[i] = false;
594 : : }
595 : 3 : i++;
596 : :
597 : : Assert(i == READ_REPLICATION_SLOT_COLS);
598 : : }
599 : :
600 : 5 : dest = CreateDestReceiver(DestRemoteSimple);
601 : 5 : tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
602 : 5 : do_tup_output(tstate, values, nulls);
603 : 5 : end_tup_output(tstate);
604 : 5 : }
605 : :
606 : :
607 : : /*
608 : : * Handle TIMELINE_HISTORY command.
609 : : */
610 : : static void
611 : 16 : SendTimeLineHistory(TimeLineHistoryCmd *cmd)
612 : : {
613 : : DestReceiver *dest;
614 : : TupleDesc tupdesc;
615 : : StringInfoData buf;
616 : : char histfname[MAXFNAMELEN];
617 : : char path[MAXPGPATH];
618 : : int fd;
619 : : off_t histfilelen;
620 : : size_t bytesleft;
621 : : Size len;
622 : :
623 : 16 : dest = CreateDestReceiver(DestRemoteSimple);
624 : :
625 : : /*
626 : : * Reply with a result set with one row, and two columns. The first col is
627 : : * the name of the history file, 2nd is the contents.
628 : : */
629 : 16 : tupdesc = CreateTemplateTupleDesc(2);
630 : 16 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "filename", TEXTOID, -1, 0);
631 : 16 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "content", TEXTOID, -1, 0);
632 : 16 : TupleDescFinalize(tupdesc);
633 : :
634 : 16 : TLHistoryFileName(histfname, cmd->timeline);
635 : 16 : TLHistoryFilePath(path, cmd->timeline);
636 : :
637 : : /* Send a RowDescription message */
638 : 16 : dest->rStartup(dest, CMD_SELECT, tupdesc);
639 : :
640 : : /* Send a DataRow message */
641 : 16 : pq_beginmessage(&buf, PqMsg_DataRow);
642 : 16 : pq_sendint16(&buf, 2); /* # of columns */
643 : 16 : len = strlen(histfname);
644 : 16 : pq_sendint32(&buf, len); /* col1 len */
645 : 16 : pq_sendbytes(&buf, histfname, len);
646 : :
647 : 16 : fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
648 [ - + ]: 16 : if (fd < 0)
649 [ # # ]: 0 : ereport(ERROR,
650 : : (errcode_for_file_access(),
651 : : errmsg("could not open file \"%s\": %m", path)));
652 : :
653 : : /* Determine file length and send it to client */
654 : 16 : histfilelen = lseek(fd, 0, SEEK_END);
655 [ - + ]: 16 : if (histfilelen < 0)
656 [ # # ]: 0 : ereport(ERROR,
657 : : (errcode_for_file_access(),
658 : : errmsg("could not seek to end of file \"%s\": %m", path)));
659 [ - + ]: 16 : if (lseek(fd, 0, SEEK_SET) != 0)
660 [ # # ]: 0 : ereport(ERROR,
661 : : (errcode_for_file_access(),
662 : : errmsg("could not seek to beginning of file \"%s\": %m", path)));
663 : :
664 : : /*
665 : : * unlikely in practice, but to document the implicit integer conversion
666 : : */
667 [ - + ]: 16 : if (histfilelen > UINT32_MAX)
668 [ # # ]: 0 : elog(ERROR, "timeline history file is too large");
669 : :
670 : 16 : pq_sendint32(&buf, histfilelen); /* col2 len */
671 : :
672 : 16 : bytesleft = histfilelen;
673 [ + + ]: 32 : while (bytesleft > 0)
674 : : {
675 : : PGAlignedBlock rbuf;
676 : : ssize_t nread;
677 : :
678 : 16 : pgstat_report_wait_start(WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ);
679 : 16 : nread = read(fd, rbuf.data, sizeof(rbuf));
680 : 16 : pgstat_report_wait_end();
681 [ - + ]: 16 : if (nread < 0)
682 [ # # ]: 0 : ereport(ERROR,
683 : : (errcode_for_file_access(),
684 : : errmsg("could not read file \"%s\": %m",
685 : : path)));
686 [ - + ]: 16 : else if (nread == 0)
687 [ # # ]: 0 : ereport(ERROR,
688 : : (errcode(ERRCODE_DATA_CORRUPTED),
689 : : errmsg("could not read file \"%s\": read %zd of %zu",
690 : : path, nread, bytesleft)));
691 : :
692 : : /*
693 : : * We could have read more than expected if the file changed
694 : : * concurrently. In that case, only send as much as we expected and
695 : : * make sure the loop aborts properly (no wrap of bytesleft). (This
696 : : * isn't possible in practice, because the files are updated by atomic
697 : : * renames, but it's a safer programming practice.)
698 : : */
699 : 16 : nread = Min(nread, bytesleft);
700 : :
701 : 16 : pq_sendbytes(&buf, rbuf.data, nread);
702 : :
703 : 16 : bytesleft -= nread;
704 : : }
705 : :
706 [ - + ]: 16 : if (CloseTransientFile(fd) != 0)
707 [ # # ]: 0 : ereport(ERROR,
708 : : (errcode_for_file_access(),
709 : : errmsg("could not close file \"%s\": %m", path)));
710 : :
711 : 16 : pq_endmessage(&buf);
712 : 16 : }
713 : :
714 : : /*
715 : : * Handle UPLOAD_MANIFEST command.
716 : : */
717 : : static void
718 : 13 : UploadManifest(void)
719 : : {
720 : : MemoryContext mcxt;
721 : : IncrementalBackupInfo *ib;
722 : 13 : off_t offset = 0;
723 : : StringInfoData buf;
724 : :
725 : : /*
726 : : * parsing the manifest will use the cryptohash stuff, which requires a
727 : : * resource owner
728 : : */
729 : : Assert(AuxProcessResourceOwner != NULL);
730 : : Assert(CurrentResourceOwner == AuxProcessResourceOwner ||
731 : : CurrentResourceOwner == NULL);
732 : 13 : CurrentResourceOwner = AuxProcessResourceOwner;
733 : :
734 : : /* Prepare to read manifest data into a temporary context. */
735 : 13 : mcxt = AllocSetContextCreate(CurrentMemoryContext,
736 : : "incremental backup information",
737 : : ALLOCSET_DEFAULT_SIZES);
738 : 13 : ib = CreateIncrementalBackupInfo(mcxt);
739 : :
740 : : /* Send a CopyInResponse message */
741 : 13 : pq_beginmessage(&buf, PqMsg_CopyInResponse);
742 : 13 : pq_sendbyte(&buf, 0);
743 : 13 : pq_sendint16(&buf, 0);
744 : 13 : pq_endmessage_reuse(&buf);
745 : 13 : pq_flush();
746 : :
747 : : /* Receive packets from client until done. */
748 [ + + ]: 52 : while (HandleUploadManifestPacket(&buf, &offset, ib))
749 : : ;
750 : :
751 : : /* Finish up manifest processing. */
752 : 12 : FinalizeIncrementalManifest(ib);
753 : :
754 : : /*
755 : : * Discard any old manifest information and arrange to preserve the new
756 : : * information we just got.
757 : : *
758 : : * We assume that MemoryContextDelete and MemoryContextSetParent won't
759 : : * fail, and thus we shouldn't end up bailing out of here in such a way as
760 : : * to leave dangling pointers.
761 : : */
762 [ - + ]: 12 : if (uploaded_manifest_mcxt != NULL)
763 : 0 : MemoryContextDelete(uploaded_manifest_mcxt);
764 : 12 : MemoryContextSetParent(mcxt, CacheMemoryContext);
765 : 12 : uploaded_manifest = ib;
766 : 12 : uploaded_manifest_mcxt = mcxt;
767 : :
768 : : /* clean up the resource owner we created */
769 : 12 : ReleaseAuxProcessResources(true);
770 : 12 : }
771 : :
772 : : /*
773 : : * Process one packet received during the handling of an UPLOAD_MANIFEST
774 : : * operation.
775 : : *
776 : : * 'buf' is scratch space. This function expects it to be initialized, doesn't
777 : : * care what the current contents are, and may override them with completely
778 : : * new contents.
779 : : *
780 : : * The return value is true if the caller should continue processing
781 : : * additional packets and false if the UPLOAD_MANIFEST operation is complete.
782 : : */
783 : : static bool
784 : 52 : HandleUploadManifestPacket(StringInfo buf, off_t *offset,
785 : : IncrementalBackupInfo *ib)
786 : : {
787 : : int mtype;
788 : : int maxmsglen;
789 : :
790 : 52 : HOLD_CANCEL_INTERRUPTS();
791 : :
792 : 52 : pq_startmsgread();
793 : 52 : mtype = pq_getbyte();
794 [ - + ]: 52 : if (mtype == EOF)
795 [ # # ]: 0 : ereport(ERROR,
796 : : (errcode(ERRCODE_CONNECTION_FAILURE),
797 : : errmsg("unexpected EOF on client connection with an open transaction")));
798 : :
799 [ + + - ]: 52 : switch (mtype)
800 : : {
801 : 40 : case PqMsg_CopyData:
802 : 40 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
803 : 40 : break;
804 : 12 : case PqMsg_CopyDone:
805 : : case PqMsg_CopyFail:
806 : : case PqMsg_Flush:
807 : : case PqMsg_Sync:
808 : 12 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
809 : 12 : break;
810 : 0 : default:
811 [ # # ]: 0 : ereport(ERROR,
812 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
813 : : errmsg("unexpected message type 0x%02X during COPY from stdin",
814 : : mtype)));
815 : : maxmsglen = 0; /* keep compiler quiet */
816 : : break;
817 : : }
818 : :
819 : : /* Now collect the message body */
820 [ - + ]: 52 : if (pq_getmessage(buf, maxmsglen))
821 [ # # ]: 0 : ereport(ERROR,
822 : : (errcode(ERRCODE_CONNECTION_FAILURE),
823 : : errmsg("unexpected EOF on client connection with an open transaction")));
824 : 52 : RESUME_CANCEL_INTERRUPTS();
825 : :
826 : : /* Process the message */
827 [ + + - - : 52 : switch (mtype)
- ]
828 : : {
829 : 40 : case PqMsg_CopyData:
830 : 40 : AppendIncrementalManifestData(ib, buf->data, buf->len);
831 : 39 : return true;
832 : :
833 : 12 : case PqMsg_CopyDone:
834 : 12 : return false;
835 : :
836 : 0 : case PqMsg_Sync:
837 : : case PqMsg_Flush:
838 : : /* Ignore these while in CopyOut mode as we do elsewhere. */
839 : 0 : return true;
840 : :
841 : 0 : case PqMsg_CopyFail:
842 [ # # ]: 0 : ereport(ERROR,
843 : : (errcode(ERRCODE_QUERY_CANCELED),
844 : : errmsg("COPY from stdin failed: %s",
845 : : pq_getmsgstring(buf))));
846 : : }
847 : :
848 : : /* Not reached. */
849 : : Assert(false);
850 : 0 : return false;
851 : : }
852 : :
853 : : /*
854 : : * Handle START_REPLICATION command.
855 : : *
856 : : * At the moment, this never returns, but an ereport(ERROR) will take us back
857 : : * to the main loop.
858 : : */
859 : : static void
860 : 324 : StartReplication(StartReplicationCmd *cmd)
861 : : {
862 : : StringInfoData buf;
863 : : XLogRecPtr FlushPtr;
864 : : TimeLineID FlushTLI;
865 : :
866 : : /* create xlogreader for physical replication */
867 : 324 : xlogreader =
868 : 324 : XLogReaderAllocate(wal_segment_size, NULL,
869 : 324 : XL_ROUTINE(.segment_open = WalSndSegmentOpen,
870 : : .segment_close = wal_segment_close),
871 : : NULL);
872 : :
873 [ - + ]: 324 : if (!xlogreader)
874 [ # # ]: 0 : ereport(ERROR,
875 : : (errcode(ERRCODE_OUT_OF_MEMORY),
876 : : errmsg("out of memory"),
877 : : errdetail("Failed while allocating a WAL reading processor.")));
878 : :
879 : : /*
880 : : * We assume here that we're logging enough information in the WAL for
881 : : * log-shipping, since this is checked in PostmasterMain().
882 : : *
883 : : * NOTE: wal_level can only change at shutdown, so in most cases it is
884 : : * difficult for there to be WAL data that we can still see that was
885 : : * written at wal_level='minimal'.
886 : : */
887 : :
888 [ + + ]: 324 : if (cmd->slotname)
889 : : {
890 : 216 : ReplicationSlotAcquire(cmd->slotname, true, true);
891 [ - + ]: 213 : if (SlotIsLogical(MyReplicationSlot))
892 [ # # ]: 0 : ereport(ERROR,
893 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
894 : : errmsg("cannot use a logical replication slot for physical replication")));
895 : :
896 : : /*
897 : : * We don't need to verify the slot's restart_lsn here; instead we
898 : : * rely on the caller requesting the starting point to use. If the
899 : : * WAL segment doesn't exist, we'll fail later.
900 : : */
901 : : }
902 : :
903 : : /*
904 : : * Select the timeline. If it was given explicitly by the client, use
905 : : * that. Otherwise use the timeline of the last replayed record.
906 : : */
907 : 321 : am_cascading_walsender = RecoveryInProgress();
908 [ + + ]: 321 : if (am_cascading_walsender)
909 : 21 : FlushPtr = GetStandbyFlushRecPtr(&FlushTLI);
910 : : else
911 : 300 : FlushPtr = GetFlushRecPtr(&FlushTLI);
912 : :
913 [ + + ]: 321 : if (cmd->timeline != 0)
914 : : {
915 : : XLogRecPtr switchpoint;
916 : :
917 : 320 : sendTimeLine = cmd->timeline;
918 [ + + ]: 320 : if (sendTimeLine == FlushTLI)
919 : : {
920 : 311 : sendTimeLineIsHistoric = false;
921 : 311 : sendTimeLineValidUpto = InvalidXLogRecPtr;
922 : : }
923 : : else
924 : : {
925 : : List *timeLineHistory;
926 : :
927 : 9 : sendTimeLineIsHistoric = true;
928 : :
929 : : /*
930 : : * Check that the timeline the client requested exists, and the
931 : : * requested start location is on that timeline.
932 : : */
933 : 9 : timeLineHistory = readTimeLineHistory(FlushTLI);
934 : 9 : switchpoint = tliSwitchPoint(cmd->timeline, timeLineHistory,
935 : : &sendTimeLineNextTLI);
936 : 9 : list_free_deep(timeLineHistory);
937 : :
938 : : /*
939 : : * Found the requested timeline in the history. Check that
940 : : * requested startpoint is on that timeline in our history.
941 : : *
942 : : * This is quite loose on purpose. We only check that we didn't
943 : : * fork off the requested timeline before the switchpoint. We
944 : : * don't check that we switched *to* it before the requested
945 : : * starting point. This is because the client can legitimately
946 : : * request to start replication from the beginning of the WAL
947 : : * segment that contains switchpoint, but on the new timeline, so
948 : : * that it doesn't end up with a partial segment. If you ask for
949 : : * too old a starting point, you'll get an error later when we
950 : : * fail to find the requested WAL segment in pg_wal.
951 : : *
952 : : * XXX: we could be more strict here and only allow a startpoint
953 : : * that's older than the switchpoint, if it's still in the same
954 : : * WAL segment.
955 : : */
956 [ + - ]: 9 : if (XLogRecPtrIsValid(switchpoint) &&
957 [ - + ]: 9 : switchpoint < cmd->startpoint)
958 : : {
959 [ # # ]: 0 : ereport(ERROR,
960 : : errmsg("requested starting point %X/%08X on timeline %u is not in this server's history",
961 : : LSN_FORMAT_ARGS(cmd->startpoint),
962 : : cmd->timeline),
963 : : errdetail("This server's history forked from timeline %u at %X/%08X.",
964 : : cmd->timeline,
965 : : LSN_FORMAT_ARGS(switchpoint)));
966 : : }
967 : 9 : sendTimeLineValidUpto = switchpoint;
968 : : }
969 : : }
970 : : else
971 : : {
972 : 1 : sendTimeLine = FlushTLI;
973 : 1 : sendTimeLineValidUpto = InvalidXLogRecPtr;
974 : 1 : sendTimeLineIsHistoric = false;
975 : : }
976 : :
977 : 321 : streamingDoneSending = streamingDoneReceiving = false;
978 : :
979 : : /* If there is nothing to stream, don't even enter COPY mode */
980 [ + + + - ]: 321 : if (!sendTimeLineIsHistoric || cmd->startpoint < sendTimeLineValidUpto)
981 : : {
982 : : /*
983 : : * When we first start replication the standby will be behind the
984 : : * primary. For some applications, for example synchronous
985 : : * replication, it is important to have a clear state for this initial
986 : : * catchup mode, so we can trigger actions when we change streaming
987 : : * state later. We may stay in this state for a long time, which is
988 : : * exactly why we want to be able to monitor whether or not we are
989 : : * still here.
990 : : */
991 : 321 : WalSndSetState(WALSNDSTATE_CATCHUP);
992 : :
993 : : /* Send a CopyBothResponse message, and start streaming */
994 : 321 : pq_beginmessage(&buf, PqMsg_CopyBothResponse);
995 : 321 : pq_sendbyte(&buf, 0);
996 : 321 : pq_sendint16(&buf, 0);
997 : 321 : pq_endmessage(&buf);
998 : 321 : pq_flush();
999 : :
1000 : : /*
1001 : : * Don't allow a request to stream from a future point in WAL that
1002 : : * hasn't been flushed to disk in this server yet.
1003 : : */
1004 [ - + ]: 321 : if (FlushPtr < cmd->startpoint)
1005 : : {
1006 [ # # ]: 0 : ereport(ERROR,
1007 : : errmsg("requested starting point %X/%08X is ahead of the WAL flush position of this server %X/%08X",
1008 : : LSN_FORMAT_ARGS(cmd->startpoint),
1009 : : LSN_FORMAT_ARGS(FlushPtr)));
1010 : : }
1011 : :
1012 : : /* Start streaming from the requested point */
1013 : 321 : sentPtr = cmd->startpoint;
1014 : :
1015 : : /* Initialize shared memory status, too */
1016 : 321 : SpinLockAcquire(&MyWalSnd->mutex);
1017 : 321 : MyWalSnd->sentPtr = sentPtr;
1018 : 321 : SpinLockRelease(&MyWalSnd->mutex);
1019 : :
1020 : 321 : SyncRepInitConfig();
1021 : :
1022 : : /* Main loop of walsender */
1023 : 321 : replication_active = true;
1024 : :
1025 : 321 : WalSndLoop(XLogSendPhysical);
1026 : :
1027 : 175 : replication_active = false;
1028 [ - + ]: 175 : if (got_STOPPING)
1029 : 0 : proc_exit(0);
1030 : 175 : WalSndSetState(WALSNDSTATE_STARTUP);
1031 : :
1032 : : Assert(streamingDoneSending && streamingDoneReceiving);
1033 : : }
1034 : :
1035 [ + + ]: 175 : if (cmd->slotname)
1036 : 160 : ReplicationSlotRelease();
1037 : :
1038 : : /*
1039 : : * Copy is finished now. Send a single-row result set indicating the next
1040 : : * timeline.
1041 : : */
1042 [ + + ]: 175 : if (sendTimeLineIsHistoric)
1043 : : {
1044 : : char startpos_str[8 + 1 + 8 + 1];
1045 : : DestReceiver *dest;
1046 : : TupOutputState *tstate;
1047 : : TupleDesc tupdesc;
1048 : : Datum values[2];
1049 : 12 : bool nulls[2] = {0};
1050 : :
1051 : 12 : snprintf(startpos_str, sizeof(startpos_str), "%X/%08X",
1052 : 12 : LSN_FORMAT_ARGS(sendTimeLineValidUpto));
1053 : :
1054 : 12 : dest = CreateDestReceiver(DestRemoteSimple);
1055 : :
1056 : : /*
1057 : : * Need a tuple descriptor representing two columns. int8 may seem
1058 : : * like a surprising data type for this, but in theory int4 would not
1059 : : * be wide enough for this, as TimeLineID is unsigned.
1060 : : */
1061 : 12 : tupdesc = CreateTemplateTupleDesc(2);
1062 : 12 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "next_tli",
1063 : : INT8OID, -1, 0);
1064 : 12 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "next_tli_startpos",
1065 : : TEXTOID, -1, 0);
1066 : 12 : TupleDescFinalize(tupdesc);
1067 : :
1068 : : /* prepare for projection of tuple */
1069 : 12 : tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
1070 : :
1071 : 12 : values[0] = Int64GetDatum((int64) sendTimeLineNextTLI);
1072 : 12 : values[1] = CStringGetTextDatum(startpos_str);
1073 : :
1074 : : /* send it to dest */
1075 : 12 : do_tup_output(tstate, values, nulls);
1076 : :
1077 : 12 : end_tup_output(tstate);
1078 : : }
1079 : :
1080 : : /* Send CommandComplete message */
1081 : 175 : EndReplicationCommand("START_STREAMING");
1082 : 175 : }
1083 : :
1084 : : /*
1085 : : * XLogReaderRoutine->page_read callback for logical decoding contexts, as a
1086 : : * walsender process.
1087 : : *
1088 : : * Inside the walsender we can do better than read_local_xlog_page,
1089 : : * which has to do a plain sleep/busy loop, because the walsender's latch gets
1090 : : * set every time WAL is flushed.
1091 : : */
1092 : : static int
1093 : 21947 : logical_read_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen,
1094 : : XLogRecPtr targetRecPtr, char *cur_page)
1095 : : {
1096 : : XLogRecPtr flushptr;
1097 : : int count;
1098 : : WALReadError errinfo;
1099 : : XLogSegNo segno;
1100 : : TimeLineID currTLI;
1101 : :
1102 : : /*
1103 : : * Make sure we have enough WAL available before retrieving the current
1104 : : * timeline.
1105 : : */
1106 : 21947 : flushptr = WalSndWaitForWal(targetPagePtr + reqLen);
1107 : :
1108 : : /* Fail if not enough (implies we are going to shut down) */
1109 [ + + ]: 21710 : if (flushptr < targetPagePtr + reqLen)
1110 : 3104 : return -1;
1111 : :
1112 : : /*
1113 : : * Since logical decoding is also permitted on a standby server, we need
1114 : : * to check if the server is in recovery to decide how to get the current
1115 : : * timeline ID (so that it also covers the promotion or timeline change
1116 : : * cases). We must determine am_cascading_walsender after waiting for the
1117 : : * required WAL so that it is correct when the walsender wakes up after a
1118 : : * promotion.
1119 : : */
1120 : 18606 : am_cascading_walsender = RecoveryInProgress();
1121 : :
1122 [ + + ]: 18606 : if (am_cascading_walsender)
1123 : : {
1124 : : TimeLineID insertTLI;
1125 : :
1126 : : /*
1127 : : * If the insertion timeline has already been set, use it.
1128 : : * InsertTimeLineID is set before the WAL segments of the old timeline
1129 : : * are removed, before SharedRecoveryState switches to
1130 : : * RECOVERY_STATE_DONE.
1131 : : *
1132 : : * There is a window where RecoveryInProgress() still returns true but
1133 : : * the old timeline's WAL segments have already been removed or
1134 : : * recycled. Using the WAL insertion timeline avoids attempting to
1135 : : * read from those removed segments, improving availability, and is a
1136 : : * safe thing to do as promotion copies the contents in the last
1137 : : * segment of the old timeline to the first segment of the new
1138 : : * timeline, up to the switchpoint.
1139 : : */
1140 : 910 : insertTLI = GetWALInsertionTimeLineIfSet();
1141 [ - + ]: 910 : if (insertTLI != 0)
1142 : 0 : currTLI = insertTLI;
1143 : : else
1144 : 910 : GetXLogReplayRecPtr(&currTLI);
1145 : : }
1146 : : else
1147 : 17696 : currTLI = GetWALInsertionTimeLine();
1148 : :
1149 : 18606 : XLogReadDetermineTimeline(state, targetPagePtr, reqLen, currTLI);
1150 : 18606 : sendTimeLineIsHistoric = (state->currTLI != currTLI);
1151 : 18606 : sendTimeLine = state->currTLI;
1152 : 18606 : sendTimeLineValidUpto = state->currTLIValidUntil;
1153 : 18606 : sendTimeLineNextTLI = state->nextTLI;
1154 : :
1155 [ + + ]: 18606 : if (targetPagePtr + XLOG_BLCKSZ <= flushptr)
1156 : 16485 : count = XLOG_BLCKSZ; /* more than one block available */
1157 : : else
1158 : 2121 : count = flushptr - targetPagePtr; /* part of the page available */
1159 : :
1160 : : /* now actually read the data, we know it's there */
1161 [ - + ]: 18606 : if (!WALRead(state,
1162 : : cur_page,
1163 : : targetPagePtr,
1164 : : count,
1165 : : currTLI, /* Pass the current TLI because only
1166 : : * WalSndSegmentOpen controls whether new TLI
1167 : : * is needed. */
1168 : : &errinfo))
1169 : 0 : WALReadRaiseError(&errinfo);
1170 : :
1171 : : /*
1172 : : * After reading into the buffer, check that what we read was valid. We do
1173 : : * this after reading, because even though the segment was present when we
1174 : : * opened it, it might get recycled or removed while we read it. The
1175 : : * read() succeeds in that case, but the data we tried to read might
1176 : : * already have been overwritten with new WAL records.
1177 : : */
1178 : 18606 : XLByteToSeg(targetPagePtr, segno, state->segcxt.ws_segsize);
1179 : 18606 : CheckXLogRemoved(segno, state->seg.ws_tli);
1180 : :
1181 : 18606 : return count;
1182 : : }
1183 : :
1184 : : /*
1185 : : * Process extra options given to CREATE_REPLICATION_SLOT.
1186 : : */
1187 : : static void
1188 : 536 : parseCreateReplSlotOptions(CreateReplicationSlotCmd *cmd,
1189 : : bool *reserve_wal,
1190 : : CRSSnapshotAction *snapshot_action,
1191 : : bool *two_phase, bool *failover)
1192 : : {
1193 : : ListCell *lc;
1194 : 536 : bool snapshot_action_given = false;
1195 : 536 : bool reserve_wal_given = false;
1196 : 536 : bool two_phase_given = false;
1197 : 536 : bool failover_given = false;
1198 : :
1199 : : /* Parse options */
1200 [ + + + + : 1084 : foreach(lc, cmd->options)
+ + ]
1201 : : {
1202 : 548 : DefElem *defel = (DefElem *) lfirst(lc);
1203 : :
1204 [ + + ]: 548 : if (strcmp(defel->defname, "snapshot") == 0)
1205 : : {
1206 : : char *action;
1207 : :
1208 [ + - - + ]: 372 : if (snapshot_action_given || cmd->kind != REPLICATION_KIND_LOGICAL)
1209 [ # # ]: 0 : ereport(ERROR,
1210 : : (errcode(ERRCODE_SYNTAX_ERROR),
1211 : : errmsg("conflicting or redundant options")));
1212 : :
1213 : 372 : action = defGetString(defel);
1214 : 372 : snapshot_action_given = true;
1215 : :
1216 [ + + ]: 372 : if (strcmp(action, "export") == 0)
1217 : 1 : *snapshot_action = CRS_EXPORT_SNAPSHOT;
1218 [ + + ]: 371 : else if (strcmp(action, "nothing") == 0)
1219 : 154 : *snapshot_action = CRS_NOEXPORT_SNAPSHOT;
1220 [ + - ]: 217 : else if (strcmp(action, "use") == 0)
1221 : 217 : *snapshot_action = CRS_USE_SNAPSHOT;
1222 : : else
1223 [ # # ]: 0 : ereport(ERROR,
1224 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1225 : : errmsg("unrecognized value for %s option \"%s\": \"%s\"",
1226 : : "CREATE_REPLICATION_SLOT", defel->defname, action)));
1227 : : }
1228 [ + + ]: 176 : else if (strcmp(defel->defname, "reserve_wal") == 0)
1229 : : {
1230 [ + - - + ]: 162 : if (reserve_wal_given || cmd->kind != REPLICATION_KIND_PHYSICAL)
1231 [ # # ]: 0 : ereport(ERROR,
1232 : : (errcode(ERRCODE_SYNTAX_ERROR),
1233 : : errmsg("conflicting or redundant options")));
1234 : :
1235 : 162 : reserve_wal_given = true;
1236 : 162 : *reserve_wal = defGetBoolean(defel);
1237 : : }
1238 [ + + ]: 14 : else if (strcmp(defel->defname, "two_phase") == 0)
1239 : : {
1240 [ + - - + ]: 2 : if (two_phase_given || cmd->kind != REPLICATION_KIND_LOGICAL)
1241 [ # # ]: 0 : ereport(ERROR,
1242 : : (errcode(ERRCODE_SYNTAX_ERROR),
1243 : : errmsg("conflicting or redundant options")));
1244 : 2 : two_phase_given = true;
1245 : 2 : *two_phase = defGetBoolean(defel);
1246 : : }
1247 [ + - ]: 12 : else if (strcmp(defel->defname, "failover") == 0)
1248 : : {
1249 [ + - - + ]: 12 : if (failover_given || cmd->kind != REPLICATION_KIND_LOGICAL)
1250 [ # # ]: 0 : ereport(ERROR,
1251 : : (errcode(ERRCODE_SYNTAX_ERROR),
1252 : : errmsg("conflicting or redundant options")));
1253 : 12 : failover_given = true;
1254 : 12 : *failover = defGetBoolean(defel);
1255 : : }
1256 : : else
1257 [ # # ]: 0 : elog(ERROR, "unrecognized option: %s", defel->defname);
1258 : : }
1259 : 536 : }
1260 : :
1261 : : /*
1262 : : * Create a new replication slot.
1263 : : */
1264 : : static void
1265 : 536 : CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
1266 : : {
1267 : 536 : const char *snapshot_name = NULL;
1268 : : char xloc[MAXFNAMELEN];
1269 : : char *slot_name;
1270 : 536 : bool reserve_wal = false;
1271 : 536 : bool two_phase = false;
1272 : 536 : bool failover = false;
1273 : 536 : CRSSnapshotAction snapshot_action = CRS_EXPORT_SNAPSHOT;
1274 : : DestReceiver *dest;
1275 : : TupOutputState *tstate;
1276 : : TupleDesc tupdesc;
1277 : : Datum values[4];
1278 : 536 : bool nulls[4] = {0};
1279 : :
1280 : : Assert(!MyReplicationSlot);
1281 : :
1282 : 536 : parseCreateReplSlotOptions(cmd, &reserve_wal, &snapshot_action, &two_phase,
1283 : : &failover);
1284 : :
1285 [ + + ]: 536 : if (cmd->kind == REPLICATION_KIND_PHYSICAL)
1286 : : {
1287 : 163 : ReplicationSlotCreate(cmd->slotname, false,
1288 [ + + ]: 163 : cmd->temporary ? RS_TEMPORARY : RS_PERSISTENT,
1289 : : false, false, false, false);
1290 : :
1291 [ + + ]: 162 : if (reserve_wal)
1292 : : {
1293 : 161 : ReplicationSlotReserveWal();
1294 : :
1295 : 161 : ReplicationSlotMarkDirty();
1296 : :
1297 : : /* Write this slot to disk if it's a permanent one. */
1298 [ + + ]: 161 : if (!cmd->temporary)
1299 : 4 : ReplicationSlotSave();
1300 : : }
1301 : : }
1302 : : else
1303 : : {
1304 : : LogicalDecodingContext *ctx;
1305 : 373 : bool need_full_snapshot = false;
1306 : :
1307 : : Assert(cmd->kind == REPLICATION_KIND_LOGICAL);
1308 : :
1309 : 373 : CheckLogicalDecodingRequirements(false);
1310 : :
1311 : : /*
1312 : : * Initially create persistent slot as ephemeral - that allows us to
1313 : : * nicely handle errors during initialization because it'll get
1314 : : * dropped if this transaction fails. We'll make it persistent at the
1315 : : * end. Temporary slots can be created as temporary from beginning as
1316 : : * they get dropped on error as well.
1317 : : */
1318 : 373 : ReplicationSlotCreate(cmd->slotname, true,
1319 [ - + ]: 373 : cmd->temporary ? RS_TEMPORARY : RS_EPHEMERAL,
1320 : : two_phase, false, failover, false);
1321 : :
1322 : : /*
1323 : : * Do options check early so that we can bail before calling the
1324 : : * DecodingContextFindStartpoint which can take long time.
1325 : : */
1326 [ + + ]: 373 : if (snapshot_action == CRS_EXPORT_SNAPSHOT)
1327 : : {
1328 [ - + ]: 2 : if (IsTransactionBlock())
1329 [ # # ]: 0 : ereport(ERROR,
1330 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1331 : : (errmsg("%s must not be called inside a transaction",
1332 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'export')")));
1333 : :
1334 : 2 : need_full_snapshot = true;
1335 : : }
1336 [ + + ]: 371 : else if (snapshot_action == CRS_USE_SNAPSHOT)
1337 : : {
1338 [ - + ]: 217 : if (!IsTransactionBlock())
1339 [ # # ]: 0 : ereport(ERROR,
1340 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1341 : : (errmsg("%s must be called inside a transaction",
1342 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
1343 : :
1344 [ - + ]: 217 : if (XactIsoLevel != XACT_REPEATABLE_READ)
1345 [ # # ]: 0 : ereport(ERROR,
1346 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1347 : : (errmsg("%s must be called in REPEATABLE READ isolation mode transaction",
1348 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
1349 [ - + ]: 217 : if (!XactReadOnly)
1350 [ # # ]: 0 : ereport(ERROR,
1351 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1352 : : (errmsg("%s must be called in a read-only transaction",
1353 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
1354 : :
1355 [ - + ]: 217 : if (FirstSnapshotSet)
1356 [ # # ]: 0 : ereport(ERROR,
1357 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1358 : : (errmsg("%s must be called before any query",
1359 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
1360 : :
1361 [ - + ]: 217 : if (IsSubTransaction())
1362 [ # # ]: 0 : ereport(ERROR,
1363 : : /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
1364 : : (errmsg("%s must not be called in a subtransaction",
1365 : : "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
1366 : :
1367 : 217 : need_full_snapshot = true;
1368 : : }
1369 : :
1370 : : /*
1371 : : * Ensure the logical decoding is enabled before initializing the
1372 : : * logical decoding context.
1373 : : */
1374 : 373 : EnsureLogicalDecodingEnabled();
1375 : :
1376 : : /* See the comment in create_logical_replication_slot() */
1377 : : Assert(RecoveryInProgress() || IsLogicalDecodingEnabled());
1378 : :
1379 : 373 : ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot,
1380 : : false,
1381 : : InvalidXLogRecPtr,
1382 : 373 : XL_ROUTINE(.page_read = logical_read_xlog_page,
1383 : : .segment_open = WalSndSegmentOpen,
1384 : : .segment_close = wal_segment_close),
1385 : : WalSndPrepareWrite, WalSndWriteData,
1386 : : WalSndUpdateProgress);
1387 : :
1388 : : /*
1389 : : * Signal that we don't need the timeout mechanism. We're just
1390 : : * creating the replication slot and don't yet accept feedback
1391 : : * messages or send keepalives. As we possibly need to wait for
1392 : : * further WAL the walsender would otherwise possibly be killed too
1393 : : * soon.
1394 : : */
1395 : 372 : last_reply_timestamp = 0;
1396 : :
1397 : : /* build initial snapshot, might take a while */
1398 : 372 : DecodingContextFindStartpoint(ctx);
1399 : :
1400 : : /*
1401 : : * Export or use the snapshot if we've been asked to do so.
1402 : : *
1403 : : * NB. We will convert the snapbuild.c kind of snapshot to normal
1404 : : * snapshot when doing this.
1405 : : */
1406 [ + + ]: 372 : if (snapshot_action == CRS_EXPORT_SNAPSHOT)
1407 : : {
1408 : 1 : snapshot_name = SnapBuildExportSnapshot(ctx->snapshot_builder);
1409 : : }
1410 [ + + ]: 371 : else if (snapshot_action == CRS_USE_SNAPSHOT)
1411 : : {
1412 : : Snapshot snap;
1413 : :
1414 : 217 : snap = SnapBuildInitialSnapshot(ctx->snapshot_builder);
1415 : 217 : RestoreTransactionSnapshot(snap, MyProc);
1416 : : }
1417 : :
1418 : : /* don't need the decoding context anymore */
1419 : 372 : FreeDecodingContext(ctx);
1420 : :
1421 [ + - ]: 372 : if (!cmd->temporary)
1422 : 372 : ReplicationSlotPersist();
1423 : : }
1424 : :
1425 : 534 : snprintf(xloc, sizeof(xloc), "%X/%08X",
1426 : 534 : LSN_FORMAT_ARGS(MyReplicationSlot->data.confirmed_flush));
1427 : :
1428 : 534 : dest = CreateDestReceiver(DestRemoteSimple);
1429 : :
1430 : : /*----------
1431 : : * Need a tuple descriptor representing four columns:
1432 : : * - first field: the slot name
1433 : : * - second field: LSN at which we became consistent
1434 : : * - third field: exported snapshot's name
1435 : : * - fourth field: output plugin
1436 : : */
1437 : 534 : tupdesc = CreateTemplateTupleDesc(4);
1438 : 534 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "slot_name",
1439 : : TEXTOID, -1, 0);
1440 : 534 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "consistent_point",
1441 : : TEXTOID, -1, 0);
1442 : 534 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "snapshot_name",
1443 : : TEXTOID, -1, 0);
1444 : 534 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "output_plugin",
1445 : : TEXTOID, -1, 0);
1446 : 534 : TupleDescFinalize(tupdesc);
1447 : :
1448 : : /* prepare for projection of tuples */
1449 : 534 : tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
1450 : :
1451 : : /* slot_name */
1452 : 534 : slot_name = NameStr(MyReplicationSlot->data.name);
1453 : 534 : values[0] = CStringGetTextDatum(slot_name);
1454 : :
1455 : : /* consistent wal location */
1456 : 534 : values[1] = CStringGetTextDatum(xloc);
1457 : :
1458 : : /* snapshot name, or NULL if none */
1459 [ + + ]: 534 : if (snapshot_name != NULL)
1460 : 1 : values[2] = CStringGetTextDatum(snapshot_name);
1461 : : else
1462 : 533 : nulls[2] = true;
1463 : :
1464 : : /* plugin, or NULL if none */
1465 [ + + ]: 534 : if (cmd->plugin != NULL)
1466 : 372 : values[3] = CStringGetTextDatum(cmd->plugin);
1467 : : else
1468 : 162 : nulls[3] = true;
1469 : :
1470 : : /* send it to dest */
1471 : 534 : do_tup_output(tstate, values, nulls);
1472 : 534 : end_tup_output(tstate);
1473 : :
1474 : 534 : ReplicationSlotRelease();
1475 : 534 : }
1476 : :
1477 : : /*
1478 : : * Get rid of a replication slot that is no longer wanted.
1479 : : */
1480 : : static void
1481 : 303 : DropReplicationSlot(DropReplicationSlotCmd *cmd)
1482 : : {
1483 : 303 : ReplicationSlotDrop(cmd->slotname, !cmd->wait);
1484 : 301 : }
1485 : :
1486 : : /*
1487 : : * Change the definition of a replication slot.
1488 : : */
1489 : : static void
1490 : 7 : AlterReplicationSlot(AlterReplicationSlotCmd *cmd)
1491 : : {
1492 : 7 : bool failover_given = false;
1493 : 7 : bool two_phase_given = false;
1494 : : bool failover;
1495 : : bool two_phase;
1496 : :
1497 : : /* Parse options */
1498 [ + - + + : 21 : foreach_ptr(DefElem, defel, cmd->options)
+ + ]
1499 : : {
1500 [ + + ]: 7 : if (strcmp(defel->defname, "failover") == 0)
1501 : : {
1502 [ - + ]: 6 : if (failover_given)
1503 [ # # ]: 0 : ereport(ERROR,
1504 : : (errcode(ERRCODE_SYNTAX_ERROR),
1505 : : errmsg("conflicting or redundant options")));
1506 : 6 : failover_given = true;
1507 : 6 : failover = defGetBoolean(defel);
1508 : : }
1509 [ + - ]: 1 : else if (strcmp(defel->defname, "two_phase") == 0)
1510 : : {
1511 [ - + ]: 1 : if (two_phase_given)
1512 [ # # ]: 0 : ereport(ERROR,
1513 : : (errcode(ERRCODE_SYNTAX_ERROR),
1514 : : errmsg("conflicting or redundant options")));
1515 : 1 : two_phase_given = true;
1516 : 1 : two_phase = defGetBoolean(defel);
1517 : : }
1518 : : else
1519 [ # # ]: 0 : elog(ERROR, "unrecognized option: %s", defel->defname);
1520 : : }
1521 : :
1522 [ + + + + ]: 7 : ReplicationSlotAlter(cmd->slotname,
1523 : : failover_given ? &failover : NULL,
1524 : : two_phase_given ? &two_phase : NULL);
1525 : 5 : }
1526 : :
1527 : : /*
1528 : : * Load previously initiated logical slot and prepare for sending data (via
1529 : : * WalSndLoop).
1530 : : */
1531 : : static void
1532 : 491 : StartLogicalReplication(StartReplicationCmd *cmd)
1533 : : {
1534 : : StringInfoData buf;
1535 : : QueryCompletion qc;
1536 : :
1537 : : /* make sure that our requirements are still fulfilled */
1538 : 491 : CheckLogicalDecodingRequirements(false);
1539 : :
1540 : : Assert(!MyReplicationSlot);
1541 : :
1542 : 489 : ReplicationSlotAcquire(cmd->slotname, true, true);
1543 : :
1544 : : /*
1545 : : * Force a disconnect, so that the decoding code doesn't need to care
1546 : : * about an eventual switch from running in recovery, to running in a
1547 : : * normal environment. Client code is expected to handle reconnects.
1548 : : */
1549 [ + + - + ]: 484 : if (am_cascading_walsender && !RecoveryInProgress())
1550 : : {
1551 [ # # ]: 0 : ereport(LOG,
1552 : : (errmsg("terminating walsender process after promotion")));
1553 : 0 : got_STOPPING = true;
1554 : : }
1555 : :
1556 : : /*
1557 : : * Create our decoding context, making it start at the previously ack'ed
1558 : : * position.
1559 : : *
1560 : : * Do this before sending a CopyBothResponse message, so that any errors
1561 : : * are reported early.
1562 : : */
1563 : 483 : logical_decoding_ctx =
1564 : 484 : CreateDecodingContext(cmd->startpoint, cmd->options, false,
1565 : 484 : XL_ROUTINE(.page_read = logical_read_xlog_page,
1566 : : .segment_open = WalSndSegmentOpen,
1567 : : .segment_close = wal_segment_close),
1568 : : WalSndPrepareWrite, WalSndWriteData,
1569 : : WalSndUpdateProgress);
1570 : 483 : xlogreader = logical_decoding_ctx->reader;
1571 : :
1572 : 483 : WalSndSetState(WALSNDSTATE_CATCHUP);
1573 : :
1574 : : /* Send a CopyBothResponse message, and start streaming */
1575 : 483 : pq_beginmessage(&buf, PqMsg_CopyBothResponse);
1576 : 483 : pq_sendbyte(&buf, 0);
1577 : 483 : pq_sendint16(&buf, 0);
1578 : 483 : pq_endmessage(&buf);
1579 : 483 : pq_flush();
1580 : :
1581 : : /* Start reading WAL from the oldest required WAL. */
1582 : 483 : XLogBeginRead(logical_decoding_ctx->reader,
1583 : 483 : MyReplicationSlot->data.restart_lsn);
1584 : :
1585 : : /*
1586 : : * Report the location after which we'll send out further commits as the
1587 : : * current sentPtr.
1588 : : */
1589 : 483 : sentPtr = MyReplicationSlot->data.confirmed_flush;
1590 : :
1591 : : /* Also update the sent position status in shared memory */
1592 : 483 : SpinLockAcquire(&MyWalSnd->mutex);
1593 : 483 : MyWalSnd->sentPtr = MyReplicationSlot->data.restart_lsn;
1594 : 483 : SpinLockRelease(&MyWalSnd->mutex);
1595 : :
1596 : 483 : replication_active = true;
1597 : :
1598 : 483 : SyncRepInitConfig();
1599 : :
1600 : : /* Main loop of walsender */
1601 : 483 : WalSndLoop(XLogSendLogical);
1602 : :
1603 : 212 : FreeDecodingContext(logical_decoding_ctx);
1604 : 212 : ReplicationSlotRelease();
1605 : :
1606 : 212 : replication_active = false;
1607 [ - + ]: 212 : if (got_STOPPING)
1608 : 0 : proc_exit(0);
1609 : 212 : WalSndSetState(WALSNDSTATE_STARTUP);
1610 : :
1611 : : /* Get out of COPY mode (CommandComplete). */
1612 : 212 : SetQueryCompletion(&qc, CMDTAG_COPY, 0);
1613 : 212 : EndCommand(&qc, DestRemote, false);
1614 : 212 : }
1615 : :
1616 : : /*
1617 : : * LogicalDecodingContext 'prepare_write' callback.
1618 : : *
1619 : : * Prepare a write into a StringInfo.
1620 : : *
1621 : : * Don't do anything lasting in here, it's quite possible that nothing will be done
1622 : : * with the data.
1623 : : */
1624 : : static void
1625 : 206132 : WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write)
1626 : : {
1627 : : /* can't have sync rep confused by sending the same LSN several times */
1628 [ + + ]: 206132 : if (!last_write)
1629 : 469 : lsn = InvalidXLogRecPtr;
1630 : :
1631 : 206132 : resetStringInfo(ctx->out);
1632 : :
1633 : 206132 : pq_sendbyte(ctx->out, PqReplMsg_WALData);
1634 : 206132 : pq_sendint64(ctx->out, lsn); /* dataStart */
1635 : 206132 : pq_sendint64(ctx->out, lsn); /* walEnd */
1636 : :
1637 : : /*
1638 : : * Fill out the sendtime later, just as it's done in XLogSendPhysical, but
1639 : : * reserve space here.
1640 : : */
1641 : 206132 : pq_sendint64(ctx->out, 0); /* sendtime */
1642 : 206132 : }
1643 : :
1644 : : /*
1645 : : * LogicalDecodingContext 'write' callback.
1646 : : *
1647 : : * Actually write out data previously prepared by WalSndPrepareWrite out to
1648 : : * the network. Take as long as needed, but process replies from the other
1649 : : * side and check timeouts during that.
1650 : : */
1651 : : static void
1652 : 206132 : WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
1653 : : bool last_write)
1654 : : {
1655 : : TimestampTz now;
1656 : :
1657 : : /*
1658 : : * Fill the send timestamp last, so that it is taken as late as possible.
1659 : : * This is somewhat ugly, but the protocol is set as it's already used for
1660 : : * several releases by streaming physical replication.
1661 : : */
1662 : 206132 : resetStringInfo(&tmpbuf);
1663 : 206132 : now = GetCurrentTimestamp();
1664 : 206132 : pq_sendint64(&tmpbuf, now);
1665 : 206132 : memcpy(&ctx->out->data[1 + sizeof(int64) + sizeof(int64)],
1666 : 206132 : tmpbuf.data, sizeof(int64));
1667 : :
1668 : : /* output previously gathered data in a CopyData packet */
1669 : 206132 : pq_putmessage_noblock(PqMsg_CopyData, ctx->out->data, ctx->out->len);
1670 : :
1671 [ - + ]: 206132 : CHECK_FOR_INTERRUPTS();
1672 : :
1673 : : /* Try to flush pending output to the client */
1674 [ + + ]: 206132 : if (pq_flush_if_writable() != 0)
1675 : 8 : WalSndShutdown();
1676 : :
1677 : : /* Try taking fast path unless we get too close to walsender timeout. */
1678 [ + - ]: 206124 : if (now < TimestampTzPlusMilliseconds(last_reply_timestamp,
1679 : 206124 : wal_sender_timeout / 2) &&
1680 [ + + ]: 206124 : !pq_is_send_pending())
1681 : : {
1682 : 205583 : return;
1683 : : }
1684 : :
1685 : : /* If we have pending write here, go to slow path */
1686 : 541 : ProcessPendingWrites();
1687 : : }
1688 : :
1689 : : /*
1690 : : * Handle configuration reload.
1691 : : *
1692 : : * Process the pending configuration file reload and reinitializes synchronous
1693 : : * replication settings. Also releases any waiters that may now be satisfied due
1694 : : * to changes in synchronous replication requirements.
1695 : : */
1696 : : static void
1697 : 1178407 : WalSndHandleConfigReload(void)
1698 : : {
1699 [ + + ]: 1178407 : if (!ConfigReloadPending)
1700 : 1178369 : return;
1701 : :
1702 : 38 : ConfigReloadPending = false;
1703 : 38 : ProcessConfigFile(PGC_SIGHUP);
1704 : 38 : SyncRepInitConfig();
1705 : :
1706 : : /*
1707 : : * Recheck and release any now-satisfied waiters after config reload
1708 : : * changes synchronous replication requirements (e.g., reducing the number
1709 : : * of sync standbys or changing the standby names).
1710 : : */
1711 [ + + ]: 38 : if (!am_cascading_walsender)
1712 : 34 : SyncRepReleaseWaiters();
1713 : : }
1714 : :
1715 : : /*
1716 : : * Wait until there is no pending write. Also process replies from the other
1717 : : * side and check timeouts during that.
1718 : : */
1719 : : static void
1720 : 541 : ProcessPendingWrites(void)
1721 : : {
1722 : : for (;;)
1723 : 739 : {
1724 : : long sleeptime;
1725 : :
1726 : : /* Check for input from the client */
1727 : 1280 : ProcessRepliesIfAny();
1728 : :
1729 : : /* die if timeout was reached */
1730 : 1280 : WalSndCheckTimeOut();
1731 : :
1732 : : /*
1733 : : * During shutdown, die if the shutdown timeout expires. Call this
1734 : : * before WalSndComputeSleeptime() so the timeout is considered when
1735 : : * computing sleep time.
1736 : : */
1737 : 1280 : WalSndCheckShutdownTimeout();
1738 : :
1739 : : /* Send keepalive if the time has come */
1740 : 1279 : WalSndKeepaliveIfNecessary();
1741 : :
1742 [ + + ]: 1279 : if (!pq_is_send_pending())
1743 : 540 : break;
1744 : :
1745 : 739 : sleeptime = WalSndComputeSleeptime(GetCurrentTimestamp());
1746 : :
1747 : : /* Sleep until something happens or we time out */
1748 : 739 : WalSndWait(WL_SOCKET_WRITEABLE | WL_SOCKET_READABLE, sleeptime,
1749 : : WAIT_EVENT_WAL_SENDER_WRITE_DATA);
1750 : :
1751 : : /* Clear any already-pending wakeups */
1752 : 739 : ResetLatch(MyLatch);
1753 : :
1754 [ - + ]: 739 : CHECK_FOR_INTERRUPTS();
1755 : :
1756 : : /* Process any requests or signals received recently */
1757 : 739 : WalSndHandleConfigReload();
1758 : :
1759 : : /* Try to flush pending output to the client */
1760 [ - + ]: 739 : if (pq_flush_if_writable() != 0)
1761 : 0 : WalSndShutdown();
1762 : : }
1763 : :
1764 : : /* reactivate latch so WalSndLoop knows to continue */
1765 : 540 : SetLatch(MyLatch);
1766 : 540 : }
1767 : :
1768 : : /*
1769 : : * LogicalDecodingContext 'update_progress' callback.
1770 : : *
1771 : : * Write the current position to the lag tracker (see XLogSendPhysical).
1772 : : *
1773 : : * When skipping empty transactions, send a keepalive message if necessary.
1774 : : */
1775 : : static void
1776 : 3326 : WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
1777 : : bool skipped_xact)
1778 : : {
1779 : : static TimestampTz sendTime = 0;
1780 : 3326 : TimestampTz now = GetCurrentTimestamp();
1781 : 3326 : bool pending_writes = false;
1782 : 3326 : bool end_xact = ctx->end_xact;
1783 : :
1784 : : /*
1785 : : * Track lag no more than once per WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS to
1786 : : * avoid flooding the lag tracker when we commit frequently.
1787 : : *
1788 : : * We don't have a mechanism to get the ack for any LSN other than end
1789 : : * xact LSN from the downstream. So, we track lag only for end of
1790 : : * transaction LSN.
1791 : : */
1792 : : #define WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS 1000
1793 [ + + + + ]: 3326 : if (end_xact && TimestampDifferenceExceeds(sendTime, now,
1794 : : WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS))
1795 : : {
1796 : 372 : LagTrackerWrite(lsn, now);
1797 : 372 : sendTime = now;
1798 : : }
1799 : :
1800 : : /*
1801 : : * When skipping empty transactions in synchronous replication, we send a
1802 : : * keepalive message to avoid delaying such transactions.
1803 : : *
1804 : : * It is okay to check sync_standbys_status without lock here as in the
1805 : : * worst case we will just send an extra keepalive message when it is
1806 : : * really not required.
1807 : : */
1808 [ + + ]: 3326 : if (skipped_xact &&
1809 [ + - + - ]: 953 : SyncRepRequested() &&
1810 [ - + ]: 953 : (((volatile WalSndCtlData *) WalSndCtl)->sync_standbys_status & SYNC_STANDBY_DEFINED))
1811 : : {
1812 : 0 : WalSndKeepalive(false, lsn);
1813 : :
1814 : : /* Try to flush pending output to the client */
1815 [ # # ]: 0 : if (pq_flush_if_writable() != 0)
1816 : 0 : WalSndShutdown();
1817 : :
1818 : : /* If we have pending write here, make sure it's actually flushed */
1819 [ # # ]: 0 : if (pq_is_send_pending())
1820 : 0 : pending_writes = true;
1821 : : }
1822 : :
1823 : : /*
1824 : : * Process pending writes if any or try to send a keepalive if required.
1825 : : * We don't need to try sending keep alive messages at the transaction end
1826 : : * as that will be done at a later point in time. This is required only
1827 : : * for large transactions where we don't send any changes to the
1828 : : * downstream and the receiver can timeout due to that.
1829 : : */
1830 [ + - + + ]: 3326 : if (pending_writes || (!end_xact &&
1831 [ - + ]: 1749 : now >= TimestampTzPlusMilliseconds(last_reply_timestamp,
1832 : : wal_sender_timeout / 2)))
1833 : 0 : ProcessPendingWrites();
1834 : 3326 : }
1835 : :
1836 : : /*
1837 : : * Wake up the logical walsender processes with logical failover slots if the
1838 : : * currently acquired physical slot is specified in synchronized_standby_slots GUC.
1839 : : */
1840 : : void
1841 : 43376 : PhysicalWakeupLogicalWalSnd(void)
1842 : : {
1843 : : Assert(MyReplicationSlot && SlotIsPhysical(MyReplicationSlot));
1844 : :
1845 : : /*
1846 : : * If we are running in a standby, there is no need to wake up walsenders.
1847 : : * This is because we do not support syncing slots to cascading standbys,
1848 : : * so, there are no walsenders waiting for standbys to catch up.
1849 : : */
1850 [ + + ]: 43376 : if (RecoveryInProgress())
1851 : 58 : return;
1852 : :
1853 [ + + ]: 43318 : if (SlotExistsInSyncStandbySlots(NameStr(MyReplicationSlot->data.name)))
1854 : 8 : ConditionVariableBroadcast(&WalSndCtl->wal_confirm_rcv_cv);
1855 : : }
1856 : :
1857 : : /*
1858 : : * Returns true if not all standbys have caught up to the flushed position
1859 : : * (flushed_lsn) when the current acquired slot is a logical failover
1860 : : * slot and we are streaming; otherwise, returns false.
1861 : : *
1862 : : * If returning true, the function sets the appropriate wait event in
1863 : : * wait_event; otherwise, wait_event is set to 0.
1864 : : */
1865 : : static bool
1866 : 21551 : NeedToWaitForStandbys(XLogRecPtr flushed_lsn, uint32 *wait_event)
1867 : : {
1868 [ + + ]: 21551 : int elevel = got_STOPPING ? ERROR : WARNING;
1869 : : bool failover_slot;
1870 : :
1871 [ + + + + ]: 21551 : failover_slot = (replication_active && MyReplicationSlot->data.failover);
1872 : :
1873 : : /*
1874 : : * Note that after receiving the shutdown signal, an ERROR is reported if
1875 : : * any slots are dropped, invalidated, or inactive. This measure is taken
1876 : : * to prevent the walsender from waiting indefinitely.
1877 : : */
1878 [ + + + + ]: 21551 : if (failover_slot && !StandbySlotsHaveCaughtup(flushed_lsn, elevel))
1879 : : {
1880 : 16 : *wait_event = WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION;
1881 : 16 : return true;
1882 : : }
1883 : :
1884 : 21535 : *wait_event = 0;
1885 : 21535 : return false;
1886 : : }
1887 : :
1888 : : /*
1889 : : * Returns true if we need to wait for WALs to be flushed to disk, or if not
1890 : : * all standbys have caught up to the flushed position (flushed_lsn) when the
1891 : : * current acquired slot is a logical failover slot and we are
1892 : : * streaming; otherwise, returns false.
1893 : : *
1894 : : * If returning true, the function sets the appropriate wait event in
1895 : : * wait_event; otherwise, wait_event is set to 0.
1896 : : */
1897 : : static bool
1898 : 32326 : NeedToWaitForWal(XLogRecPtr target_lsn, XLogRecPtr flushed_lsn,
1899 : : uint32 *wait_event)
1900 : : {
1901 : : /* Check if we need to wait for WALs to be flushed to disk */
1902 [ + + ]: 32326 : if (target_lsn > flushed_lsn)
1903 : : {
1904 : 13707 : *wait_event = WAIT_EVENT_WAL_SENDER_WAIT_FOR_WAL;
1905 : 13707 : return true;
1906 : : }
1907 : :
1908 : : /* Check if the standby slots have caught up to the flushed position */
1909 : 18619 : return NeedToWaitForStandbys(flushed_lsn, wait_event);
1910 : : }
1911 : :
1912 : : /*
1913 : : * Wait till WAL < loc is flushed to disk so it can be safely sent to client.
1914 : : *
1915 : : * If the walsender holds a logical failover slot, we also wait for all the
1916 : : * specified streaming replication standby servers to confirm receipt of WAL
1917 : : * up to RecentFlushPtr. It is beneficial to wait here for the confirmation
1918 : : * up to RecentFlushPtr rather than waiting before transmitting each change
1919 : : * to logical subscribers, which is already covered by RecentFlushPtr.
1920 : : *
1921 : : * Returns end LSN of flushed WAL. Normally this will be >= loc, but if we
1922 : : * detect a shutdown request (either from postmaster or client) we will return
1923 : : * early, so caller must always check.
1924 : : */
1925 : : static XLogRecPtr
1926 : 21947 : WalSndWaitForWal(XLogRecPtr loc)
1927 : : {
1928 : : int wakeEvents;
1929 : 21947 : uint32 wait_event = 0;
1930 : : static XLogRecPtr RecentFlushPtr = InvalidXLogRecPtr;
1931 : 21947 : TimestampTz last_flush = 0;
1932 : :
1933 : : /*
1934 : : * Fast path to avoid acquiring the spinlock in case we already know we
1935 : : * have enough WAL available and all the standby servers have confirmed
1936 : : * receipt of WAL up to RecentFlushPtr. This is particularly interesting
1937 : : * if we're far behind.
1938 : : */
1939 [ + + ]: 21947 : if (XLogRecPtrIsValid(RecentFlushPtr) &&
1940 [ + + ]: 21292 : !NeedToWaitForWal(loc, RecentFlushPtr, &wait_event))
1941 : 16588 : return RecentFlushPtr;
1942 : :
1943 : : /*
1944 : : * Within the loop, we wait for the necessary WALs to be flushed to disk
1945 : : * first, followed by waiting for standbys to catch up if there are enough
1946 : : * WALs (see NeedToWaitForWal()) or upon receiving the shutdown signal.
1947 : : */
1948 : : for (;;)
1949 : 8843 : {
1950 : 14202 : bool wait_for_standby_at_stop = false;
1951 : : long sleeptime;
1952 : : TimestampTz now;
1953 : :
1954 : : /* Clear any already-pending wakeups */
1955 : 14202 : ResetLatch(MyLatch);
1956 : :
1957 [ + + ]: 14202 : CHECK_FOR_INTERRUPTS();
1958 : :
1959 : : /* Process any requests or signals received recently */
1960 : 14195 : WalSndHandleConfigReload();
1961 : :
1962 : : /* Check for input from the client */
1963 : 14195 : ProcessRepliesIfAny();
1964 : :
1965 : : /*
1966 : : * If we're shutting down, trigger pending WAL to be written out,
1967 : : * otherwise we'd possibly end up waiting for WAL that never gets
1968 : : * written, because walwriter has shut down already.
1969 : : *
1970 : : * Note that GetXLogInsertEndRecPtr() is used to obtain the WAL flush
1971 : : * request location instead of GetXLogInsertRecPtr(). Because if the
1972 : : * last WAL record ends at a page boundary, GetXLogInsertRecPtr() can
1973 : : * return an LSN pointing past the page header, which may cause
1974 : : * XLogFlush() to report an error.
1975 : : */
1976 [ + + + + ]: 13966 : if (got_STOPPING && !RecoveryInProgress())
1977 : 2168 : XLogFlush(GetXLogInsertEndRecPtr());
1978 : :
1979 : : /*
1980 : : * To avoid the scenario where standbys need to catch up to a newer
1981 : : * WAL location in each iteration, we update our idea of the currently
1982 : : * flushed position only if we are not waiting for standbys to catch
1983 : : * up.
1984 : : */
1985 [ + + ]: 13966 : if (wait_event != WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION)
1986 : : {
1987 [ + + ]: 13951 : if (!RecoveryInProgress())
1988 : 13018 : RecentFlushPtr = GetFlushRecPtr(NULL);
1989 : : else
1990 : 933 : RecentFlushPtr = GetXLogReplayRecPtr(NULL);
1991 : : }
1992 : :
1993 : : /*
1994 : : * If postmaster asked us to stop and the standby slots have caught up
1995 : : * to the flushed position, don't wait anymore.
1996 : : *
1997 : : * It's important to do this check after the recomputation of
1998 : : * RecentFlushPtr, so we can send all remaining data before shutting
1999 : : * down.
2000 : : */
2001 [ + + ]: 13966 : if (got_STOPPING)
2002 : : {
2003 [ + + ]: 2932 : if (NeedToWaitForStandbys(RecentFlushPtr, &wait_event))
2004 : 2 : wait_for_standby_at_stop = true;
2005 : : else
2006 : 2930 : break;
2007 : : }
2008 : :
2009 : : /*
2010 : : * We only send regular messages to the client for full decoded
2011 : : * transactions, but a synchronous replication and walsender shutdown
2012 : : * possibly are waiting for a later location. So, before sleeping, we
2013 : : * send a ping containing the flush location. If the receiver is
2014 : : * otherwise idle, this keepalive will trigger a reply. Processing the
2015 : : * reply will update these MyWalSnd locations.
2016 : : */
2017 [ + + ]: 11036 : if (MyWalSnd->flush < sentPtr &&
2018 [ + + ]: 2641 : MyWalSnd->write < sentPtr &&
2019 [ + - ]: 2029 : !waiting_for_ping_response)
2020 : 2029 : WalSndKeepalive(false, InvalidXLogRecPtr);
2021 : :
2022 : : /*
2023 : : * Exit the loop if already caught up and doesn't need to wait for
2024 : : * standby slots.
2025 : : */
2026 [ + + ]: 11036 : if (!wait_for_standby_at_stop &&
2027 [ + + ]: 11034 : !NeedToWaitForWal(loc, RecentFlushPtr, &wait_event))
2028 : 2017 : break;
2029 : :
2030 : : /*
2031 : : * Waiting for new WAL or waiting for standbys to catch up. Since we
2032 : : * need to wait, we're now caught up.
2033 : : */
2034 : 9019 : WalSndCaughtUp = true;
2035 : :
2036 : : /*
2037 : : * Try to flush any pending output to the client.
2038 : : */
2039 [ - + ]: 9019 : if (pq_flush_if_writable() != 0)
2040 : 0 : WalSndShutdown();
2041 : :
2042 : : /*
2043 : : * If we have received CopyDone from the client, sent CopyDone
2044 : : * ourselves, and the output buffer is empty, it's time to exit
2045 : : * streaming, so fail the current WAL fetch request.
2046 : : */
2047 [ + + + - ]: 9019 : if (streamingDoneReceiving && streamingDoneSending &&
2048 [ + - ]: 175 : !pq_is_send_pending())
2049 : 175 : break;
2050 : :
2051 : : /* die if timeout was reached */
2052 : 8844 : WalSndCheckTimeOut();
2053 : :
2054 : : /*
2055 : : * During shutdown, die if the shutdown timeout expires. Call this
2056 : : * before WalSndComputeSleeptime() so the timeout is considered when
2057 : : * computing sleep time.
2058 : : */
2059 : 8844 : WalSndCheckShutdownTimeout();
2060 : :
2061 : : /* Send keepalive if the time has come */
2062 : 8843 : WalSndKeepaliveIfNecessary();
2063 : :
2064 : : /*
2065 : : * Sleep until something happens or we time out. Also wait for the
2066 : : * socket becoming writable, if there's still pending output.
2067 : : * Otherwise we might sit on sendable output data while waiting for
2068 : : * new WAL to be generated. (But if we have nothing to send, we don't
2069 : : * want to wake on socket-writable.)
2070 : : */
2071 : 8843 : now = GetCurrentTimestamp();
2072 : 8843 : sleeptime = WalSndComputeSleeptime(now);
2073 : :
2074 : 8843 : wakeEvents = WL_SOCKET_READABLE;
2075 : :
2076 [ - + ]: 8843 : if (pq_is_send_pending())
2077 : 0 : wakeEvents |= WL_SOCKET_WRITEABLE;
2078 : :
2079 : : Assert(wait_event != 0);
2080 : :
2081 : : /* Report IO statistics, if needed */
2082 [ + + ]: 8843 : if (TimestampDifferenceExceeds(last_flush, now,
2083 : : WALSENDER_STATS_FLUSH_INTERVAL))
2084 : : {
2085 : 1732 : pgstat_flush_io(false);
2086 : 1732 : (void) pgstat_flush_backend(false, PGSTAT_BACKEND_FLUSH_IO);
2087 : 1732 : last_flush = now;
2088 : : }
2089 : :
2090 : 8843 : WalSndWait(wakeEvents, sleeptime, wait_event);
2091 : : }
2092 : :
2093 : : /* reactivate latch so WalSndLoop knows to continue */
2094 : 5122 : SetLatch(MyLatch);
2095 : 5122 : return RecentFlushPtr;
2096 : : }
2097 : :
2098 : : /*
2099 : : * Execute an incoming replication command.
2100 : : *
2101 : : * Returns true if the cmd_string was recognized as WalSender command, false
2102 : : * if not.
2103 : : */
2104 : : bool
2105 : 6101 : exec_replication_command(const char *cmd_string)
2106 : : {
2107 : : yyscan_t scanner;
2108 : : int parse_rc;
2109 : : Node *cmd_node;
2110 : : const char *cmdtag;
2111 : 6101 : MemoryContext old_context = CurrentMemoryContext;
2112 : :
2113 : : /* We save and re-use the cmd_context across calls */
2114 : : static MemoryContext cmd_context = NULL;
2115 : :
2116 : : /*
2117 : : * If WAL sender has been told that shutdown is getting close, switch its
2118 : : * status accordingly to handle the next replication commands correctly.
2119 : : */
2120 [ - + ]: 6101 : if (got_STOPPING)
2121 : 0 : WalSndSetState(WALSNDSTATE_STOPPING);
2122 : :
2123 : : /*
2124 : : * Throw error if in stopping mode. We need prevent commands that could
2125 : : * generate WAL while the shutdown checkpoint is being written. To be
2126 : : * safe, we just prohibit all new commands.
2127 : : */
2128 [ - + ]: 6101 : if (MyWalSnd->state == WALSNDSTATE_STOPPING)
2129 [ # # ]: 0 : ereport(ERROR,
2130 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2131 : : errmsg("cannot execute new commands while WAL sender is in stopping mode")));
2132 : :
2133 : : /*
2134 : : * CREATE_REPLICATION_SLOT ... LOGICAL exports a snapshot until the next
2135 : : * command arrives. Clean up the old stuff if there's anything.
2136 : : */
2137 : 6101 : SnapBuildClearExportedSnapshot();
2138 : :
2139 [ - + ]: 6101 : CHECK_FOR_INTERRUPTS();
2140 : :
2141 : : /*
2142 : : * Prepare to parse and execute the command.
2143 : : *
2144 : : * Because replication command execution can involve beginning or ending
2145 : : * transactions, we need a working context that will survive that, so we
2146 : : * make it a child of TopMemoryContext. That in turn creates a hazard of
2147 : : * long-lived memory leaks if we lose track of the working context. We
2148 : : * deal with that by creating it only once per walsender, and resetting it
2149 : : * for each new command. (Normally this reset is a no-op, but if the
2150 : : * prior exec_replication_command call failed with an error, it won't be.)
2151 : : *
2152 : : * This is subtler than it looks. The transactions we manage can extend
2153 : : * across replication commands, indeed SnapBuildClearExportedSnapshot
2154 : : * might have just ended one. Because transaction exit will revert to the
2155 : : * memory context that was current at transaction start, we need to be
2156 : : * sure that that context is still valid. That motivates re-using the
2157 : : * same cmd_context rather than making a new one each time.
2158 : : */
2159 [ + + ]: 6101 : if (cmd_context == NULL)
2160 : 1358 : cmd_context = AllocSetContextCreate(TopMemoryContext,
2161 : : "Replication command context",
2162 : : ALLOCSET_DEFAULT_SIZES);
2163 : : else
2164 : 4743 : MemoryContextReset(cmd_context);
2165 : :
2166 : 6101 : MemoryContextSwitchTo(cmd_context);
2167 : :
2168 : 6101 : replication_scanner_init(cmd_string, &scanner);
2169 : :
2170 : : /*
2171 : : * Is it a WalSender command?
2172 : : */
2173 [ + + ]: 6101 : if (!replication_scanner_is_replication_command(scanner))
2174 : : {
2175 : : /* Nope; clean up and get out. */
2176 : 2671 : replication_scanner_finish(scanner);
2177 : :
2178 : 2671 : MemoryContextSwitchTo(old_context);
2179 : 2671 : MemoryContextReset(cmd_context);
2180 : :
2181 : : /* XXX this is a pretty random place to make this check */
2182 [ - + ]: 2671 : if (MyDatabaseId == InvalidOid)
2183 [ # # ]: 0 : ereport(ERROR,
2184 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2185 : : errmsg("cannot execute SQL commands in WAL sender for physical replication")));
2186 : :
2187 : : /* Tell the caller that this wasn't a WalSender command. */
2188 : 2671 : return false;
2189 : : }
2190 : :
2191 : : /*
2192 : : * Looks like a WalSender command, so parse it.
2193 : : */
2194 : 3430 : parse_rc = replication_yyparse(&cmd_node, scanner);
2195 [ - + ]: 3430 : if (parse_rc != 0)
2196 [ # # ]: 0 : ereport(ERROR,
2197 : : (errcode(ERRCODE_SYNTAX_ERROR),
2198 : : errmsg_internal("replication command parser returned %d",
2199 : : parse_rc)));
2200 : 3430 : replication_scanner_finish(scanner);
2201 : :
2202 : : /*
2203 : : * Report query to various monitoring facilities. For this purpose, we
2204 : : * report replication commands just like SQL commands.
2205 : : */
2206 : 3430 : debug_query_string = cmd_string;
2207 : :
2208 : 3430 : pgstat_report_activity(STATE_RUNNING, cmd_string);
2209 : :
2210 : : /*
2211 : : * Log replication command if log_replication_commands is enabled. Even
2212 : : * when it's disabled, log the command with DEBUG1 level for backward
2213 : : * compatibility.
2214 : : */
2215 [ + - + - ]: 3430 : ereport(log_replication_commands ? LOG : DEBUG1,
2216 : : (errmsg("received replication command: %s", cmd_string)));
2217 : :
2218 : : /*
2219 : : * Disallow replication commands in aborted transaction blocks.
2220 : : */
2221 [ - + ]: 3430 : if (IsAbortedTransactionBlockState())
2222 [ # # ]: 0 : ereport(ERROR,
2223 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2224 : : errmsg("current transaction is aborted, "
2225 : : "commands ignored until end of transaction block")));
2226 : :
2227 [ - + ]: 3430 : CHECK_FOR_INTERRUPTS();
2228 : :
2229 : : /*
2230 : : * Allocate buffers that will be used for each outgoing and incoming
2231 : : * message. We do this just once per command to reduce palloc overhead.
2232 : : */
2233 : 3430 : initStringInfo(&output_message);
2234 : 3430 : initStringInfo(&reply_message);
2235 : 3430 : initStringInfo(&tmpbuf);
2236 : :
2237 [ + + + + : 3430 : switch (cmd_node->type)
+ + + + +
+ - ]
2238 : : {
2239 : 868 : case T_IdentifySystemCmd:
2240 : 868 : cmdtag = "IDENTIFY_SYSTEM";
2241 : 868 : set_ps_display(cmdtag);
2242 : 868 : IdentifySystem();
2243 : 868 : EndReplicationCommand(cmdtag);
2244 : 868 : break;
2245 : :
2246 : 6 : case T_ReadReplicationSlotCmd:
2247 : 6 : cmdtag = "READ_REPLICATION_SLOT";
2248 : 6 : set_ps_display(cmdtag);
2249 : 6 : ReadReplicationSlot((ReadReplicationSlotCmd *) cmd_node);
2250 : 5 : EndReplicationCommand(cmdtag);
2251 : 5 : break;
2252 : :
2253 : 207 : case T_BaseBackupCmd:
2254 : 207 : cmdtag = "BASE_BACKUP";
2255 : 207 : set_ps_display(cmdtag);
2256 : 207 : PreventInTransactionBlock(true, cmdtag);
2257 : 207 : SendBaseBackup((BaseBackupCmd *) cmd_node, uploaded_manifest);
2258 : 180 : EndReplicationCommand(cmdtag);
2259 : 180 : break;
2260 : :
2261 : 536 : case T_CreateReplicationSlotCmd:
2262 : 536 : cmdtag = "CREATE_REPLICATION_SLOT";
2263 : 536 : set_ps_display(cmdtag);
2264 : 536 : CreateReplicationSlot((CreateReplicationSlotCmd *) cmd_node);
2265 : 534 : EndReplicationCommand(cmdtag);
2266 : 534 : break;
2267 : :
2268 : 303 : case T_DropReplicationSlotCmd:
2269 : 303 : cmdtag = "DROP_REPLICATION_SLOT";
2270 : 303 : set_ps_display(cmdtag);
2271 : 303 : DropReplicationSlot((DropReplicationSlotCmd *) cmd_node);
2272 : 301 : EndReplicationCommand(cmdtag);
2273 : 301 : break;
2274 : :
2275 : 7 : case T_AlterReplicationSlotCmd:
2276 : 7 : cmdtag = "ALTER_REPLICATION_SLOT";
2277 : 7 : set_ps_display(cmdtag);
2278 : 7 : AlterReplicationSlot((AlterReplicationSlotCmd *) cmd_node);
2279 : 5 : EndReplicationCommand(cmdtag);
2280 : 5 : break;
2281 : :
2282 : 815 : case T_StartReplicationCmd:
2283 : : {
2284 : 815 : StartReplicationCmd *cmd = (StartReplicationCmd *) cmd_node;
2285 : :
2286 : 815 : cmdtag = "START_REPLICATION";
2287 : 815 : set_ps_display(cmdtag);
2288 : 815 : PreventInTransactionBlock(true, cmdtag);
2289 : :
2290 [ + + ]: 815 : if (cmd->kind == REPLICATION_KIND_PHYSICAL)
2291 : 324 : StartReplication(cmd);
2292 : : else
2293 : 491 : StartLogicalReplication(cmd);
2294 : :
2295 : : /* dupe, but necessary per libpqrcv_endstreaming */
2296 : 387 : EndReplicationCommand(cmdtag);
2297 : :
2298 : : Assert(xlogreader != NULL);
2299 : 387 : break;
2300 : : }
2301 : :
2302 : 16 : case T_TimeLineHistoryCmd:
2303 : 16 : cmdtag = "TIMELINE_HISTORY";
2304 : 16 : set_ps_display(cmdtag);
2305 : 16 : PreventInTransactionBlock(true, cmdtag);
2306 : 16 : SendTimeLineHistory((TimeLineHistoryCmd *) cmd_node);
2307 : 16 : EndReplicationCommand(cmdtag);
2308 : 16 : break;
2309 : :
2310 : 659 : case T_VariableShowStmt:
2311 : : {
2312 : 659 : DestReceiver *dest = CreateDestReceiver(DestRemoteSimple);
2313 : 659 : VariableShowStmt *n = (VariableShowStmt *) cmd_node;
2314 : :
2315 : 659 : cmdtag = "SHOW";
2316 : 659 : set_ps_display(cmdtag);
2317 : :
2318 : : /* syscache access needs a transaction environment */
2319 : 659 : StartTransactionCommand();
2320 : 659 : GetPGVariable(n->name, dest);
2321 : 659 : CommitTransactionCommand();
2322 : 659 : EndReplicationCommand(cmdtag);
2323 : : }
2324 : 659 : break;
2325 : :
2326 : 13 : case T_UploadManifestCmd:
2327 : 13 : cmdtag = "UPLOAD_MANIFEST";
2328 : 13 : set_ps_display(cmdtag);
2329 : 13 : PreventInTransactionBlock(true, cmdtag);
2330 : 13 : UploadManifest();
2331 : 12 : EndReplicationCommand(cmdtag);
2332 : 12 : break;
2333 : :
2334 : 0 : default:
2335 [ # # ]: 0 : elog(ERROR, "unrecognized replication command node tag: %u",
2336 : : cmd_node->type);
2337 : : }
2338 : :
2339 : : /*
2340 : : * Done. Revert to caller's memory context, and clean out the cmd_context
2341 : : * to recover memory right away.
2342 : : */
2343 : 2967 : MemoryContextSwitchTo(old_context);
2344 : 2967 : MemoryContextReset(cmd_context);
2345 : :
2346 : : /*
2347 : : * We need not update ps display or pg_stat_activity, because PostgresMain
2348 : : * will reset those to "idle". But we must reset debug_query_string to
2349 : : * ensure it doesn't become a dangling pointer.
2350 : : */
2351 : 2967 : debug_query_string = NULL;
2352 : :
2353 : 2967 : return true;
2354 : : }
2355 : :
2356 : : /*
2357 : : * Process any incoming messages while streaming. Also checks if the remote
2358 : : * end has closed the connection.
2359 : : */
2360 : : static void
2361 : 1178948 : ProcessRepliesIfAny(void)
2362 : : {
2363 : : unsigned char firstchar;
2364 : : int maxmsglen;
2365 : : int r;
2366 : 1178948 : bool received = false;
2367 : :
2368 : 1178948 : last_processing = GetCurrentTimestamp();
2369 : :
2370 : : /*
2371 : : * If we already received a CopyDone from the frontend, any subsequent
2372 : : * message is the beginning of a new command, and should be processed in
2373 : : * the main processing loop.
2374 : : */
2375 [ + + ]: 2486523 : while (!streamingDoneReceiving)
2376 : : {
2377 : 1306785 : pq_startmsgread();
2378 : 1306785 : r = pq_getbyte_if_available(&firstchar);
2379 [ + + ]: 1306785 : if (r < 0)
2380 : : {
2381 : : /* unexpected error or EOF */
2382 [ + - ]: 17 : ereport(COMMERROR,
2383 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2384 : : errmsg("unexpected EOF on standby connection")));
2385 : 17 : proc_exit(0);
2386 : : }
2387 [ + + ]: 1306768 : if (r == 0)
2388 : : {
2389 : : /* no data available without blocking */
2390 : 1177812 : pq_endmsgread();
2391 : 1177812 : break;
2392 : : }
2393 : :
2394 : : /* Validate message type and set packet size limit */
2395 [ + + - ]: 128956 : switch (firstchar)
2396 : : {
2397 : 128240 : case PqMsg_CopyData:
2398 : 128240 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
2399 : 128240 : break;
2400 : 716 : case PqMsg_CopyDone:
2401 : : case PqMsg_Terminate:
2402 : 716 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
2403 : 716 : break;
2404 : 0 : default:
2405 [ # # ]: 0 : ereport(FATAL,
2406 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2407 : : errmsg("invalid standby message type \"%c\"",
2408 : : firstchar)));
2409 : : maxmsglen = 0; /* keep compiler quiet */
2410 : : break;
2411 : : }
2412 : :
2413 : : /* Read the message contents */
2414 : 128956 : resetStringInfo(&reply_message);
2415 [ - + ]: 128956 : if (pq_getmessage(&reply_message, maxmsglen))
2416 : : {
2417 [ # # ]: 0 : ereport(COMMERROR,
2418 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2419 : : errmsg("unexpected EOF on standby connection")));
2420 : 0 : proc_exit(0);
2421 : : }
2422 : :
2423 : : /* ... and process it */
2424 [ + + + - ]: 128956 : switch (firstchar)
2425 : : {
2426 : : /*
2427 : : * PqMsg_CopyData means a standby reply wrapped in a CopyData
2428 : : * packet.
2429 : : */
2430 : 128240 : case PqMsg_CopyData:
2431 : 128240 : ProcessStandbyMessage();
2432 : 128240 : received = true;
2433 : 128240 : break;
2434 : :
2435 : : /*
2436 : : * PqMsg_CopyDone means the standby requested to finish
2437 : : * streaming. Reply with CopyDone, if we had not sent that
2438 : : * already.
2439 : : */
2440 : 387 : case PqMsg_CopyDone:
2441 [ + + ]: 387 : if (!streamingDoneSending)
2442 : : {
2443 : 375 : pq_putmessage_noblock(PqMsg_CopyDone, NULL, 0);
2444 : 375 : streamingDoneSending = true;
2445 : : }
2446 : :
2447 : 387 : streamingDoneReceiving = true;
2448 : 387 : received = true;
2449 : 387 : break;
2450 : :
2451 : : /*
2452 : : * PqMsg_Terminate means that the standby is closing down the
2453 : : * socket.
2454 : : */
2455 : 329 : case PqMsg_Terminate:
2456 : 329 : proc_exit(0);
2457 : :
2458 : 128627 : default:
2459 : : Assert(false); /* NOT REACHED */
2460 : : }
2461 : : }
2462 : :
2463 : : /*
2464 : : * Save the last reply timestamp if we've received at least one reply.
2465 : : */
2466 [ + + ]: 1178602 : if (received)
2467 : : {
2468 : 66320 : last_reply_timestamp = last_processing;
2469 : 66320 : waiting_for_ping_response = false;
2470 : : }
2471 : 1178602 : }
2472 : :
2473 : : /*
2474 : : * Process a status update message received from standby.
2475 : : */
2476 : : static void
2477 : 128240 : ProcessStandbyMessage(void)
2478 : : {
2479 : : char msgtype;
2480 : :
2481 : : /*
2482 : : * Check message type from the first byte.
2483 : : */
2484 : 128240 : msgtype = pq_getmsgbyte(&reply_message);
2485 : :
2486 [ + + + - ]: 128240 : switch (msgtype)
2487 : : {
2488 : 122542 : case PqReplMsg_StandbyStatusUpdate:
2489 : 122542 : ProcessStandbyReplyMessage();
2490 : 122542 : break;
2491 : :
2492 : 163 : case PqReplMsg_HotStandbyFeedback:
2493 : 163 : ProcessStandbyHSFeedbackMessage();
2494 : 163 : break;
2495 : :
2496 : 5535 : case PqReplMsg_PrimaryStatusRequest:
2497 : 5535 : ProcessStandbyPSRequestMessage();
2498 : 5535 : break;
2499 : :
2500 : 0 : default:
2501 [ # # ]: 0 : ereport(COMMERROR,
2502 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2503 : : errmsg("unexpected message type \"%c\"", msgtype)));
2504 : 0 : proc_exit(0);
2505 : : }
2506 : 128240 : }
2507 : :
2508 : : /*
2509 : : * Remember that a walreceiver just confirmed receipt of lsn `lsn`.
2510 : : */
2511 : : static void
2512 : 96090 : PhysicalConfirmReceivedLocation(XLogRecPtr lsn)
2513 : : {
2514 : 96090 : bool changed = false;
2515 : 96090 : ReplicationSlot *slot = MyReplicationSlot;
2516 : :
2517 : : Assert(XLogRecPtrIsValid(lsn));
2518 : 96090 : SpinLockAcquire(&slot->mutex);
2519 [ + + ]: 96090 : if (slot->data.restart_lsn != lsn)
2520 : : {
2521 : 43369 : changed = true;
2522 : 43369 : slot->data.restart_lsn = lsn;
2523 : : }
2524 : 96090 : SpinLockRelease(&slot->mutex);
2525 : :
2526 [ + + ]: 96090 : if (changed)
2527 : : {
2528 : 43369 : ReplicationSlotMarkDirty();
2529 : 43369 : ReplicationSlotsComputeRequiredLSN();
2530 : 43369 : PhysicalWakeupLogicalWalSnd();
2531 : : }
2532 : :
2533 : : /*
2534 : : * One could argue that the slot should be saved to disk now, but that'd
2535 : : * be energy wasted - the worst thing lost information could cause here is
2536 : : * to give wrong information in a statistics view - we'll just potentially
2537 : : * be more conservative in removing files.
2538 : : */
2539 : 96090 : }
2540 : :
2541 : : /*
2542 : : * Regular reply from standby advising of WAL locations on standby server.
2543 : : */
2544 : : static void
2545 : 122542 : ProcessStandbyReplyMessage(void)
2546 : : {
2547 : : XLogRecPtr writePtr,
2548 : : flushPtr,
2549 : : applyPtr;
2550 : : bool replyRequested;
2551 : : TimeOffset writeLag,
2552 : : flushLag,
2553 : : applyLag;
2554 : : bool clearLagTimes;
2555 : : TimestampTz now;
2556 : : TimestampTz replyTime;
2557 : :
2558 : : static XLogRecPtr prevWritePtr = InvalidXLogRecPtr;
2559 : : static XLogRecPtr prevFlushPtr = InvalidXLogRecPtr;
2560 : : static XLogRecPtr prevApplyPtr = InvalidXLogRecPtr;
2561 : :
2562 : : /* the caller already consumed the msgtype byte */
2563 : 122542 : writePtr = pq_getmsgint64(&reply_message);
2564 : 122542 : flushPtr = pq_getmsgint64(&reply_message);
2565 : 122542 : applyPtr = pq_getmsgint64(&reply_message);
2566 : 122542 : replyTime = pq_getmsgint64(&reply_message);
2567 : 122542 : replyRequested = pq_getmsgbyte(&reply_message);
2568 : :
2569 [ + + ]: 122542 : if (message_level_is_interesting(DEBUG2))
2570 : : {
2571 : : char *replyTimeStr;
2572 : :
2573 : : /* Copy because timestamptz_to_str returns a static buffer */
2574 : 663 : replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
2575 : :
2576 [ + - - + ]: 663 : elog(DEBUG2, "write %X/%08X flush %X/%08X apply %X/%08X%s reply_time %s",
2577 : : LSN_FORMAT_ARGS(writePtr),
2578 : : LSN_FORMAT_ARGS(flushPtr),
2579 : : LSN_FORMAT_ARGS(applyPtr),
2580 : : replyRequested ? " (reply requested)" : "",
2581 : : replyTimeStr);
2582 : :
2583 : 663 : pfree(replyTimeStr);
2584 : : }
2585 : :
2586 : : /* See if we can compute the round-trip lag for these positions. */
2587 : 122542 : now = GetCurrentTimestamp();
2588 : 122542 : writeLag = LagTrackerRead(SYNC_REP_WAIT_WRITE, writePtr, now);
2589 : 122542 : flushLag = LagTrackerRead(SYNC_REP_WAIT_FLUSH, flushPtr, now);
2590 : 122542 : applyLag = LagTrackerRead(SYNC_REP_WAIT_APPLY, applyPtr, now);
2591 : :
2592 : : /*
2593 : : * If the standby reports that it has fully replayed the WAL, and the
2594 : : * write/flush/apply positions remain unchanged across two consecutive
2595 : : * reply messages, forget the lag times measured when it last
2596 : : * wrote/flushed/applied a WAL record.
2597 : : *
2598 : : * The second message with unchanged positions typically results from
2599 : : * wal_receiver_status_interval expiring on the standby, so lag values are
2600 : : * usually cleared after that interval when there is no activity. This
2601 : : * avoids displaying stale lag data until more WAL traffic arrives.
2602 : : */
2603 [ + + ]: 11284 : clearLagTimes = (applyPtr == sentPtr && flushPtr == sentPtr &&
2604 [ + + + + : 142236 : writePtr == prevWritePtr && flushPtr == prevFlushPtr &&
+ + ]
2605 [ + + ]: 8410 : applyPtr == prevApplyPtr);
2606 : :
2607 : 122542 : prevWritePtr = writePtr;
2608 : 122542 : prevFlushPtr = flushPtr;
2609 : 122542 : prevApplyPtr = applyPtr;
2610 : :
2611 : : /* Send a reply if the standby requested one. */
2612 [ - + ]: 122542 : if (replyRequested)
2613 : 0 : WalSndKeepalive(false, InvalidXLogRecPtr);
2614 : :
2615 : : /*
2616 : : * Update shared state for this WalSender process based on reply data from
2617 : : * standby.
2618 : : */
2619 : : {
2620 : 122542 : WalSnd *walsnd = MyWalSnd;
2621 : :
2622 : 122542 : SpinLockAcquire(&walsnd->mutex);
2623 : 122542 : walsnd->write = writePtr;
2624 : 122542 : walsnd->flush = flushPtr;
2625 : 122542 : walsnd->apply = applyPtr;
2626 [ + + + + ]: 122542 : if (writeLag != -1 || clearLagTimes)
2627 : 72647 : walsnd->writeLag = writeLag;
2628 [ + + + + ]: 122542 : if (flushLag != -1 || clearLagTimes)
2629 : 90773 : walsnd->flushLag = flushLag;
2630 [ + + + + ]: 122542 : if (applyLag != -1 || clearLagTimes)
2631 : 98876 : walsnd->applyLag = applyLag;
2632 : 122542 : walsnd->replyTime = replyTime;
2633 : 122542 : SpinLockRelease(&walsnd->mutex);
2634 : : }
2635 : :
2636 [ + + ]: 122542 : if (!am_cascading_walsender)
2637 : 122228 : SyncRepReleaseWaiters();
2638 : :
2639 : : /*
2640 : : * Advance our local xmin horizon when the client confirmed a flush.
2641 : : */
2642 [ + + + + ]: 122542 : if (MyReplicationSlot && XLogRecPtrIsValid(flushPtr))
2643 : : {
2644 [ + + ]: 119539 : if (SlotIsLogical(MyReplicationSlot))
2645 : 23449 : LogicalConfirmReceivedLocation(flushPtr);
2646 : : else
2647 : 96090 : PhysicalConfirmReceivedLocation(flushPtr);
2648 : : }
2649 : 122542 : }
2650 : :
2651 : : /* compute new replication slot xmin horizon if needed */
2652 : : static void
2653 : 73 : PhysicalReplicationSlotNewXmin(TransactionId feedbackXmin, TransactionId feedbackCatalogXmin)
2654 : : {
2655 : 73 : bool changed = false;
2656 : 73 : ReplicationSlot *slot = MyReplicationSlot;
2657 : :
2658 : 73 : SpinLockAcquire(&slot->mutex);
2659 : 73 : MyProc->xmin = InvalidTransactionId;
2660 : :
2661 : : /*
2662 : : * For physical replication we don't need the interlock provided by xmin
2663 : : * and effective_xmin since the consequences of a missed increase are
2664 : : * limited to query cancellations, so set both at once.
2665 : : */
2666 [ + + + + ]: 73 : if (!TransactionIdIsNormal(slot->data.xmin) ||
2667 [ + + ]: 35 : !TransactionIdIsNormal(feedbackXmin) ||
2668 : 35 : TransactionIdPrecedes(slot->data.xmin, feedbackXmin))
2669 : : {
2670 : 49 : changed = true;
2671 : 49 : slot->data.xmin = feedbackXmin;
2672 : 49 : slot->effective_xmin = feedbackXmin;
2673 : : }
2674 [ + + + + ]: 73 : if (!TransactionIdIsNormal(slot->data.catalog_xmin) ||
2675 [ + + ]: 19 : !TransactionIdIsNormal(feedbackCatalogXmin) ||
2676 : 19 : TransactionIdPrecedes(slot->data.catalog_xmin, feedbackCatalogXmin))
2677 : : {
2678 : 55 : changed = true;
2679 : 55 : slot->data.catalog_xmin = feedbackCatalogXmin;
2680 : 55 : slot->effective_catalog_xmin = feedbackCatalogXmin;
2681 : : }
2682 : 73 : SpinLockRelease(&slot->mutex);
2683 : :
2684 [ + + ]: 73 : if (changed)
2685 : : {
2686 : 59 : ReplicationSlotMarkDirty();
2687 : 59 : ReplicationSlotsComputeRequiredXmin(false);
2688 : : }
2689 : 73 : }
2690 : :
2691 : : /*
2692 : : * Check that the provided xmin/epoch are sane, that is, not in the future
2693 : : * and not so far back as to be already wrapped around.
2694 : : *
2695 : : * Epoch of nextXid should be same as standby, or if the counter has
2696 : : * wrapped, then one greater than standby.
2697 : : *
2698 : : * This check doesn't care about whether clog exists for these xids
2699 : : * at all.
2700 : : */
2701 : : static bool
2702 : 77 : TransactionIdInRecentPast(TransactionId xid, uint32 epoch)
2703 : : {
2704 : : FullTransactionId nextFullXid;
2705 : : TransactionId nextXid;
2706 : : uint32 nextEpoch;
2707 : :
2708 : 77 : nextFullXid = ReadNextFullTransactionId();
2709 : 77 : nextXid = XidFromFullTransactionId(nextFullXid);
2710 : 77 : nextEpoch = EpochFromFullTransactionId(nextFullXid);
2711 : :
2712 [ + - ]: 77 : if (xid <= nextXid)
2713 : : {
2714 [ - + ]: 77 : if (epoch != nextEpoch)
2715 : 0 : return false;
2716 : : }
2717 : : else
2718 : : {
2719 [ # # ]: 0 : if (epoch + 1 != nextEpoch)
2720 : 0 : return false;
2721 : : }
2722 : :
2723 [ - + ]: 77 : if (!TransactionIdPrecedesOrEquals(xid, nextXid))
2724 : 0 : return false; /* epoch OK, but it's wrapped around */
2725 : :
2726 : 77 : return true;
2727 : : }
2728 : :
2729 : : /*
2730 : : * Hot Standby feedback
2731 : : */
2732 : : static void
2733 : 163 : ProcessStandbyHSFeedbackMessage(void)
2734 : : {
2735 : : TransactionId feedbackXmin;
2736 : : uint32 feedbackEpoch;
2737 : : TransactionId feedbackCatalogXmin;
2738 : : uint32 feedbackCatalogEpoch;
2739 : : TimestampTz replyTime;
2740 : :
2741 : : /*
2742 : : * Decipher the reply message. The caller already consumed the msgtype
2743 : : * byte. See XLogWalRcvSendHSFeedback() in walreceiver.c for the creation
2744 : : * of this message.
2745 : : */
2746 : 163 : replyTime = pq_getmsgint64(&reply_message);
2747 : 163 : feedbackXmin = pq_getmsgint(&reply_message, 4);
2748 : 163 : feedbackEpoch = pq_getmsgint(&reply_message, 4);
2749 : 163 : feedbackCatalogXmin = pq_getmsgint(&reply_message, 4);
2750 : 163 : feedbackCatalogEpoch = pq_getmsgint(&reply_message, 4);
2751 : :
2752 [ + + ]: 163 : if (message_level_is_interesting(DEBUG2))
2753 : : {
2754 : : char *replyTimeStr;
2755 : :
2756 : : /* Copy because timestamptz_to_str returns a static buffer */
2757 : 4 : replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
2758 : :
2759 [ + - ]: 4 : elog(DEBUG2, "hot standby feedback xmin %u epoch %u, catalog_xmin %u epoch %u reply_time %s",
2760 : : feedbackXmin,
2761 : : feedbackEpoch,
2762 : : feedbackCatalogXmin,
2763 : : feedbackCatalogEpoch,
2764 : : replyTimeStr);
2765 : :
2766 : 4 : pfree(replyTimeStr);
2767 : : }
2768 : :
2769 : : /*
2770 : : * Update shared state for this WalSender process based on reply data from
2771 : : * standby.
2772 : : */
2773 : : {
2774 : 163 : WalSnd *walsnd = MyWalSnd;
2775 : :
2776 : 163 : SpinLockAcquire(&walsnd->mutex);
2777 : 163 : walsnd->replyTime = replyTime;
2778 : 163 : SpinLockRelease(&walsnd->mutex);
2779 : : }
2780 : :
2781 : : /*
2782 : : * Unset WalSender's xmins if the feedback message values are invalid.
2783 : : * This happens when the downstream turned hot_standby_feedback off.
2784 : : */
2785 [ + + ]: 163 : if (!TransactionIdIsNormal(feedbackXmin)
2786 [ + - ]: 112 : && !TransactionIdIsNormal(feedbackCatalogXmin))
2787 : : {
2788 : 112 : MyProc->xmin = InvalidTransactionId;
2789 [ + + ]: 112 : if (MyReplicationSlot != NULL)
2790 : 25 : PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
2791 : 112 : return;
2792 : : }
2793 : :
2794 : : /*
2795 : : * Check that the provided xmin/epoch are sane, that is, not in the future
2796 : : * and not so far back as to be already wrapped around. Ignore if not.
2797 : : */
2798 [ + - ]: 51 : if (TransactionIdIsNormal(feedbackXmin) &&
2799 [ - + ]: 51 : !TransactionIdInRecentPast(feedbackXmin, feedbackEpoch))
2800 : 0 : return;
2801 : :
2802 [ + + ]: 51 : if (TransactionIdIsNormal(feedbackCatalogXmin) &&
2803 [ - + ]: 26 : !TransactionIdInRecentPast(feedbackCatalogXmin, feedbackCatalogEpoch))
2804 : 0 : return;
2805 : :
2806 : : /*
2807 : : * Set the WalSender's xmin equal to the standby's requested xmin, so that
2808 : : * the xmin will be taken into account by GetSnapshotData() /
2809 : : * ComputeXidHorizons(). This will hold back the removal of dead rows and
2810 : : * thereby prevent the generation of cleanup conflicts on the standby
2811 : : * server.
2812 : : *
2813 : : * There is a small window for a race condition here: although we just
2814 : : * checked that feedbackXmin precedes nextXid, the nextXid could have
2815 : : * gotten advanced between our fetching it and applying the xmin below,
2816 : : * perhaps far enough to make feedbackXmin wrap around. In that case the
2817 : : * xmin we set here would be "in the future" and have no effect. No point
2818 : : * in worrying about this since it's too late to save the desired data
2819 : : * anyway. Assuming that the standby sends us an increasing sequence of
2820 : : * xmins, this could only happen during the first reply cycle, else our
2821 : : * own xmin would prevent nextXid from advancing so far.
2822 : : *
2823 : : * We don't bother taking the ProcArrayLock here. Setting the xmin field
2824 : : * is assumed atomic, and there's no real need to prevent concurrent
2825 : : * horizon determinations. (If we're moving our xmin forward, this is
2826 : : * obviously safe, and if we're moving it backwards, well, the data is at
2827 : : * risk already since a VACUUM could already have determined the horizon.)
2828 : : *
2829 : : * If we're using a replication slot we reserve the xmin via that,
2830 : : * otherwise via the walsender's PGPROC entry. We can only track the
2831 : : * catalog xmin separately when using a slot, so we store the least of the
2832 : : * two provided when not using a slot.
2833 : : *
2834 : : * XXX: It might make sense to generalize the ephemeral slot concept and
2835 : : * always use the slot mechanism to handle the feedback xmin.
2836 : : */
2837 [ + + ]: 51 : if (MyReplicationSlot != NULL) /* XXX: persistency configurable? */
2838 : 48 : PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
2839 : : else
2840 : : {
2841 [ - + ]: 3 : if (TransactionIdIsNormal(feedbackCatalogXmin)
2842 [ # # ]: 0 : && TransactionIdPrecedes(feedbackCatalogXmin, feedbackXmin))
2843 : 0 : MyProc->xmin = feedbackCatalogXmin;
2844 : : else
2845 : 3 : MyProc->xmin = feedbackXmin;
2846 : : }
2847 : : }
2848 : :
2849 : : /*
2850 : : * Process the request for a primary status update message.
2851 : : */
2852 : : static void
2853 : 5535 : ProcessStandbyPSRequestMessage(void)
2854 : : {
2855 : 5535 : XLogRecPtr lsn = InvalidXLogRecPtr;
2856 : : TransactionId oldestXidInCommit;
2857 : : TransactionId oldestGXidInCommit;
2858 : : FullTransactionId nextFullXid;
2859 : : FullTransactionId fullOldestXidInCommit;
2860 : 5535 : WalSnd *walsnd = MyWalSnd;
2861 : : TimestampTz replyTime;
2862 : :
2863 : : /*
2864 : : * This shouldn't happen because we don't support getting primary status
2865 : : * message from standby.
2866 : : */
2867 [ - + ]: 5535 : if (RecoveryInProgress())
2868 [ # # ]: 0 : elog(ERROR, "the primary status is unavailable during recovery");
2869 : :
2870 : 5535 : replyTime = pq_getmsgint64(&reply_message);
2871 : :
2872 : : /*
2873 : : * Update shared state for this WalSender process based on reply data from
2874 : : * standby.
2875 : : */
2876 : 5535 : SpinLockAcquire(&walsnd->mutex);
2877 : 5535 : walsnd->replyTime = replyTime;
2878 : 5535 : SpinLockRelease(&walsnd->mutex);
2879 : :
2880 : : /*
2881 : : * Consider transactions in the current database, as only these are the
2882 : : * ones replicated.
2883 : : */
2884 : 5535 : oldestXidInCommit = GetOldestActiveTransactionId(true, false);
2885 : 5535 : oldestGXidInCommit = TwoPhaseGetOldestXidInCommit();
2886 : :
2887 : : /*
2888 : : * Update the oldest xid for standby transmission if an older prepared
2889 : : * transaction exists and is currently in commit phase.
2890 : : */
2891 [ + + + - ]: 11022 : if (TransactionIdIsValid(oldestGXidInCommit) &&
2892 : 5487 : TransactionIdPrecedes(oldestGXidInCommit, oldestXidInCommit))
2893 : 5487 : oldestXidInCommit = oldestGXidInCommit;
2894 : :
2895 : 5535 : nextFullXid = ReadNextFullTransactionId();
2896 : 5535 : fullOldestXidInCommit = FullTransactionIdFromAllowableAt(nextFullXid,
2897 : : oldestXidInCommit);
2898 : :
2899 : : /*
2900 : : * Report the end of the last inserted WAL record rather than the WAL
2901 : : * write position. A transaction that commits asynchronously (with
2902 : : * synchronous_commit = off) clears DELAY_CHKPT_IN_COMMIT without flushing
2903 : : * its commit record, so it is visible to neither the in-commit scan above
2904 : : * nor a write position that has not yet reached its commit record. The
2905 : : * subscriber waits until it has applied and flushed up to the reported
2906 : : * position before advancing its non-removable transaction ID, so the
2907 : : * reported position must cover every transaction that has already
2908 : : * committed, as each of those already carries a commit timestamp earlier
2909 : : * than this reply. A transaction's commit timestamp is written as part
2910 : : * of its commit record, so it cannot have committed without that record
2911 : : * already being at or before the insert position. A transaction that has
2912 : : * determined its commit timestamp but not yet inserted the record is
2913 : : * still in the commit phase, and so is reported by the in-commit scan
2914 : : * above.
2915 : : *
2916 : : * GetXLogInsertEndRecPtr() is used rather than GetXLogInsertRecPtr()
2917 : : * because the latter can return a position past the page header when the
2918 : : * last record ends at a page boundary, which can never match a record end
2919 : : * and would needlessly stall the subscriber's wait.
2920 : : */
2921 : 5535 : lsn = GetXLogInsertEndRecPtr();
2922 : :
2923 [ + + ]: 5535 : elog(DEBUG2, "sending primary status");
2924 : :
2925 : : /* construct the message... */
2926 : 5535 : resetStringInfo(&output_message);
2927 : 5535 : pq_sendbyte(&output_message, PqReplMsg_PrimaryStatusUpdate);
2928 : 5535 : pq_sendint64(&output_message, lsn);
2929 : 5535 : pq_sendint64(&output_message, (int64) U64FromFullTransactionId(fullOldestXidInCommit));
2930 : 5535 : pq_sendint64(&output_message, (int64) U64FromFullTransactionId(nextFullXid));
2931 : 5535 : pq_sendint64(&output_message, GetCurrentTimestamp());
2932 : :
2933 : : /* ... and send it wrapped in CopyData */
2934 : 5535 : pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
2935 : 5535 : }
2936 : :
2937 : : /*
2938 : : * Compute how long send/receive loops should sleep.
2939 : : *
2940 : : * If wal_sender_timeout is enabled we want to wake up in time to send
2941 : : * keepalives and to abort the connection if wal_sender_timeout has been
2942 : : * reached.
2943 : : *
2944 : : * If wal_sender_shutdown_timeout is enabled, during shutdown, we want to
2945 : : * wake up in time to exit when it expires.
2946 : : */
2947 : : static long
2948 : 103774 : WalSndComputeSleeptime(TimestampTz now)
2949 : : {
2950 : : TimestampTz wakeup_time;
2951 : 103774 : long sleeptime = 10000; /* 10 s */
2952 : :
2953 [ + - + + ]: 103774 : if (wal_sender_timeout > 0 && last_reply_timestamp > 0)
2954 : : {
2955 : : /*
2956 : : * At the latest stop sleeping once wal_sender_timeout has been
2957 : : * reached.
2958 : : */
2959 : 103698 : wakeup_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
2960 : : wal_sender_timeout);
2961 : :
2962 : : /*
2963 : : * If no ping has been sent yet, wakeup when it's time to do so.
2964 : : * WalSndKeepaliveIfNecessary() wants to send a keepalive once half of
2965 : : * the timeout passed without a response.
2966 : : */
2967 [ + + ]: 103698 : if (!waiting_for_ping_response)
2968 : 103446 : wakeup_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
2969 : : wal_sender_timeout / 2);
2970 : :
2971 : : /* Compute relative time until wakeup. */
2972 : 103698 : sleeptime = TimestampDifferenceMilliseconds(now, wakeup_time);
2973 : : }
2974 : :
2975 [ + + + + ]: 103774 : if (shutdown_request_timestamp != 0 && wal_sender_shutdown_timeout > 0)
2976 : : {
2977 : : long shutdown_sleeptime;
2978 : :
2979 : 4 : wakeup_time = TimestampTzPlusMilliseconds(shutdown_request_timestamp,
2980 : : wal_sender_shutdown_timeout);
2981 : :
2982 : 4 : shutdown_sleeptime = TimestampDifferenceMilliseconds(now, wakeup_time);
2983 : :
2984 : : /* Choose the earliest wakeup. */
2985 [ + - ]: 4 : if (shutdown_sleeptime < sleeptime)
2986 : 4 : sleeptime = shutdown_sleeptime;
2987 : : }
2988 : :
2989 : 103774 : return sleeptime;
2990 : : }
2991 : :
2992 : : /*
2993 : : * Check whether there have been responses by the client within
2994 : : * wal_sender_timeout and shutdown if not. Using last_processing as the
2995 : : * reference point avoids counting server-side stalls against the client.
2996 : : * However, a long server-side stall can make WalSndKeepaliveIfNecessary()
2997 : : * postdate last_processing by more than wal_sender_timeout. If that happens,
2998 : : * the client must reply almost immediately to avoid a timeout. This rarely
2999 : : * affects the default configuration, under which clients spontaneously send a
3000 : : * message every standby_message_timeout = wal_sender_timeout/6 = 10s. We
3001 : : * could eliminate that problem by recognizing timeout expiration at
3002 : : * wal_sender_timeout/2 after the keepalive.
3003 : : */
3004 : : static void
3005 : 1172798 : WalSndCheckTimeOut(void)
3006 : : {
3007 : : TimestampTz timeout;
3008 : :
3009 : : /* don't bail out if we're doing something that doesn't require timeouts */
3010 [ + + ]: 1172798 : if (last_reply_timestamp <= 0)
3011 : 29 : return;
3012 : :
3013 : 1172769 : timeout = TimestampTzPlusMilliseconds(last_reply_timestamp,
3014 : : wal_sender_timeout);
3015 : :
3016 [ + - - + ]: 1172769 : if (wal_sender_timeout > 0 && last_processing >= timeout)
3017 : : {
3018 : : /*
3019 : : * Since typically expiration of replication timeout means
3020 : : * communication problem, we don't send the error message to the
3021 : : * standby.
3022 : : */
3023 [ # # ]: 0 : ereport(COMMERROR,
3024 : : (errmsg("terminating walsender process due to replication timeout")));
3025 : :
3026 : 0 : WalSndShutdown();
3027 : : }
3028 : : }
3029 : :
3030 : : /*
3031 : : * Check whether the walsender process should terminate due to the expiration
3032 : : * of wal_sender_shutdown_timeout after the receipt of a shutdown request.
3033 : : */
3034 : : static void
3035 : 1172892 : WalSndCheckShutdownTimeout(void)
3036 : : {
3037 : : TimestampTz now;
3038 : :
3039 : : /* Do nothing if shutdown has not been requested yet */
3040 [ + + + - ]: 1172892 : if (!(got_STOPPING || got_SIGUSR2))
3041 : 1170475 : return;
3042 : :
3043 : : /* Terminate immediately if the timeout is set to 0 */
3044 [ - + ]: 2417 : if (wal_sender_shutdown_timeout == 0)
3045 : 0 : WalSndDoneImmediate();
3046 : :
3047 : : /*
3048 : : * Record the shutdown request timestamp even if
3049 : : * wal_sender_shutdown_timeout is disabled (-1), since the setting may
3050 : : * change during shutdown and the timestamp will be needed in that case.
3051 : : */
3052 [ + + ]: 2417 : if (shutdown_request_timestamp == 0)
3053 : : {
3054 : 51 : shutdown_request_timestamp = GetCurrentTimestamp();
3055 : 51 : return;
3056 : : }
3057 : :
3058 : : /* Do not check the timeout if it's disabled */
3059 [ + + ]: 2366 : if (wal_sender_shutdown_timeout == -1)
3060 : 1756 : return;
3061 : :
3062 : : /* Terminate immediately if the timeout expires */
3063 : 610 : now = GetCurrentTimestamp();
3064 [ + + ]: 610 : if (TimestampDifferenceExceeds(shutdown_request_timestamp, now,
3065 : : wal_sender_shutdown_timeout))
3066 : 4 : WalSndDoneImmediate();
3067 : : }
3068 : :
3069 : : /* Main loop of walsender process that streams the WAL over Copy messages. */
3070 : : static void
3071 : 804 : WalSndLoop(WalSndSendDataCallback send_data)
3072 : : {
3073 : 804 : TimestampTz last_flush = 0;
3074 : :
3075 : : /*
3076 : : * Initialize the last reply timestamp. That enables timeout processing
3077 : : * from hereon.
3078 : : */
3079 : 804 : last_reply_timestamp = GetCurrentTimestamp();
3080 : 804 : waiting_for_ping_response = false;
3081 : :
3082 : : /*
3083 : : * Loop until we reach the end of this timeline or the client requests to
3084 : : * stop streaming.
3085 : : */
3086 : : for (;;)
3087 : : {
3088 : : /* Clear any already-pending wakeups */
3089 : 1163476 : ResetLatch(MyLatch);
3090 : :
3091 [ + + ]: 1163476 : CHECK_FOR_INTERRUPTS();
3092 : :
3093 : : /* Process any requests or signals received recently */
3094 : 1163473 : WalSndHandleConfigReload();
3095 : :
3096 : : /* Check for input from the client */
3097 : 1163473 : ProcessRepliesIfAny();
3098 : :
3099 : : /*
3100 : : * If we have received CopyDone from the client, sent CopyDone
3101 : : * ourselves, and the output buffer is empty, it's time to exit
3102 : : * streaming.
3103 : : */
3104 [ + + + - ]: 1163356 : if (streamingDoneReceiving && streamingDoneSending &&
3105 [ + + ]: 615 : !pq_is_send_pending())
3106 : 387 : break;
3107 : :
3108 : : /*
3109 : : * If we don't have any pending data in the output buffer, try to send
3110 : : * some more. If there is some, we don't bother to call send_data
3111 : : * again until we've flushed it ... but we'd better assume we are not
3112 : : * caught up.
3113 : : */
3114 [ + + ]: 1162969 : if (!pq_is_send_pending())
3115 : 1118871 : send_data();
3116 : : else
3117 : 44098 : WalSndCaughtUp = false;
3118 : :
3119 : : /* Try to flush pending output to the client */
3120 [ - + ]: 1162721 : if (pq_flush_if_writable() != 0)
3121 : 0 : WalSndShutdown();
3122 : :
3123 : : /* If nothing remains to be sent right now ... */
3124 [ + + + + ]: 1162721 : if (WalSndCaughtUp && !pq_is_send_pending())
3125 : : {
3126 : : /*
3127 : : * If we're in catchup state, move to streaming. This is an
3128 : : * important state change for users to know about, since before
3129 : : * this point data loss might occur if the primary dies and we
3130 : : * need to failover to the standby. The state change is also
3131 : : * important for synchronous replication, since commits that
3132 : : * started to wait at that point might wait for some time.
3133 : : */
3134 [ + + ]: 104771 : if (MyWalSnd->state == WALSNDSTATE_CATCHUP)
3135 : : {
3136 [ + + ]: 750 : ereport(DEBUG1,
3137 : : (errmsg_internal("\"%s\" has now caught up with upstream server",
3138 : : application_name)));
3139 : 750 : WalSndSetState(WALSNDSTATE_STREAMING);
3140 : : }
3141 : :
3142 : : /*
3143 : : * When SIGUSR2 arrives, we send any outstanding logs up to the
3144 : : * shutdown checkpoint record (i.e., the latest record), wait for
3145 : : * them to be replicated to the standby, and exit. This may be a
3146 : : * normal termination at shutdown, or a promotion, the walsender
3147 : : * is not sure which.
3148 : : */
3149 [ + + ]: 104771 : if (got_SIGUSR2)
3150 : 1746 : WalSndDone(send_data);
3151 : : }
3152 : :
3153 : : /* Check for replication timeout. */
3154 : 1162674 : WalSndCheckTimeOut();
3155 : :
3156 : : /*
3157 : : * During shutdown, die if the shutdown timeout expires. Call this
3158 : : * before WalSndComputeSleeptime() so the timeout is considered when
3159 : : * computing sleep time.
3160 : : */
3161 : 1162674 : WalSndCheckShutdownTimeout();
3162 : :
3163 : : /* Send keepalive if the time has come */
3164 : 1162672 : WalSndKeepaliveIfNecessary();
3165 : :
3166 : : /*
3167 : : * Block if we have unsent data. XXX For logical replication, let
3168 : : * WalSndWaitForWal() handle any other blocking; idle receivers need
3169 : : * its additional actions. For physical replication, also block if
3170 : : * caught up; its send_data does not block.
3171 : : *
3172 : : * The IO statistics are reported in WalSndWaitForWal() for the
3173 : : * logical WAL senders.
3174 : : */
3175 [ + + + + ]: 1162672 : if ((WalSndCaughtUp && send_data != XLogSendLogical &&
3176 [ + + + + ]: 1212894 : !streamingDoneSending) ||
3177 : 1110548 : pq_is_send_pending())
3178 : : {
3179 : : long sleeptime;
3180 : : int wakeEvents;
3181 : : TimestampTz now;
3182 : :
3183 [ + + ]: 94145 : if (!streamingDoneReceiving)
3184 : 94117 : wakeEvents = WL_SOCKET_READABLE;
3185 : : else
3186 : 28 : wakeEvents = 0;
3187 : :
3188 : : /*
3189 : : * Use fresh timestamp, not last_processing, to reduce the chance
3190 : : * of reaching wal_sender_timeout before sending a keepalive.
3191 : : */
3192 : 94145 : now = GetCurrentTimestamp();
3193 : 94145 : sleeptime = WalSndComputeSleeptime(now);
3194 : :
3195 [ + + ]: 94145 : if (pq_is_send_pending())
3196 : 44043 : wakeEvents |= WL_SOCKET_WRITEABLE;
3197 : :
3198 : : /* Report IO statistics, if needed */
3199 [ + + ]: 94145 : if (TimestampDifferenceExceeds(last_flush, now,
3200 : : WALSENDER_STATS_FLUSH_INTERVAL))
3201 : : {
3202 : 621 : pgstat_flush_io(false);
3203 : 621 : (void) pgstat_flush_backend(false, PGSTAT_BACKEND_FLUSH_IO);
3204 : 621 : last_flush = now;
3205 : : }
3206 : :
3207 : : /* Sleep until something happens or we time out */
3208 : 94145 : WalSndWait(wakeEvents, sleeptime, WAIT_EVENT_WAL_SENDER_MAIN);
3209 : : }
3210 : : }
3211 : 387 : }
3212 : :
3213 : : /* Initialize a per-walsender data structure for this walsender process */
3214 : : static void
3215 : 1358 : InitWalSenderSlot(void)
3216 : : {
3217 : : int i;
3218 : :
3219 : : /*
3220 : : * WalSndCtl should be set up already (we inherit this by fork() or
3221 : : * EXEC_BACKEND mechanism from the postmaster).
3222 : : */
3223 : : Assert(WalSndCtl != NULL);
3224 : : Assert(MyWalSnd == NULL);
3225 : :
3226 : : /*
3227 : : * Find a free walsender slot and reserve it. This must not fail due to
3228 : : * the prior check for free WAL senders in InitProcess().
3229 : : */
3230 [ + - ]: 2017 : for (i = 0; i < max_wal_senders; i++)
3231 : : {
3232 : 2017 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
3233 : :
3234 : 2017 : SpinLockAcquire(&walsnd->mutex);
3235 : :
3236 [ + + ]: 2017 : if (walsnd->pid != 0)
3237 : : {
3238 : 659 : SpinLockRelease(&walsnd->mutex);
3239 : 659 : continue;
3240 : : }
3241 : : else
3242 : : {
3243 : : /*
3244 : : * Found a free slot. Reserve it for us.
3245 : : */
3246 : 1358 : walsnd->pid = MyProcPid;
3247 : 1358 : walsnd->state = WALSNDSTATE_STARTUP;
3248 : 1358 : walsnd->sentPtr = InvalidXLogRecPtr;
3249 : 1358 : walsnd->needreload = false;
3250 : 1358 : walsnd->write = InvalidXLogRecPtr;
3251 : 1358 : walsnd->flush = InvalidXLogRecPtr;
3252 : 1358 : walsnd->apply = InvalidXLogRecPtr;
3253 : 1358 : walsnd->writeLag = -1;
3254 : 1358 : walsnd->flushLag = -1;
3255 : 1358 : walsnd->applyLag = -1;
3256 : 1358 : walsnd->sync_standby_priority = 0;
3257 : 1358 : walsnd->replyTime = 0;
3258 : :
3259 : : /*
3260 : : * The kind assignment is done here and not in StartReplication()
3261 : : * and StartLogicalReplication(). Indeed, the logical walsender
3262 : : * needs to read WAL records (like snapshot of running
3263 : : * transactions) during the slot creation. So it needs to be woken
3264 : : * up based on its kind.
3265 : : *
3266 : : * The kind assignment could also be done in StartReplication(),
3267 : : * StartLogicalReplication() and CREATE_REPLICATION_SLOT but it
3268 : : * seems better to set it on one place.
3269 : : */
3270 [ + + ]: 1358 : if (MyDatabaseId == InvalidOid)
3271 : 532 : walsnd->kind = REPLICATION_KIND_PHYSICAL;
3272 : : else
3273 : 826 : walsnd->kind = REPLICATION_KIND_LOGICAL;
3274 : :
3275 : 1358 : SpinLockRelease(&walsnd->mutex);
3276 : : /* don't need the lock anymore */
3277 : 1358 : MyWalSnd = walsnd;
3278 : :
3279 : 1358 : break;
3280 : : }
3281 : : }
3282 : :
3283 : : Assert(MyWalSnd != NULL);
3284 : :
3285 : : /* Arrange to clean up at walsender exit */
3286 : 1358 : on_shmem_exit(WalSndKill, 0);
3287 : 1358 : }
3288 : :
3289 : : /* Destroy the per-walsender data structure for this walsender process */
3290 : : static void
3291 : 1358 : WalSndKill(int code, Datum arg)
3292 : : {
3293 : 1358 : WalSnd *walsnd = MyWalSnd;
3294 : :
3295 : : Assert(walsnd != NULL);
3296 : :
3297 : 1358 : MyWalSnd = NULL;
3298 : :
3299 : 1358 : SpinLockAcquire(&walsnd->mutex);
3300 : : /* Mark WalSnd struct as no longer being in use. */
3301 : 1358 : walsnd->pid = 0;
3302 : 1358 : SpinLockRelease(&walsnd->mutex);
3303 : 1358 : }
3304 : :
3305 : : /* XLogReaderRoutine->segment_open callback */
3306 : : static void
3307 : 5364 : WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
3308 : : TimeLineID *tli_p)
3309 : : {
3310 : : char path[MAXPGPATH];
3311 : :
3312 : : /*-------
3313 : : * When reading from a historic timeline, and there is a timeline switch
3314 : : * within this segment, read from the WAL segment belonging to the new
3315 : : * timeline.
3316 : : *
3317 : : * For example, imagine that this server is currently on timeline 5, and
3318 : : * we're streaming timeline 4. The switch from timeline 4 to 5 happened at
3319 : : * 0/13002088. In pg_wal, we have these files:
3320 : : *
3321 : : * ...
3322 : : * 000000040000000000000012
3323 : : * 000000040000000000000013
3324 : : * 000000050000000000000013
3325 : : * 000000050000000000000014
3326 : : * ...
3327 : : *
3328 : : * In this situation, when requested to send the WAL from segment 0x13, on
3329 : : * timeline 4, we read the WAL from file 000000050000000000000013. Archive
3330 : : * recovery prefers files from newer timelines, so if the segment was
3331 : : * restored from the archive on this server, the file belonging to the old
3332 : : * timeline, 000000040000000000000013, might not exist. Their contents are
3333 : : * equal up to the switchpoint, because at a timeline switch, the used
3334 : : * portion of the old segment is copied to the new file.
3335 : : */
3336 : 5364 : *tli_p = sendTimeLine;
3337 [ + + ]: 5364 : if (sendTimeLineIsHistoric)
3338 : : {
3339 : : XLogSegNo endSegNo;
3340 : :
3341 : 592 : XLByteToSeg(sendTimeLineValidUpto, endSegNo, state->segcxt.ws_segsize);
3342 [ + + ]: 592 : if (nextSegNo == endSegNo)
3343 : 8 : *tli_p = sendTimeLineNextTLI;
3344 : : }
3345 : :
3346 : 5364 : XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize);
3347 : 5364 : state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
3348 [ + + ]: 5364 : if (state->seg.ws_file >= 0)
3349 : 5363 : return;
3350 : :
3351 : : /*
3352 : : * If the file is not found, assume it's because the standby asked for a
3353 : : * too old WAL segment that has already been removed or recycled.
3354 : : */
3355 [ + - ]: 1 : if (errno == ENOENT)
3356 : : {
3357 : : char xlogfname[MAXFNAMELEN];
3358 : 1 : int save_errno = errno;
3359 : :
3360 : 1 : XLogFileName(xlogfname, *tli_p, nextSegNo, wal_segment_size);
3361 : 1 : errno = save_errno;
3362 [ + - ]: 1 : ereport(ERROR,
3363 : : (errcode_for_file_access(),
3364 : : errmsg("requested WAL segment %s has already been removed",
3365 : : xlogfname)));
3366 : : }
3367 : : else
3368 [ # # ]: 0 : ereport(ERROR,
3369 : : (errcode_for_file_access(),
3370 : : errmsg("could not open file \"%s\": %m",
3371 : : path)));
3372 : : }
3373 : :
3374 : : /*
3375 : : * Send out the WAL in its normal physical/stored form.
3376 : : *
3377 : : * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
3378 : : * but not yet sent to the client, and buffer it in the libpq output
3379 : : * buffer.
3380 : : *
3381 : : * If there is no unsent WAL remaining, WalSndCaughtUp is set to true,
3382 : : * otherwise WalSndCaughtUp is set to false.
3383 : : */
3384 : : static void
3385 : 191046 : XLogSendPhysical(void)
3386 : : {
3387 : : XLogRecPtr SendRqstPtr;
3388 : : XLogRecPtr startptr;
3389 : : XLogRecPtr endptr;
3390 : : Size nbytes;
3391 : : XLogSegNo segno;
3392 : : WALReadError errinfo;
3393 : : Size rbytes;
3394 : :
3395 : : /* If requested switch the WAL sender to the stopping state. */
3396 [ + + ]: 191046 : if (got_STOPPING)
3397 : 896 : WalSndSetState(WALSNDSTATE_STOPPING);
3398 : :
3399 [ + + ]: 191046 : if (streamingDoneSending)
3400 : : {
3401 : 50210 : WalSndCaughtUp = true;
3402 : 82955 : return;
3403 : : }
3404 : :
3405 : : /* Figure out how far we can safely send the WAL. */
3406 [ + + ]: 140836 : if (sendTimeLineIsHistoric)
3407 : : {
3408 : : /*
3409 : : * Streaming an old timeline that's in this server's history, but is
3410 : : * not the one we're currently inserting or replaying. It can be
3411 : : * streamed up to the point where we switched off that timeline.
3412 : : */
3413 : 33 : SendRqstPtr = sendTimeLineValidUpto;
3414 : : }
3415 [ + + ]: 140803 : else if (am_cascading_walsender)
3416 : : {
3417 : : TimeLineID SendRqstTLI;
3418 : :
3419 : : /*
3420 : : * Streaming the latest timeline on a standby.
3421 : : *
3422 : : * Attempt to send all WAL that has already been replayed, so that we
3423 : : * know it's valid. If we're receiving WAL through streaming
3424 : : * replication, it's also OK to send any WAL that has been received
3425 : : * but not replayed.
3426 : : *
3427 : : * The timeline we're recovering from can change, or we can be
3428 : : * promoted. In either case, the current timeline becomes historic. We
3429 : : * need to detect that so that we don't try to stream past the point
3430 : : * where we switched to another timeline. We check for promotion or
3431 : : * timeline switch after calculating FlushPtr, to avoid a race
3432 : : * condition: if the timeline becomes historic just after we checked
3433 : : * that it was still current, it's still be OK to stream it up to the
3434 : : * FlushPtr that was calculated before it became historic.
3435 : : */
3436 : 1302 : bool becameHistoric = false;
3437 : :
3438 : 1302 : SendRqstPtr = GetStandbyFlushRecPtr(&SendRqstTLI);
3439 : :
3440 [ + + ]: 1302 : if (!RecoveryInProgress())
3441 : : {
3442 : : /* We have been promoted. */
3443 : 3 : SendRqstTLI = GetWALInsertionTimeLine();
3444 : 3 : am_cascading_walsender = false;
3445 : 3 : becameHistoric = true;
3446 : : }
3447 : : else
3448 : : {
3449 : : /*
3450 : : * Still a cascading standby. But is the timeline we're sending
3451 : : * still the one recovery is recovering from?
3452 : : */
3453 [ - + ]: 1299 : if (sendTimeLine != SendRqstTLI)
3454 : 0 : becameHistoric = true;
3455 : : }
3456 : :
3457 [ + + ]: 1302 : if (becameHistoric)
3458 : : {
3459 : : /*
3460 : : * The timeline we were sending has become historic. Read the
3461 : : * timeline history file of the new timeline to see where exactly
3462 : : * we forked off from the timeline we were sending.
3463 : : */
3464 : : List *history;
3465 : :
3466 : 3 : history = readTimeLineHistory(SendRqstTLI);
3467 : 3 : sendTimeLineValidUpto = tliSwitchPoint(sendTimeLine, history, &sendTimeLineNextTLI);
3468 : :
3469 : : Assert(sendTimeLine < sendTimeLineNextTLI);
3470 : 3 : list_free_deep(history);
3471 : :
3472 : 3 : sendTimeLineIsHistoric = true;
3473 : :
3474 : 3 : SendRqstPtr = sendTimeLineValidUpto;
3475 : : }
3476 : : }
3477 : : else
3478 : : {
3479 : : /*
3480 : : * Streaming the current timeline on a primary.
3481 : : *
3482 : : * Attempt to send all data that's already been written out and
3483 : : * fsync'd to disk. We cannot go further than what's been written out
3484 : : * given the current implementation of WALRead(). And in any case
3485 : : * it's unsafe to send WAL that is not securely down to disk on the
3486 : : * primary: if the primary subsequently crashes and restarts, standbys
3487 : : * must not have applied any WAL that got lost on the primary.
3488 : : */
3489 : 139501 : SendRqstPtr = GetFlushRecPtr(NULL);
3490 : : }
3491 : :
3492 : : /*
3493 : : * Record the current system time as an approximation of the time at which
3494 : : * this WAL location was written for the purposes of lag tracking.
3495 : : *
3496 : : * In theory we could make XLogFlush() record a time in shmem whenever WAL
3497 : : * is flushed and we could get that time as well as the LSN when we call
3498 : : * GetFlushRecPtr() above (and likewise for the cascading standby
3499 : : * equivalent), but rather than putting any new code into the hot WAL path
3500 : : * it seems good enough to capture the time here. We should reach this
3501 : : * after XLogFlush() runs WalSndWakeupProcessRequests(), and although that
3502 : : * may take some time, we read the WAL flush pointer and take the time
3503 : : * very close to together here so that we'll get a later position if it is
3504 : : * still moving.
3505 : : *
3506 : : * Because LagTrackerWrite ignores samples when the LSN hasn't advanced,
3507 : : * this gives us a cheap approximation for the WAL flush time for this
3508 : : * LSN.
3509 : : *
3510 : : * Note that the LSN is not necessarily the LSN for the data contained in
3511 : : * the present message; it's the end of the WAL, which might be further
3512 : : * ahead. All the lag tracking machinery cares about is finding out when
3513 : : * that arbitrary LSN is eventually reported as written, flushed and
3514 : : * applied, so that it can measure the elapsed time.
3515 : : */
3516 : 140836 : LagTrackerWrite(SendRqstPtr, GetCurrentTimestamp());
3517 : :
3518 : : /*
3519 : : * If this is a historic timeline and we've reached the point where we
3520 : : * forked to the next timeline, stop streaming.
3521 : : *
3522 : : * Note: We might already have sent WAL > sendTimeLineValidUpto. The
3523 : : * startup process will normally replay all WAL that has been received
3524 : : * from the primary, before promoting, but if the WAL streaming is
3525 : : * terminated at a WAL page boundary, the valid portion of the timeline
3526 : : * might end in the middle of a WAL record. We might've already sent the
3527 : : * first half of that partial WAL record to the cascading standby, so that
3528 : : * sentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
3529 : : * replay the partial WAL record either, so it can still follow our
3530 : : * timeline switch.
3531 : : */
3532 [ + + + + ]: 140836 : if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= sentPtr)
3533 : : {
3534 : : /* close the current file. */
3535 [ + - ]: 12 : if (xlogreader->seg.ws_file >= 0)
3536 : 12 : wal_segment_close(xlogreader);
3537 : :
3538 : : /* Send CopyDone */
3539 : 12 : pq_putmessage_noblock(PqMsg_CopyDone, NULL, 0);
3540 : 12 : streamingDoneSending = true;
3541 : :
3542 : 12 : WalSndCaughtUp = true;
3543 : :
3544 [ + + ]: 12 : elog(DEBUG1, "walsender reached end of timeline at %X/%08X (sent up to %X/%08X)",
3545 : : LSN_FORMAT_ARGS(sendTimeLineValidUpto),
3546 : : LSN_FORMAT_ARGS(sentPtr));
3547 : 12 : return;
3548 : : }
3549 : :
3550 : : /* Do we have any work to do? */
3551 : : Assert(sentPtr <= SendRqstPtr);
3552 [ + + ]: 140824 : if (SendRqstPtr <= sentPtr)
3553 : : {
3554 : 32733 : WalSndCaughtUp = true;
3555 : 32733 : return;
3556 : : }
3557 : :
3558 : : /*
3559 : : * Figure out how much to send in one message. If there's no more than
3560 : : * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
3561 : : * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
3562 : : *
3563 : : * The rounding is not only for performance reasons. Walreceiver relies on
3564 : : * the fact that we never split a WAL record across two messages. Since a
3565 : : * long WAL record is split at page boundary into continuation records,
3566 : : * page boundary is always a safe cut-off point. We also assume that
3567 : : * SendRqstPtr never points to the middle of a WAL record.
3568 : : */
3569 : 108091 : startptr = sentPtr;
3570 : 108091 : endptr = startptr;
3571 : 108091 : endptr += MAX_SEND_SIZE;
3572 : :
3573 : : /* if we went beyond SendRqstPtr, back off */
3574 [ + + ]: 108091 : if (SendRqstPtr <= endptr)
3575 : : {
3576 : 19714 : endptr = SendRqstPtr;
3577 [ + + ]: 19714 : if (sendTimeLineIsHistoric)
3578 : 9 : WalSndCaughtUp = false;
3579 : : else
3580 : 19705 : WalSndCaughtUp = true;
3581 : : }
3582 : : else
3583 : : {
3584 : : /* round down to page boundary. */
3585 : 88377 : endptr -= (endptr % XLOG_BLCKSZ);
3586 : 88377 : WalSndCaughtUp = false;
3587 : : }
3588 : :
3589 : 108091 : nbytes = endptr - startptr;
3590 : : Assert(nbytes <= MAX_SEND_SIZE);
3591 : :
3592 : : /*
3593 : : * OK to read and send the slice.
3594 : : */
3595 : 108091 : resetStringInfo(&output_message);
3596 : 108091 : pq_sendbyte(&output_message, PqReplMsg_WALData);
3597 : :
3598 : 108091 : pq_sendint64(&output_message, startptr); /* dataStart */
3599 : 108091 : pq_sendint64(&output_message, SendRqstPtr); /* walEnd */
3600 : 108091 : pq_sendint64(&output_message, 0); /* sendtime, filled in last */
3601 : :
3602 : : /*
3603 : : * Read the log directly into the output buffer to avoid extra memcpy
3604 : : * calls.
3605 : : */
3606 : 108091 : enlargeStringInfo(&output_message, nbytes);
3607 : :
3608 : 108091 : retry:
3609 : : /* attempt to read WAL from WAL buffers first */
3610 : 108091 : rbytes = WALReadFromBuffers(&output_message.data[output_message.len],
3611 : 108091 : startptr, nbytes, xlogreader->seg.ws_tli);
3612 : 108091 : output_message.len += rbytes;
3613 : 108091 : startptr += rbytes;
3614 : 108091 : nbytes -= rbytes;
3615 : :
3616 : : /* now read the remaining WAL from WAL file */
3617 [ + + ]: 108091 : if (nbytes > 0 &&
3618 [ - + ]: 98857 : !WALRead(xlogreader,
3619 : 98858 : &output_message.data[output_message.len],
3620 : : startptr,
3621 : : nbytes,
3622 : 98858 : xlogreader->seg.ws_tli, /* Pass the current TLI because
3623 : : * only WalSndSegmentOpen controls
3624 : : * whether new TLI is needed. */
3625 : : &errinfo))
3626 : 0 : WALReadRaiseError(&errinfo);
3627 : :
3628 : : /* See logical_read_xlog_page(). */
3629 : 108090 : XLByteToSeg(startptr, segno, xlogreader->segcxt.ws_segsize);
3630 : 108090 : CheckXLogRemoved(segno, xlogreader->seg.ws_tli);
3631 : :
3632 : : /*
3633 : : * During recovery, the currently-open WAL file might be replaced with the
3634 : : * file of the same name retrieved from archive. So we always need to
3635 : : * check what we read was valid after reading into the buffer. If it's
3636 : : * invalid, we try to open and read the file again.
3637 : : */
3638 [ + + ]: 108090 : if (am_cascading_walsender)
3639 : : {
3640 : 1071 : WalSnd *walsnd = MyWalSnd;
3641 : : bool reload;
3642 : :
3643 : 1071 : SpinLockAcquire(&walsnd->mutex);
3644 : 1071 : reload = walsnd->needreload;
3645 : 1071 : walsnd->needreload = false;
3646 : 1071 : SpinLockRelease(&walsnd->mutex);
3647 : :
3648 [ - + - - ]: 1071 : if (reload && xlogreader->seg.ws_file >= 0)
3649 : : {
3650 : 0 : wal_segment_close(xlogreader);
3651 : :
3652 : 0 : goto retry;
3653 : : }
3654 : : }
3655 : :
3656 : 108090 : output_message.len += nbytes;
3657 : 108090 : output_message.data[output_message.len] = '\0';
3658 : :
3659 : : /*
3660 : : * Fill the send timestamp last, so that it is taken as late as possible.
3661 : : */
3662 : 108090 : resetStringInfo(&tmpbuf);
3663 : 108090 : pq_sendint64(&tmpbuf, GetCurrentTimestamp());
3664 : 108090 : memcpy(&output_message.data[1 + sizeof(int64) + sizeof(int64)],
3665 : 108090 : tmpbuf.data, sizeof(int64));
3666 : :
3667 : 108090 : pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
3668 : :
3669 : 108090 : sentPtr = endptr;
3670 : :
3671 : : /* Update shared memory status */
3672 : : {
3673 : 108090 : WalSnd *walsnd = MyWalSnd;
3674 : :
3675 : 108090 : SpinLockAcquire(&walsnd->mutex);
3676 : 108090 : walsnd->sentPtr = sentPtr;
3677 : 108090 : SpinLockRelease(&walsnd->mutex);
3678 : : }
3679 : :
3680 : : /* Report progress of XLOG streaming in PS display */
3681 [ + - ]: 108090 : if (update_process_title)
3682 : : {
3683 : : char activitymsg[50];
3684 : :
3685 : 108090 : snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%08X",
3686 : 108090 : LSN_FORMAT_ARGS(sentPtr));
3687 : 108090 : set_ps_display(activitymsg);
3688 : : }
3689 : : }
3690 : :
3691 : : /*
3692 : : * Stream out logically decoded data.
3693 : : */
3694 : : static void
3695 : 929571 : XLogSendLogical(void)
3696 : : {
3697 : : XLogRecord *record;
3698 : : char *errm;
3699 : :
3700 : : /*
3701 : : * We'll use the current flush point to determine whether we've caught up.
3702 : : * This variable is static in order to cache it across calls. Caching is
3703 : : * helpful because GetFlushRecPtr() needs to acquire a heavily-contended
3704 : : * spinlock.
3705 : : */
3706 : : static XLogRecPtr flushPtr = InvalidXLogRecPtr;
3707 : :
3708 : : /*
3709 : : * Don't know whether we've caught up yet. We'll set WalSndCaughtUp to
3710 : : * true in WalSndWaitForWal, if we're actually waiting. We also set to
3711 : : * true if XLogReadRecord() had to stop reading but WalSndWaitForWal
3712 : : * didn't wait - i.e. when we're shutting down.
3713 : : */
3714 : 929571 : WalSndCaughtUp = false;
3715 : :
3716 : 929571 : record = XLogReadRecord(logical_decoding_ctx->reader, &errm);
3717 : :
3718 : : /* xlog record was invalid */
3719 [ - + ]: 929334 : if (errm != NULL)
3720 [ # # ]: 0 : elog(ERROR, "could not find record while sending logically-decoded data: %s",
3721 : : errm);
3722 : :
3723 [ + + ]: 929334 : if (record != NULL)
3724 : : {
3725 : : /*
3726 : : * Note the lack of any call to LagTrackerWrite() which is handled by
3727 : : * WalSndUpdateProgress which is called by output plugin through
3728 : : * logical decoding write api.
3729 : : */
3730 : 926230 : LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
3731 : :
3732 : 926220 : sentPtr = logical_decoding_ctx->reader->EndRecPtr;
3733 : : }
3734 : :
3735 : : /*
3736 : : * If first time through in this session, initialize flushPtr. Otherwise,
3737 : : * we only need to update flushPtr if EndRecPtr is past it.
3738 : : */
3739 [ + + ]: 929324 : if (!XLogRecPtrIsValid(flushPtr) ||
3740 [ + + ]: 928877 : logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
3741 : : {
3742 : : /*
3743 : : * For cascading logical WAL senders, we use the replay LSN instead of
3744 : : * the flush LSN, since logical decoding on a standby only processes
3745 : : * WAL that has been replayed. This distinction becomes particularly
3746 : : * important during shutdown, as new WAL is no longer replayed and the
3747 : : * last replayed LSN marks the furthest point up to which decoding can
3748 : : * proceed.
3749 : : */
3750 [ + + ]: 5974 : if (am_cascading_walsender)
3751 : 826 : flushPtr = GetXLogReplayRecPtr(NULL);
3752 : : else
3753 : 5148 : flushPtr = GetFlushRecPtr(NULL);
3754 : : }
3755 : :
3756 : : /* If EndRecPtr is still past our flushPtr, it means we caught up. */
3757 [ + + ]: 929324 : if (logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
3758 : 4776 : WalSndCaughtUp = true;
3759 : :
3760 : : /*
3761 : : * If we're caught up and have been requested to stop, have WalSndLoop()
3762 : : * terminate the connection in an orderly manner, after writing out all
3763 : : * the pending data.
3764 : : */
3765 [ + + + + ]: 929324 : if (WalSndCaughtUp && got_STOPPING)
3766 : 2931 : got_SIGUSR2 = true;
3767 : :
3768 : : /* Update shared memory status */
3769 : : {
3770 : 929324 : WalSnd *walsnd = MyWalSnd;
3771 : :
3772 : 929324 : SpinLockAcquire(&walsnd->mutex);
3773 : 929324 : walsnd->sentPtr = sentPtr;
3774 : 929324 : SpinLockRelease(&walsnd->mutex);
3775 : : }
3776 : 929324 : }
3777 : :
3778 : : /*
3779 : : * Forced shutdown of walsender if wal_sender_shutdown_timeout has expired.
3780 : : */
3781 : : static void
3782 : 4 : WalSndDoneImmediate(void)
3783 : : {
3784 : 4 : WalSndState state = MyWalSnd->state;
3785 : :
3786 [ + - + + ]: 4 : if ((state == WALSNDSTATE_CATCHUP ||
3787 [ + - ]: 1 : state == WALSNDSTATE_STREAMING ||
3788 : 4 : state == WALSNDSTATE_STOPPING) &&
3789 [ + - ]: 4 : !shutdown_stream_done_queued)
3790 : : {
3791 : : QueryCompletion qc;
3792 : :
3793 : : /* Try to inform receiver that XLOG streaming is done */
3794 : 4 : SetQueryCompletion(&qc, CMDTAG_COPY, 0);
3795 : 4 : EndCommandExtended(&qc, DestRemote, false, true);
3796 : 4 : shutdown_stream_done_queued = true;
3797 : :
3798 : : /*
3799 : : * Note that the output buffer may be full during the forced shutdown
3800 : : * of walsender. If pq_flush() is called at that time, the walsender
3801 : : * process will be stuck. Therefore, call pq_flush_if_writable()
3802 : : * instead. Successful reception of the done message with the
3803 : : * walsender forced into a shutdown is not guaranteed.
3804 : : */
3805 : 4 : pq_flush_if_writable();
3806 : : }
3807 : :
3808 : : /*
3809 : : * Prevent ereport from attempting to send any more messages to the
3810 : : * standby. Otherwise, it can cause the process to get stuck if the output
3811 : : * buffers are full.
3812 : : */
3813 [ + - ]: 4 : if (whereToSendOutput == DestRemote)
3814 : 4 : whereToSendOutput = DestNone;
3815 : :
3816 [ + - ]: 4 : ereport(WARNING,
3817 : : (errmsg("terminating walsender process due to replication shutdown timeout"),
3818 : : errdetail("Walsender process might have been terminated before all WAL data was replicated to the receiver.")));
3819 : :
3820 : 4 : proc_exit(0);
3821 : : }
3822 : :
3823 : : /*
3824 : : * Shutdown if the sender is caught up.
3825 : : *
3826 : : * NB: This should only be called when the shutdown signal has been received
3827 : : * from postmaster.
3828 : : *
3829 : : * Note that if we determine that there's still more data to send, this
3830 : : * function will return control to the caller.
3831 : : */
3832 : : static void
3833 : 1746 : WalSndDone(WalSndSendDataCallback send_data)
3834 : : {
3835 : : XLogRecPtr replicatedPtr;
3836 : :
3837 : : /* ... let's just be real sure we're caught up ... */
3838 : 1746 : send_data();
3839 : :
3840 : : /*
3841 : : * To figure out whether all WAL has successfully been replicated, check
3842 : : * flush location if valid, write otherwise. Tools like pg_receivewal will
3843 : : * usually (unless in synchronous mode) return an invalid flush location.
3844 : : */
3845 : 3492 : replicatedPtr = XLogRecPtrIsValid(MyWalSnd->flush) ?
3846 [ + + ]: 1746 : MyWalSnd->flush : MyWalSnd->write;
3847 : :
3848 [ + + + + ]: 1746 : if (WalSndCaughtUp && sentPtr == replicatedPtr &&
3849 [ + - ]: 47 : !pq_is_send_pending())
3850 : : {
3851 : : QueryCompletion qc;
3852 : :
3853 : : Assert(!shutdown_stream_done_queued);
3854 : :
3855 : : /* Inform the standby that XLOG streaming is done */
3856 : 47 : SetQueryCompletion(&qc, CMDTAG_COPY, 0);
3857 : 47 : EndCommandExtended(&qc, DestRemote, false, true);
3858 : 47 : shutdown_stream_done_queued = true;
3859 : :
3860 : : /*
3861 : : * Reset last_reply_timestamp so subsequent WalSndComputeSleeptime()
3862 : : * calls ignore wal_sender_timeout during shutdown.
3863 : : */
3864 : 47 : last_reply_timestamp = 0;
3865 : :
3866 : : /*
3867 : : * Do not call pq_flush() here, since it can block indefinitely while
3868 : : * waiting for the socket to become writable, preventing
3869 : : * wal_sender_shutdown_timeout from being enforced. Instead, use the
3870 : : * walsender nonblocking flush path so the shutdown timeout continues
3871 : : * to be checked while the send buffer drains.
3872 : : */
3873 : : for (;;)
3874 : 47 : {
3875 : : long sleeptime;
3876 : :
3877 : : /*
3878 : : * During shutdown, die if the shutdown timeout expires. Call this
3879 : : * before WalSndComputeSleeptime() so the timeout is considered
3880 : : * when computing sleep time.
3881 : : */
3882 : 94 : WalSndCheckShutdownTimeout();
3883 : :
3884 [ + + ]: 94 : if (!pq_is_send_pending())
3885 : 47 : break;
3886 : :
3887 : 47 : sleeptime = WalSndComputeSleeptime(GetCurrentTimestamp());
3888 : :
3889 : : /* Sleep until something happens or we time out */
3890 : 47 : WalSndWait(WL_SOCKET_WRITEABLE, sleeptime,
3891 : : WAIT_EVENT_WAL_SENDER_WRITE_DATA);
3892 : :
3893 : : /* Clear any already-pending wakeups */
3894 : 47 : ResetLatch(MyLatch);
3895 : :
3896 [ - + ]: 47 : CHECK_FOR_INTERRUPTS();
3897 : :
3898 : : /* Try to flush pending output to the client */
3899 [ - + ]: 47 : if (pq_flush_if_writable() != 0)
3900 : 0 : WalSndShutdown();
3901 : : }
3902 : :
3903 : 47 : proc_exit(0);
3904 : : }
3905 [ + + ]: 1699 : if (!waiting_for_ping_response)
3906 : 130 : WalSndKeepalive(true, InvalidXLogRecPtr);
3907 : 1699 : }
3908 : :
3909 : : /*
3910 : : * Returns the latest point in WAL that has been safely flushed to disk.
3911 : : * This should only be called when in recovery.
3912 : : *
3913 : : * This is called either by cascading walsender to find WAL position to be sent
3914 : : * to a cascaded standby or by slot synchronization operation to validate remote
3915 : : * slot's lsn before syncing it locally.
3916 : : *
3917 : : * As a side-effect, *tli is updated to the TLI of the last
3918 : : * replayed WAL record.
3919 : : */
3920 : : XLogRecPtr
3921 : 1455 : GetStandbyFlushRecPtr(TimeLineID *tli)
3922 : : {
3923 : : XLogRecPtr replayPtr;
3924 : : TimeLineID replayTLI;
3925 : : XLogRecPtr receivePtr;
3926 : : TimeLineID receiveTLI;
3927 : : XLogRecPtr result;
3928 : :
3929 : : Assert(am_cascading_walsender || IsSyncingReplicationSlots());
3930 : :
3931 : : /*
3932 : : * We can safely send what's already been replayed. Also, if walreceiver
3933 : : * is streaming WAL from the same timeline, we can send anything that it
3934 : : * has streamed, but hasn't been replayed yet.
3935 : : */
3936 : :
3937 : 1455 : receivePtr = GetWalRcvFlushRecPtr(NULL, &receiveTLI);
3938 : 1455 : replayPtr = GetXLogReplayRecPtr(&replayTLI);
3939 : :
3940 [ + + ]: 1455 : if (tli)
3941 : 1398 : *tli = replayTLI;
3942 : :
3943 : 1455 : result = replayPtr;
3944 [ + - + + ]: 1455 : if (receiveTLI == replayTLI && receivePtr > replayPtr)
3945 : 137 : result = receivePtr;
3946 : :
3947 : 1455 : return result;
3948 : : }
3949 : :
3950 : : /*
3951 : : * Request walsenders to reload the currently-open WAL file
3952 : : */
3953 : : void
3954 : 30 : WalSndRqstFileReload(void)
3955 : : {
3956 : : int i;
3957 : :
3958 [ + + ]: 306 : for (i = 0; i < max_wal_senders; i++)
3959 : : {
3960 : 276 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
3961 : :
3962 : 276 : SpinLockAcquire(&walsnd->mutex);
3963 [ + - ]: 276 : if (walsnd->pid == 0)
3964 : : {
3965 : 276 : SpinLockRelease(&walsnd->mutex);
3966 : 276 : continue;
3967 : : }
3968 : 0 : walsnd->needreload = true;
3969 : 0 : SpinLockRelease(&walsnd->mutex);
3970 : : }
3971 : 30 : }
3972 : :
3973 : : /*
3974 : : * Handle PROCSIG_WALSND_INIT_STOPPING signal.
3975 : : */
3976 : : void
3977 : 51 : HandleWalSndInitStopping(void)
3978 : : {
3979 : : Assert(am_walsender);
3980 : :
3981 : : /*
3982 : : * If replication has not yet started, die like with SIGTERM. If
3983 : : * replication is active, only set a flag and wake up the main loop. It
3984 : : * will send any outstanding WAL, wait for it to be replicated to the
3985 : : * standby, and then exit gracefully.
3986 : : */
3987 [ - + ]: 51 : if (!replication_active)
3988 : 0 : kill(MyProcPid, SIGTERM);
3989 : : else
3990 : 51 : got_STOPPING = true;
3991 : :
3992 : : /* latch will be set by procsignal_sigusr1_handler */
3993 : 51 : }
3994 : :
3995 : : /*
3996 : : * SIGUSR2: set flag to do a last cycle and shut down afterwards. The WAL
3997 : : * sender should already have been switched to WALSNDSTATE_STOPPING at
3998 : : * this point.
3999 : : */
4000 : : static void
4001 : 51 : WalSndLastCycleHandler(SIGNAL_ARGS)
4002 : : {
4003 : 51 : got_SIGUSR2 = true;
4004 : 51 : SetLatch(MyLatch);
4005 : 51 : }
4006 : :
4007 : : /* Set up signal handlers */
4008 : : void
4009 : 1358 : WalSndSignals(void)
4010 : : {
4011 : : /* Set up signal handlers */
4012 : 1358 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
4013 : 1358 : pqsignal(SIGINT, StatementCancelHandler); /* query cancel */
4014 : 1358 : pqsignal(SIGTERM, die); /* request shutdown */
4015 : : /* SIGQUIT handler was already set up by InitPostmasterChild */
4016 : 1358 : InitializeTimeouts(); /* establishes SIGALRM handler */
4017 : 1358 : pqsignal(SIGPIPE, PG_SIG_IGN);
4018 : 1358 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
4019 : 1358 : pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
4020 : : * shutdown */
4021 : :
4022 : : /* Reset some signals that are accepted by postmaster but not here */
4023 : 1358 : pqsignal(SIGCHLD, PG_SIG_DFL);
4024 : 1358 : }
4025 : :
4026 : : /* Register shared-memory space needed by walsender */
4027 : : static void
4028 : 1283 : WalSndShmemRequest(void *arg)
4029 : : {
4030 : : Size size;
4031 : :
4032 : 1283 : size = offsetof(WalSndCtlData, walsnds);
4033 : 1283 : size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
4034 : 1283 : ShmemRequestStruct(.name = "Wal Sender Ctl",
4035 : : .size = size,
4036 : : .ptr = (void **) &WalSndCtl,
4037 : : );
4038 : 1283 : }
4039 : :
4040 : : /* Initialize walsender-related shared memory */
4041 : : static void
4042 : 1280 : WalSndShmemInit(void *arg)
4043 : : {
4044 [ + + ]: 5120 : for (int i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
4045 : 3840 : dlist_init(&(WalSndCtl->SyncRepQueue[i]));
4046 : :
4047 [ + + ]: 9512 : for (int i = 0; i < max_wal_senders; i++)
4048 : : {
4049 : 8232 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
4050 : :
4051 : 8232 : SpinLockInit(&walsnd->mutex);
4052 : : }
4053 : :
4054 : 1280 : ConditionVariableInit(&WalSndCtl->wal_flush_cv);
4055 : 1280 : ConditionVariableInit(&WalSndCtl->wal_replay_cv);
4056 : 1280 : ConditionVariableInit(&WalSndCtl->wal_confirm_rcv_cv);
4057 : 1280 : }
4058 : :
4059 : : /*
4060 : : * Wake up physical, logical or both kinds of walsenders
4061 : : *
4062 : : * The distinction between physical and logical walsenders is done, because:
4063 : : * - physical walsenders can't send data until it's been flushed
4064 : : * - logical walsenders on standby can't decode and send data until it's been
4065 : : * applied
4066 : : *
4067 : : * For cascading replication we need to wake up physical walsenders separately
4068 : : * from logical walsenders (see the comment before calling WalSndWakeup() in
4069 : : * ApplyWalRecord() for more details).
4070 : : *
4071 : : * This will be called inside critical sections, so throwing an error is not
4072 : : * advisable.
4073 : : */
4074 : : void
4075 : 2848494 : WalSndWakeup(bool physical, bool logical)
4076 : : {
4077 : : /*
4078 : : * Wake up all the walsenders waiting on WAL being flushed or replayed
4079 : : * respectively. Note that waiting walsender would have prepared to sleep
4080 : : * on the CV (i.e., added itself to the CV's waitlist) in WalSndWait()
4081 : : * before actually waiting.
4082 : : */
4083 [ + + ]: 2848494 : if (physical)
4084 : 158753 : ConditionVariableBroadcast(&WalSndCtl->wal_flush_cv);
4085 : :
4086 [ + + ]: 2848494 : if (logical)
4087 : 2802825 : ConditionVariableBroadcast(&WalSndCtl->wal_replay_cv);
4088 : 2848494 : }
4089 : :
4090 : : /*
4091 : : * Wait for readiness on the FeBe socket, or a timeout. The mask should be
4092 : : * composed of optional WL_SOCKET_WRITEABLE and WL_SOCKET_READABLE flags. Exit
4093 : : * on postmaster death.
4094 : : */
4095 : : static void
4096 : 103774 : WalSndWait(uint32 socket_events, long timeout, uint32 wait_event)
4097 : : {
4098 : : WaitEvent event;
4099 : :
4100 : 103774 : ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetSocketPos, socket_events, NULL);
4101 : :
4102 : : /*
4103 : : * We use a condition variable to efficiently wake up walsenders in
4104 : : * WalSndWakeup().
4105 : : *
4106 : : * Every walsender prepares to sleep on a shared memory CV. Note that it
4107 : : * just prepares to sleep on the CV (i.e., adds itself to the CV's
4108 : : * waitlist), but does not actually wait on the CV (IOW, it never calls
4109 : : * ConditionVariableSleep()). It still uses WaitEventSetWait() for
4110 : : * waiting, because we also need to wait for socket events. The processes
4111 : : * (startup process, walreceiver etc.) wanting to wake up walsenders use
4112 : : * ConditionVariableBroadcast(), which in turn calls SetLatch(), helping
4113 : : * walsenders come out of WaitEventSetWait().
4114 : : *
4115 : : * This approach is simple and efficient because, one doesn't have to loop
4116 : : * through all the walsenders slots, with a spinlock acquisition and
4117 : : * release for every iteration, just to wake up only the waiting
4118 : : * walsenders. It makes WalSndWakeup() callers' life easy.
4119 : : *
4120 : : * XXX: A desirable future improvement would be to add support for CVs
4121 : : * into WaitEventSetWait().
4122 : : *
4123 : : * And, we use separate shared memory CVs for physical and logical
4124 : : * walsenders for selective wake ups, see WalSndWakeup() for more details.
4125 : : *
4126 : : * If the wait event is WAIT_FOR_STANDBY_CONFIRMATION, wait on another CV
4127 : : * until awakened by physical walsenders after the walreceiver confirms
4128 : : * the receipt of the LSN.
4129 : : */
4130 [ + + ]: 103774 : if (wait_event == WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION)
4131 : 14 : ConditionVariablePrepareToSleep(&WalSndCtl->wal_confirm_rcv_cv);
4132 [ + + ]: 103760 : else if (MyWalSnd->kind == REPLICATION_KIND_PHYSICAL)
4133 : 94173 : ConditionVariablePrepareToSleep(&WalSndCtl->wal_flush_cv);
4134 [ + - ]: 9587 : else if (MyWalSnd->kind == REPLICATION_KIND_LOGICAL)
4135 : 9587 : ConditionVariablePrepareToSleep(&WalSndCtl->wal_replay_cv);
4136 : :
4137 [ + + ]: 103774 : if (WaitEventSetWait(FeBeWaitSet, timeout, &event, 1, wait_event) == 1 &&
4138 [ - + ]: 103771 : (event.events & WL_POSTMASTER_DEATH))
4139 : : {
4140 : 0 : ConditionVariableCancelSleep();
4141 : 0 : proc_exit(1);
4142 : : }
4143 : :
4144 : 103774 : ConditionVariableCancelSleep();
4145 : 103774 : }
4146 : :
4147 : : /*
4148 : : * Signal all walsenders to move to stopping state.
4149 : : *
4150 : : * This will trigger walsenders to move to a state where no further WAL can be
4151 : : * generated. See this file's header for details.
4152 : : */
4153 : : void
4154 : 787 : WalSndInitStopping(void)
4155 : : {
4156 : : int i;
4157 : :
4158 [ + + ]: 5863 : for (i = 0; i < max_wal_senders; i++)
4159 : : {
4160 : 5076 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
4161 : : pid_t pid;
4162 : :
4163 : 5076 : SpinLockAcquire(&walsnd->mutex);
4164 : 5076 : pid = walsnd->pid;
4165 : 5076 : SpinLockRelease(&walsnd->mutex);
4166 : :
4167 [ + + ]: 5076 : if (pid == 0)
4168 : 5025 : continue;
4169 : :
4170 : 51 : SendProcSignal(pid, PROCSIG_WALSND_INIT_STOPPING, INVALID_PROC_NUMBER);
4171 : : }
4172 : 787 : }
4173 : :
4174 : : /*
4175 : : * Wait that all the WAL senders have quit or reached the stopping state. This
4176 : : * is used by the checkpointer to control when the shutdown checkpoint can
4177 : : * safely be performed.
4178 : : */
4179 : : void
4180 : 787 : WalSndWaitStopping(void)
4181 : : {
4182 : : for (;;)
4183 : 41 : {
4184 : : int i;
4185 : 828 : bool all_stopped = true;
4186 : :
4187 [ + + ]: 5907 : for (i = 0; i < max_wal_senders; i++)
4188 : : {
4189 : 5120 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
4190 : :
4191 : 5120 : SpinLockAcquire(&walsnd->mutex);
4192 : :
4193 [ + + ]: 5120 : if (walsnd->pid == 0)
4194 : : {
4195 : 5044 : SpinLockRelease(&walsnd->mutex);
4196 : 5044 : continue;
4197 : : }
4198 : :
4199 [ + + ]: 76 : if (walsnd->state != WALSNDSTATE_STOPPING)
4200 : : {
4201 : 41 : all_stopped = false;
4202 : 41 : SpinLockRelease(&walsnd->mutex);
4203 : 41 : break;
4204 : : }
4205 : 35 : SpinLockRelease(&walsnd->mutex);
4206 : : }
4207 : :
4208 : : /* safe to leave if confirmation is done for all WAL senders */
4209 [ + + ]: 828 : if (all_stopped)
4210 : 787 : return;
4211 : :
4212 : 41 : pg_usleep(10000L); /* wait for 10 msec */
4213 : : }
4214 : : }
4215 : :
4216 : : /* Set state for current walsender (only called in walsender) */
4217 : : void
4218 : 3081 : WalSndSetState(WalSndState state)
4219 : : {
4220 : 3081 : WalSnd *walsnd = MyWalSnd;
4221 : :
4222 : : Assert(am_walsender);
4223 : :
4224 [ + + ]: 3081 : if (walsnd->state == state)
4225 : 899 : return;
4226 : :
4227 : 2182 : SpinLockAcquire(&walsnd->mutex);
4228 : 2182 : walsnd->state = state;
4229 : 2182 : SpinLockRelease(&walsnd->mutex);
4230 : : }
4231 : :
4232 : : /*
4233 : : * Return a string constant representing the state. This is used
4234 : : * in system views, and should *not* be translated.
4235 : : */
4236 : : static const char *
4237 : 619 : WalSndGetStateString(WalSndState state)
4238 : : {
4239 [ + - + + : 619 : switch (state)
- - ]
4240 : : {
4241 : 1 : case WALSNDSTATE_STARTUP:
4242 : 1 : return "startup";
4243 : 0 : case WALSNDSTATE_BACKUP:
4244 : 0 : return "backup";
4245 : 3 : case WALSNDSTATE_CATCHUP:
4246 : 3 : return "catchup";
4247 : 615 : case WALSNDSTATE_STREAMING:
4248 : 615 : return "streaming";
4249 : 0 : case WALSNDSTATE_STOPPING:
4250 : 0 : return "stopping";
4251 : : }
4252 : 0 : return "UNKNOWN";
4253 : : }
4254 : :
4255 : : static Interval *
4256 : 1485 : offset_to_interval(TimeOffset offset)
4257 : : {
4258 : 1485 : Interval *result = palloc_object(Interval);
4259 : :
4260 : 1485 : result->month = 0;
4261 : 1485 : result->day = 0;
4262 : 1485 : result->time = offset;
4263 : :
4264 : 1485 : return result;
4265 : : }
4266 : :
4267 : : /*
4268 : : * Returns activity of walsenders, including pids and xlog locations sent to
4269 : : * standby servers.
4270 : : */
4271 : : Datum
4272 : 480 : pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
4273 : : {
4274 : : #define PG_STAT_GET_WAL_SENDERS_COLS 12
4275 : 480 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
4276 : : SyncRepStandbyData *sync_standbys;
4277 : : int num_standbys;
4278 : : int i;
4279 : :
4280 : 480 : InitMaterializedSRF(fcinfo, 0);
4281 : :
4282 : : /*
4283 : : * Get the currently active synchronous standbys. This could be out of
4284 : : * date before we're done, but we'll use the data anyway.
4285 : : */
4286 : 480 : num_standbys = SyncRepGetCandidateStandbys(&sync_standbys);
4287 : :
4288 [ + + ]: 5268 : for (i = 0; i < max_wal_senders; i++)
4289 : : {
4290 : 4788 : WalSnd *walsnd = &WalSndCtl->walsnds[i];
4291 : : XLogRecPtr sent_ptr;
4292 : : XLogRecPtr write;
4293 : : XLogRecPtr flush;
4294 : : XLogRecPtr apply;
4295 : : TimeOffset writeLag;
4296 : : TimeOffset flushLag;
4297 : : TimeOffset applyLag;
4298 : : int priority;
4299 : : int pid;
4300 : : WalSndState state;
4301 : : TimestampTz replyTime;
4302 : : bool is_sync_standby;
4303 : : Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
4304 : 4788 : bool nulls[PG_STAT_GET_WAL_SENDERS_COLS] = {0};
4305 : : int j;
4306 : :
4307 : : /* Collect data from shared memory */
4308 : 4788 : SpinLockAcquire(&walsnd->mutex);
4309 [ + + ]: 4788 : if (walsnd->pid == 0)
4310 : : {
4311 : 4169 : SpinLockRelease(&walsnd->mutex);
4312 : 4169 : continue;
4313 : : }
4314 : 619 : pid = walsnd->pid;
4315 : 619 : sent_ptr = walsnd->sentPtr;
4316 : 619 : state = walsnd->state;
4317 : 619 : write = walsnd->write;
4318 : 619 : flush = walsnd->flush;
4319 : 619 : apply = walsnd->apply;
4320 : 619 : writeLag = walsnd->writeLag;
4321 : 619 : flushLag = walsnd->flushLag;
4322 : 619 : applyLag = walsnd->applyLag;
4323 : 619 : priority = walsnd->sync_standby_priority;
4324 : 619 : replyTime = walsnd->replyTime;
4325 : 619 : SpinLockRelease(&walsnd->mutex);
4326 : :
4327 : : /*
4328 : : * Detect whether walsender is/was considered synchronous. We can
4329 : : * provide some protection against stale data by checking the PID
4330 : : * along with walsnd_index.
4331 : : */
4332 : 619 : is_sync_standby = false;
4333 [ + + ]: 666 : for (j = 0; j < num_standbys; j++)
4334 : : {
4335 [ + + ]: 76 : if (sync_standbys[j].walsnd_index == i &&
4336 [ + - ]: 29 : sync_standbys[j].pid == pid)
4337 : : {
4338 : 29 : is_sync_standby = true;
4339 : 29 : break;
4340 : : }
4341 : : }
4342 : :
4343 : 619 : values[0] = Int32GetDatum(pid);
4344 : :
4345 [ - + ]: 619 : if (!has_privs_of_role(GetUserId(), ROLE_PG_READ_ALL_STATS))
4346 : : {
4347 : : /*
4348 : : * Only superusers and roles with privileges of pg_read_all_stats
4349 : : * can see details. Other users only get the pid value to know
4350 : : * it's a walsender, but no details.
4351 : : */
4352 [ # # # # : 0 : MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
# # # # #
# ]
4353 : : }
4354 : : else
4355 : : {
4356 : 619 : values[1] = CStringGetTextDatum(WalSndGetStateString(state));
4357 : :
4358 [ + + ]: 619 : if (!XLogRecPtrIsValid(sent_ptr))
4359 : 1 : nulls[2] = true;
4360 : 619 : values[2] = LSNGetDatum(sent_ptr);
4361 : :
4362 [ + + ]: 619 : if (!XLogRecPtrIsValid(write))
4363 : 1 : nulls[3] = true;
4364 : 619 : values[3] = LSNGetDatum(write);
4365 : :
4366 [ + + ]: 619 : if (!XLogRecPtrIsValid(flush))
4367 : 1 : nulls[4] = true;
4368 : 619 : values[4] = LSNGetDatum(flush);
4369 : :
4370 [ + + ]: 619 : if (!XLogRecPtrIsValid(apply))
4371 : 1 : nulls[5] = true;
4372 : 619 : values[5] = LSNGetDatum(apply);
4373 : :
4374 : : /*
4375 : : * Treat a standby such as a pg_basebackup background process
4376 : : * which always returns an invalid flush location, as an
4377 : : * asynchronous standby.
4378 : : */
4379 [ + + ]: 619 : priority = XLogRecPtrIsValid(flush) ? priority : 0;
4380 : :
4381 [ + + ]: 619 : if (writeLag < 0)
4382 : 124 : nulls[6] = true;
4383 : : else
4384 : 495 : values[6] = IntervalPGetDatum(offset_to_interval(writeLag));
4385 : :
4386 [ + + ]: 619 : if (flushLag < 0)
4387 : 124 : nulls[7] = true;
4388 : : else
4389 : 495 : values[7] = IntervalPGetDatum(offset_to_interval(flushLag));
4390 : :
4391 [ + + ]: 619 : if (applyLag < 0)
4392 : 124 : nulls[8] = true;
4393 : : else
4394 : 495 : values[8] = IntervalPGetDatum(offset_to_interval(applyLag));
4395 : :
4396 : 619 : values[9] = Int32GetDatum(priority);
4397 : :
4398 : : /*
4399 : : * More easily understood version of standby state. This is purely
4400 : : * informational.
4401 : : *
4402 : : * In quorum-based sync replication, the role of each standby
4403 : : * listed in synchronous_standby_names can be changing very
4404 : : * frequently. Any standbys considered as "sync" at one moment can
4405 : : * be switched to "potential" ones at the next moment. So, it's
4406 : : * basically useless to report "sync" or "potential" as their sync
4407 : : * states. We report just "quorum" for them.
4408 : : */
4409 [ + + ]: 619 : if (priority == 0)
4410 : 579 : values[10] = CStringGetTextDatum("async");
4411 [ + + ]: 40 : else if (is_sync_standby)
4412 : 29 : values[10] = SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY ?
4413 [ + + ]: 29 : CStringGetTextDatum("sync") : CStringGetTextDatum("quorum");
4414 : : else
4415 : 11 : values[10] = CStringGetTextDatum("potential");
4416 : :
4417 [ + + ]: 619 : if (replyTime == 0)
4418 : 1 : nulls[11] = true;
4419 : : else
4420 : 618 : values[11] = TimestampTzGetDatum(replyTime);
4421 : : }
4422 : :
4423 : 619 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
4424 : : values, nulls);
4425 : : }
4426 : :
4427 : 480 : return (Datum) 0;
4428 : : }
4429 : :
4430 : : /*
4431 : : * Send a keepalive message to standby.
4432 : : *
4433 : : * If requestReply is set, the message requests the other party to send
4434 : : * a message back to us, for heartbeat purposes. We also set a flag to
4435 : : * let nearby code know that we're waiting for that response, to avoid
4436 : : * repeated requests.
4437 : : *
4438 : : * writePtr is the location up to which the WAL is sent. It is essentially
4439 : : * the same as sentPtr but in some cases, we need to send keep alive before
4440 : : * sentPtr is updated like when skipping empty transactions.
4441 : : */
4442 : : static void
4443 : 2159 : WalSndKeepalive(bool requestReply, XLogRecPtr writePtr)
4444 : : {
4445 [ + + ]: 2159 : elog(DEBUG2, "sending replication keepalive");
4446 : :
4447 : : /* construct the message... */
4448 : 2159 : resetStringInfo(&output_message);
4449 : 2159 : pq_sendbyte(&output_message, PqReplMsg_Keepalive);
4450 [ - + ]: 2159 : pq_sendint64(&output_message, XLogRecPtrIsValid(writePtr) ? writePtr : sentPtr);
4451 : 2159 : pq_sendint64(&output_message, GetCurrentTimestamp());
4452 : 2159 : pq_sendbyte(&output_message, requestReply ? 1 : 0);
4453 : :
4454 : : /* ... and send it wrapped in CopyData */
4455 : 2159 : pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
4456 : :
4457 : : /* Set local flag */
4458 [ + + ]: 2159 : if (requestReply)
4459 : 130 : waiting_for_ping_response = true;
4460 : 2159 : }
4461 : :
4462 : : /*
4463 : : * Send keepalive message if too much time has elapsed.
4464 : : */
4465 : : static void
4466 : 1172794 : WalSndKeepaliveIfNecessary(void)
4467 : : {
4468 : : TimestampTz ping_time;
4469 : :
4470 : : /*
4471 : : * Don't send keepalive messages if timeouts are globally disabled or
4472 : : * we're doing something not partaking in timeouts.
4473 : : */
4474 [ + - + + ]: 1172794 : if (wal_sender_timeout <= 0 || last_reply_timestamp <= 0)
4475 : 29 : return;
4476 : :
4477 [ + + ]: 1172765 : if (waiting_for_ping_response)
4478 : 1825 : return;
4479 : :
4480 : : /*
4481 : : * If half of wal_sender_timeout has lapsed without receiving any reply
4482 : : * from the standby, send a keep-alive message to the standby requesting
4483 : : * an immediate reply.
4484 : : */
4485 : 1170940 : ping_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
4486 : : wal_sender_timeout / 2);
4487 [ - + ]: 1170940 : if (last_processing >= ping_time)
4488 : : {
4489 : 0 : WalSndKeepalive(true, InvalidXLogRecPtr);
4490 : :
4491 : : /* Try to flush pending output to the client */
4492 [ # # ]: 0 : if (pq_flush_if_writable() != 0)
4493 : 0 : WalSndShutdown();
4494 : : }
4495 : : }
4496 : :
4497 : : /*
4498 : : * Record the end of the WAL and the time it was flushed locally, so that
4499 : : * LagTrackerRead can compute the elapsed time (lag) when this WAL location is
4500 : : * eventually reported to have been written, flushed and applied by the
4501 : : * standby in a reply message.
4502 : : */
4503 : : static void
4504 : 141208 : LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time)
4505 : : {
4506 : : int new_write_head;
4507 : : int i;
4508 : :
4509 [ - + ]: 141208 : if (!am_walsender)
4510 : 0 : return;
4511 : :
4512 : : /*
4513 : : * If the lsn hasn't advanced since last time, then do nothing. This way
4514 : : * we only record a new sample when new WAL has been written.
4515 : : */
4516 [ + + ]: 141208 : if (lag_tracker->last_lsn == lsn)
4517 : 117787 : return;
4518 : 23421 : lag_tracker->last_lsn = lsn;
4519 : :
4520 : : /*
4521 : : * If advancing the write head of the circular buffer would crash into any
4522 : : * of the read heads, then the buffer is full. In other words, the
4523 : : * slowest reader (presumably apply) is the one that controls the release
4524 : : * of space.
4525 : : */
4526 : 23421 : new_write_head = (lag_tracker->write_head + 1) % LAG_TRACKER_BUFFER_SIZE;
4527 [ + + ]: 93684 : for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; ++i)
4528 : : {
4529 : : /*
4530 : : * If the buffer is full, move the slowest reader to a separate
4531 : : * overflow entry and free its space in the buffer so the write head
4532 : : * can advance.
4533 : : */
4534 [ - + ]: 70263 : if (new_write_head == lag_tracker->read_heads[i])
4535 : : {
4536 : 0 : lag_tracker->overflowed[i] =
4537 : 0 : lag_tracker->buffer[lag_tracker->read_heads[i]];
4538 : 0 : lag_tracker->read_heads[i] = -1;
4539 : : }
4540 : : }
4541 : :
4542 : : /* Store a sample at the current write head position. */
4543 : 23421 : lag_tracker->buffer[lag_tracker->write_head].lsn = lsn;
4544 : 23421 : lag_tracker->buffer[lag_tracker->write_head].time = local_flush_time;
4545 : 23421 : lag_tracker->write_head = new_write_head;
4546 : : }
4547 : :
4548 : : /*
4549 : : * Find out how much time has elapsed between the moment WAL location 'lsn'
4550 : : * (or the highest known earlier LSN) was flushed locally and the time 'now'.
4551 : : * We have a separate read head for each of the reported LSN locations we
4552 : : * receive in replies from standby; 'head' controls which read head is
4553 : : * used. Whenever a read head crosses an LSN which was written into the
4554 : : * lag buffer with LagTrackerWrite, we can use the associated timestamp to
4555 : : * find out the time this LSN (or an earlier one) was flushed locally, and
4556 : : * therefore compute the lag.
4557 : : *
4558 : : * Return -1 if no new sample data is available, and otherwise the elapsed
4559 : : * time in microseconds.
4560 : : */
4561 : : static TimeOffset
4562 : 367626 : LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now)
4563 : : {
4564 : 367626 : TimestampTz time = 0;
4565 : :
4566 : : /*
4567 : : * If 'lsn' has not passed the WAL position stored in the overflow entry,
4568 : : * return the elapsed time (in microseconds) since the saved local flush
4569 : : * time. If the flush time is in the future (due to clock drift), return
4570 : : * -1 to treat as no valid sample.
4571 : : *
4572 : : * Otherwise, switch back to using the buffer to control the read head and
4573 : : * compute the elapsed time. The read head is then reset to point to the
4574 : : * oldest entry in the buffer.
4575 : : */
4576 [ - + ]: 367626 : if (lag_tracker->read_heads[head] == -1)
4577 : : {
4578 [ # # ]: 0 : if (lag_tracker->overflowed[head].lsn > lsn)
4579 : 0 : return (now >= lag_tracker->overflowed[head].time) ?
4580 [ # # ]: 0 : now - lag_tracker->overflowed[head].time : -1;
4581 : :
4582 : 0 : time = lag_tracker->overflowed[head].time;
4583 : 0 : lag_tracker->last_read[head] = lag_tracker->overflowed[head];
4584 : 0 : lag_tracker->read_heads[head] =
4585 : 0 : (lag_tracker->write_head + 1) % LAG_TRACKER_BUFFER_SIZE;
4586 : : }
4587 : :
4588 : : /* Read all unread samples up to this LSN or end of buffer. */
4589 [ + + ]: 436646 : while (lag_tracker->read_heads[head] != lag_tracker->write_head &&
4590 [ + + ]: 284674 : lag_tracker->buffer[lag_tracker->read_heads[head]].lsn <= lsn)
4591 : : {
4592 : 69020 : time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
4593 : 69020 : lag_tracker->last_read[head] =
4594 : 69020 : lag_tracker->buffer[lag_tracker->read_heads[head]];
4595 : 69020 : lag_tracker->read_heads[head] =
4596 : 69020 : (lag_tracker->read_heads[head] + 1) % LAG_TRACKER_BUFFER_SIZE;
4597 : : }
4598 : :
4599 : : /*
4600 : : * If the lag tracker is empty, that means the standby has processed
4601 : : * everything we've ever sent so we should now clear 'last_read'. If we
4602 : : * didn't do that, we'd risk using a stale and irrelevant sample for
4603 : : * interpolation at the beginning of the next burst of WAL after a period
4604 : : * of idleness.
4605 : : */
4606 [ + + ]: 367626 : if (lag_tracker->read_heads[head] == lag_tracker->write_head)
4607 : 151972 : lag_tracker->last_read[head].time = 0;
4608 : :
4609 [ - + ]: 367626 : if (time > now)
4610 : : {
4611 : : /* If the clock somehow went backwards, treat as not found. */
4612 : 0 : return -1;
4613 : : }
4614 [ + + ]: 367626 : else if (time == 0)
4615 : : {
4616 : : /*
4617 : : * We didn't cross a time. If there is a future sample that we
4618 : : * haven't reached yet, and we've already reached at least one sample,
4619 : : * let's interpolate the local flushed time. This is mainly useful
4620 : : * for reporting a completely stuck apply position as having
4621 : : * increasing lag, since otherwise we'd have to wait for it to
4622 : : * eventually start moving again and cross one of our samples before
4623 : : * we can show the lag increasing.
4624 : : */
4625 [ + + ]: 311697 : if (lag_tracker->read_heads[head] == lag_tracker->write_head)
4626 : : {
4627 : : /* There are no future samples, so we can't interpolate. */
4628 : 105336 : return -1;
4629 : : }
4630 [ + + ]: 206361 : else if (lag_tracker->last_read[head].time != 0)
4631 : : {
4632 : : /* We can interpolate between last_read and the next sample. */
4633 : : double fraction;
4634 : 80336 : WalTimeSample prev = lag_tracker->last_read[head];
4635 : 80336 : WalTimeSample next = lag_tracker->buffer[lag_tracker->read_heads[head]];
4636 : :
4637 [ - + ]: 80336 : if (lsn < prev.lsn)
4638 : : {
4639 : : /*
4640 : : * Reported LSNs shouldn't normally go backwards, but it's
4641 : : * possible when there is a timeline change. Treat as not
4642 : : * found.
4643 : : */
4644 : 0 : return -1;
4645 : : }
4646 : :
4647 : : Assert(prev.lsn < next.lsn);
4648 : :
4649 [ - + ]: 80336 : if (prev.time > next.time)
4650 : : {
4651 : : /* If the clock somehow went backwards, treat as not found. */
4652 : 0 : return -1;
4653 : : }
4654 : :
4655 : : /* See how far we are between the previous and next samples. */
4656 : 80336 : fraction =
4657 : 80336 : (double) (lsn - prev.lsn) / (double) (next.lsn - prev.lsn);
4658 : :
4659 : : /* Scale the local flush time proportionally. */
4660 : 80336 : time = (TimestampTz)
4661 : 80336 : ((double) prev.time + (next.time - prev.time) * fraction);
4662 : : }
4663 : : else
4664 : : {
4665 : : /*
4666 : : * We have only a future sample, implying that we were entirely
4667 : : * caught up but and now there is a new burst of WAL and the
4668 : : * standby hasn't processed the first sample yet. Until the
4669 : : * standby reaches the future sample the best we can do is report
4670 : : * the hypothetical lag if that sample were to be replayed now.
4671 : : */
4672 : 126025 : time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
4673 : : }
4674 : : }
4675 : :
4676 : : /* Return the elapsed time since local flush time in microseconds. */
4677 : : Assert(time != 0);
4678 : 262290 : return now - time;
4679 : : }
|