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