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