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