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