]> granicus.if.org Git - postgresql/blob - src/backend/replication/walsender.c
Refer to max_wal_senders in a more consistent fashion.
[postgresql] / src / backend / replication / walsender.c
1 /*-------------------------------------------------------------------------
2  *
3  * walsender.c
4  *
5  * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
6  * charge of XLOG streaming sender in the primary server. At first, it is
7  * started by the postmaster when the walreceiver in the standby server
8  * connects to the primary server and requests XLOG streaming replication,
9  * i.e., unlike any auxiliary process, it is not an always-running process.
10  * It attempts to keep reading XLOG records from the disk and sending them
11  * to the standby server, as long as the connection is alive (i.e., like
12  * any backend, there is an one to one relationship between a connection
13  * and a walsender process).
14  *
15  * Normal termination is by SIGTERM, which instructs the walsender to
16  * close the connection and exit(0) at next convenient moment. Emergency
17  * termination is by SIGQUIT; like any backend, the walsender will simply
18  * abort and exit on SIGQUIT. A close of the connection and a FATAL error
19  * are treated as not a crash but approximately normal termination;
20  * the walsender will exit quickly without sending any more XLOG records.
21  *
22  * If the server is shut down, postmaster sends us SIGUSR2 after all
23  * regular backends have exited and the shutdown checkpoint has been written.
24  * This instruct walsender to send any outstanding WAL, including the
25  * shutdown checkpoint record, and then exit.
26  *
27  * Note that there can be more than one walsender process concurrently.
28  *
29  * Portions Copyright (c) 2010-2010, PostgreSQL Global Development Group
30  *
31  *
32  * IDENTIFICATION
33  *        $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.14 2010/04/01 00:43:29 rhaas Exp $
34  *
35  *-------------------------------------------------------------------------
36  */
37 #include "postgres.h"
38
39 #include <unistd.h>
40
41 #include "access/xlog_internal.h"
42 #include "catalog/pg_type.h"
43 #include "libpq/libpq.h"
44 #include "libpq/pqformat.h"
45 #include "libpq/pqsignal.h"
46 #include "miscadmin.h"
47 #include "replication/walsender.h"
48 #include "storage/fd.h"
49 #include "storage/ipc.h"
50 #include "storage/lock.h"
51 #include "storage/pmsignal.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/guc.h"
54 #include "utils/memutils.h"
55 #include "utils/ps_status.h"
56
57 /* Array of WalSnds in shared memory */
58 WalSndCtlData *WalSndCtl = NULL;
59
60 /* My slot in the shared memory array */
61 static WalSnd *MyWalSnd = NULL;
62
63 /* Global state */
64 bool            am_walsender = false;           /* Am I a walsender process ? */
65
66 /* User-settable parameters for walsender */
67 int                     max_wal_senders = 0;    /* the maximum number of concurrent walsenders */
68 int                     WalSndDelay = 200;      /* max sleep time between some actions */
69
70 #define NAPTIME_PER_CYCLE 100000L       /* max sleep time between cycles (100ms) */
71
72 /*
73  * These variables are used similarly to openLogFile/Id/Seg/Off,
74  * but for walsender to read the XLOG.
75  */
76 static int      sendFile = -1;
77 static uint32 sendId = 0;
78 static uint32 sendSeg = 0;
79 static uint32 sendOff = 0;
80
81 /*
82  * How far have we sent WAL already? This is also advertised in
83  * MyWalSnd->sentPtr.
84  */
85 static XLogRecPtr sentPtr = {0, 0};
86
87 /* Flags set by signal handlers for later service in main loop */
88 static volatile sig_atomic_t got_SIGHUP = false;
89 static volatile sig_atomic_t shutdown_requested = false;
90 static volatile sig_atomic_t ready_to_stop = false;
91
92 /* Signal handlers */
93 static void WalSndSigHupHandler(SIGNAL_ARGS);
94 static void WalSndShutdownHandler(SIGNAL_ARGS);
95 static void WalSndQuickDieHandler(SIGNAL_ARGS);
96
97 /* Prototypes for private functions */
98 static int      WalSndLoop(void);
99 static void InitWalSnd(void);
100 static void WalSndHandshake(void);
101 static void WalSndKill(int code, Datum arg);
102 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
103 static bool XLogSend(StringInfo outMsg);
104 static void CheckClosedConnection(void);
105
106 /*
107  * How much WAL to send in one message? Must be >= XLOG_BLCKSZ.
108  */
109 #define MAX_SEND_SIZE (XLOG_SEG_SIZE / 2)
110
111 /* Main entry point for walsender process */
112 int
113 WalSenderMain(void)
114 {
115         MemoryContext walsnd_context;
116
117         if (!superuser())
118                 ereport(FATAL,
119                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
120                                  errmsg("must be superuser to start walsender")));
121
122         if (RecoveryInProgress())
123                 ereport(FATAL,
124                                 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
125                                  errmsg("recovery is still in progress, can't accept WAL streaming connections")));
126
127         /* Create a per-walsender data structure in shared memory */
128         InitWalSnd();
129
130         /*
131          * Create a memory context that we will do all our work in.  We do this so
132          * that we can reset the context during error recovery and thereby avoid
133          * possible memory leaks.  Formerly this code just ran in
134          * TopMemoryContext, but resetting that would be a really bad idea.
135          *
136          * XXX: we don't actually attempt error recovery in walsender, we just
137          * close the connection and exit.
138          */
139         walsnd_context = AllocSetContextCreate(TopMemoryContext,
140                                                                                    "Wal Sender",
141                                                                                    ALLOCSET_DEFAULT_MINSIZE,
142                                                                                    ALLOCSET_DEFAULT_INITSIZE,
143                                                                                    ALLOCSET_DEFAULT_MAXSIZE);
144         MemoryContextSwitchTo(walsnd_context);
145
146         /* Unblock signals (they were blocked when the postmaster forked us) */
147         PG_SETMASK(&UnBlockSig);
148
149         /* Tell the standby that walsender is ready for receiving commands */
150         ReadyForQuery(DestRemote);
151
152         /* Handle handshake messages before streaming */
153         WalSndHandshake();
154
155         /* Main loop of walsender */
156         return WalSndLoop();
157 }
158
159 static void
160 WalSndHandshake(void)
161 {
162         StringInfoData input_message;
163         bool            replication_started = false;
164
165         initStringInfo(&input_message);
166
167         while (!replication_started)
168         {
169                 int                     firstchar;
170
171                 /* Wait for a command to arrive */
172                 firstchar = pq_getbyte();
173
174                 /*
175                  * Check for any other interesting events that happened while we
176                  * slept.
177                  */
178                 if (got_SIGHUP)
179                 {
180                         got_SIGHUP = false;
181                         ProcessConfigFile(PGC_SIGHUP);
182                 }
183
184                 if (firstchar != EOF)
185                 {
186                         /*
187                          * Read the message contents. This is expected to be done without
188                          * blocking because we've been able to get message type code.
189                          */
190                         if (pq_getmessage(&input_message, 0))
191                                 firstchar = EOF;        /* suitable message already logged */
192                 }
193
194                 /* Handle the very limited subset of commands expected in this phase */
195                 switch (firstchar)
196                 {
197                         case 'Q':                       /* Query message */
198                                 {
199                                         const char *query_string;
200                                         XLogRecPtr      recptr;
201
202                                         query_string = pq_getmsgstring(&input_message);
203                                         pq_getmsgend(&input_message);
204
205                                         if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
206                                         {
207                                                 StringInfoData buf;
208                                                 char            sysid[32];
209                                                 char            tli[11];
210
211                                                 /*
212                                                  * Reply with a result set with one row, two columns.
213                                                  * First col is system ID, and second if timeline ID
214                                                  */
215
216                                                 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
217                                                                  GetSystemIdentifier());
218                                                 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
219
220                                                 /* Send a RowDescription message */
221                                                 pq_beginmessage(&buf, 'T');
222                                                 pq_sendint(&buf, 2, 2); /* 2 fields */
223
224                                                 /* first field */
225                                                 pq_sendstring(&buf, "systemid");                /* col name */
226                                                 pq_sendint(&buf, 0, 4); /* table oid */
227                                                 pq_sendint(&buf, 0, 2); /* attnum */
228                                                 pq_sendint(&buf, TEXTOID, 4);   /* type oid */
229                                                 pq_sendint(&buf, -1, 2);                /* typlen */
230                                                 pq_sendint(&buf, 0, 4); /* typmod */
231                                                 pq_sendint(&buf, 0, 2); /* format code */
232
233                                                 /* second field */
234                                                 pq_sendstring(&buf, "timeline");                /* col name */
235                                                 pq_sendint(&buf, 0, 4); /* table oid */
236                                                 pq_sendint(&buf, 0, 2); /* attnum */
237                                                 pq_sendint(&buf, INT4OID, 4);   /* type oid */
238                                                 pq_sendint(&buf, 4, 2); /* typlen */
239                                                 pq_sendint(&buf, 0, 4); /* typmod */
240                                                 pq_sendint(&buf, 0, 2); /* format code */
241                                                 pq_endmessage(&buf);
242
243                                                 /* Send a DataRow message */
244                                                 pq_beginmessage(&buf, 'D');
245                                                 pq_sendint(&buf, 2, 2); /* # of columns */
246                                                 pq_sendint(&buf, strlen(sysid), 4);             /* col1 len */
247                                                 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
248                                                 pq_sendint(&buf, strlen(tli), 4);               /* col2 len */
249                                                 pq_sendbytes(&buf, (char *) tli, strlen(tli));
250                                                 pq_endmessage(&buf);
251
252                                                 /* Send CommandComplete and ReadyForQuery messages */
253                                                 EndCommand("SELECT", DestRemote);
254                                                 ReadyForQuery(DestRemote);
255                                         }
256                                         else if (sscanf(query_string, "START_REPLICATION %X/%X",
257                                                                         &recptr.xlogid, &recptr.xrecoff) == 2)
258                                         {
259                                                 StringInfoData buf;
260
261                                                 /* Send a CopyOutResponse message, and start streaming */
262                                                 pq_beginmessage(&buf, 'H');
263                                                 pq_sendbyte(&buf, 0);
264                                                 pq_sendint(&buf, 0, 2);
265                                                 pq_endmessage(&buf);
266                                                 pq_flush();
267
268                                                 /*
269                                                  * Initialize position to the received one, then the
270                                                  * xlog records begin to be shipped from that position
271                                                  */
272                                                 sentPtr = recptr;
273
274                                                 /* break out of the loop */
275                                                 replication_started = true;
276                                         }
277                                         else
278                                         {
279                                                 ereport(FATAL,
280                                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
281                                                                  errmsg("invalid standby query string: %s", query_string)));
282                                         }
283                                         break;
284                                 }
285
286                         case 'X':
287                                 /* standby is closing the connection */
288                                 proc_exit(0);
289
290                         case EOF:
291                                 /* standby disconnected unexpectedly */
292                                 ereport(COMMERROR,
293                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
294                                                  errmsg("unexpected EOF on standby connection")));
295                                 proc_exit(0);
296
297                         default:
298                                 ereport(FATAL,
299                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
300                                                  errmsg("invalid standby handshake message type %d", firstchar)));
301                 }
302         }
303 }
304
305 /*
306  * Check if the remote end has closed the connection.
307  */
308 static void
309 CheckClosedConnection(void)
310 {
311         unsigned char firstchar;
312         int                     r;
313
314         r = pq_getbyte_if_available(&firstchar);
315         if (r < 0)
316         {
317                 /* unexpected error or EOF */
318                 ereport(COMMERROR,
319                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
320                                  errmsg("unexpected EOF on standby connection")));
321                 proc_exit(0);
322         }
323         if (r == 0)
324         {
325                 /* no data available without blocking */
326                 return;
327         }
328
329         /* Handle the very limited subset of commands expected in this phase */
330         switch (firstchar)
331         {
332                         /*
333                          * 'X' means that the standby is closing down the socket.
334                          */
335                 case 'X':
336                         proc_exit(0);
337
338                 default:
339                         ereport(FATAL,
340                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
341                                          errmsg("invalid standby closing message type %d",
342                                                         firstchar)));
343         }
344 }
345
346 /* Main loop of walsender process */
347 static int
348 WalSndLoop(void)
349 {
350         StringInfoData output_message;
351
352         initStringInfo(&output_message);
353
354         /* Loop forever */
355         for (;;)
356         {
357                 long    remain;         /* remaining time (us) */
358
359                 /*
360                  * Emergency bailout if postmaster has died.  This is to avoid the
361                  * necessity for manual cleanup of all postmaster children.
362                  */
363                 if (!PostmasterIsAlive(true))
364                         exit(1);
365                 /* Process any requests or signals received recently */
366                 if (got_SIGHUP)
367                 {
368                         got_SIGHUP = false;
369                         ProcessConfigFile(PGC_SIGHUP);
370                 }
371
372                 /*
373                  * When SIGUSR2 arrives, we send all outstanding logs up to the
374                  * shutdown checkpoint record (i.e., the latest record) and exit.
375                  */
376                 if (ready_to_stop)
377                 {
378                         XLogSend(&output_message);
379                         shutdown_requested = true;
380                 }
381
382                 /* Normal exit from the walsender is here */
383                 if (shutdown_requested)
384                 {
385                         /* Inform the standby that XLOG streaming was done */
386                         pq_puttextmessage('C', "COPY 0");
387                         pq_flush();
388
389                         proc_exit(0);
390                 }
391
392                 /*
393                  * Nap for the configured time or until a message arrives.
394                  *
395                  * On some platforms, signals won't interrupt the sleep.  To ensure we
396                  * respond reasonably promptly when someone signals us, break down the
397                  * sleep into NAPTIME_PER_CYCLE increments, and check for
398                  * interrupts after each nap.
399                  */
400                 remain = WalSndDelay * 1000L;
401                 while (remain > 0)
402                 {
403                         if (got_SIGHUP || shutdown_requested || ready_to_stop)
404                                 break;
405
406                         /*
407                          * Check to see whether a message from the standby or an interrupt
408                          * from other processes has arrived.
409                          */
410                         pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
411                         CheckClosedConnection();
412
413                         remain -= NAPTIME_PER_CYCLE;
414                 }
415
416                 /* Attempt to send the log once every loop */
417                 if (!XLogSend(&output_message))
418                         goto eof;
419         }
420
421         /* can't get here because the above loop never exits */
422         return 1;
423
424 eof:
425
426         /*
427          * Reset whereToSendOutput to prevent ereport from attempting to send any
428          * more messages to the standby.
429          */
430         if (whereToSendOutput == DestRemote)
431                 whereToSendOutput = DestNone;
432
433         proc_exit(0);
434         return 1;                                       /* keep the compiler quiet */
435 }
436
437 /* Initialize a per-walsender data structure for this walsender process */
438 static void
439 InitWalSnd(void)
440 {
441         /* use volatile pointer to prevent code rearrangement */
442         int                     i;
443
444         /*
445          * WalSndCtl should be set up already (we inherit this by fork() or
446          * EXEC_BACKEND mechanism from the postmaster).
447          */
448         Assert(WalSndCtl != NULL);
449         Assert(MyWalSnd == NULL);
450
451         /*
452          * Find a free walsender slot and reserve it. If this fails, we must be
453          * out of WalSnd structures.
454          */
455         for (i = 0; i < max_wal_senders; i++)
456         {
457                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
458
459                 SpinLockAcquire(&walsnd->mutex);
460
461                 if (walsnd->pid != 0)
462                 {
463                         SpinLockRelease(&walsnd->mutex);
464                         continue;
465                 }
466                 else
467                 {
468                         /* found */
469                         MyWalSnd = (WalSnd *) walsnd;
470                         walsnd->pid = MyProcPid;
471                         MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
472                         SpinLockRelease(&walsnd->mutex);
473                         break;
474                 }
475         }
476         if (MyWalSnd == NULL)
477                 ereport(FATAL,
478                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
479                                  errmsg("number of requested standby connections "
480                                         "exceeds max_wal_senders (currently %d)",
481                                         max_wal_senders)));
482
483         /* Arrange to clean up at walsender exit */
484         on_shmem_exit(WalSndKill, 0);
485 }
486
487 /* Destroy the per-walsender data structure for this walsender process */
488 static void
489 WalSndKill(int code, Datum arg)
490 {
491         Assert(MyWalSnd != NULL);
492
493         /*
494          * Mark WalSnd struct no longer in use. Assume that no lock is required
495          * for this.
496          */
497         MyWalSnd->pid = 0;
498
499         /* WalSnd struct isn't mine anymore */
500         MyWalSnd = NULL;
501 }
502
503 /*
504  * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
505  */
506 void
507 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
508 {
509         char            path[MAXPGPATH];
510         uint32          startoff;
511
512         while (nbytes > 0)
513         {
514                 int                     segbytes;
515                 int                     readbytes;
516
517                 startoff = recptr.xrecoff % XLogSegSize;
518
519                 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
520                 {
521                         /* Switch to another logfile segment */
522                         if (sendFile >= 0)
523                                 close(sendFile);
524
525                         XLByteToSeg(recptr, sendId, sendSeg);
526                         XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
527
528                         sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
529                         if (sendFile < 0)
530                                 ereport(FATAL,  /* XXX: Why FATAL? */
531                                                 (errcode_for_file_access(),
532                                                  errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
533                                                                 path, sendId, sendSeg)));
534                         sendOff = 0;
535                 }
536
537                 /* Need to seek in the file? */
538                 if (sendOff != startoff)
539                 {
540                         if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
541                                 ereport(FATAL,
542                                                 (errcode_for_file_access(),
543                                                  errmsg("could not seek in log file %u, segment %u to offset %u: %m",
544                                                                 sendId, sendSeg, startoff)));
545                         sendOff = startoff;
546                 }
547
548                 /* How many bytes are within this segment? */
549                 if (nbytes > (XLogSegSize - startoff))
550                         segbytes = XLogSegSize - startoff;
551                 else
552                         segbytes = nbytes;
553
554                 readbytes = read(sendFile, buf, segbytes);
555                 if (readbytes <= 0)
556                         ereport(FATAL,
557                                         (errcode_for_file_access(),
558                         errmsg("could not read from log file %u, segment %u, offset %u, "
559                                    "length %lu: %m",
560                                    sendId, sendSeg, sendOff, (unsigned long) segbytes)));
561
562                 /* Update state for read */
563                 XLByteAdvance(recptr, readbytes);
564
565                 sendOff += readbytes;
566                 nbytes -= readbytes;
567                 buf += readbytes;
568         }
569 }
570
571 /*
572  * Read all WAL that's been written (and flushed) since last cycle, and send
573  * it to client.
574  *
575  * Returns true if OK, false if trouble.
576  */
577 static bool
578 XLogSend(StringInfo outMsg)
579 {
580         XLogRecPtr      SendRqstPtr;
581         char            activitymsg[50];
582
583         /* use volatile pointer to prevent code rearrangement */
584         volatile WalSnd *walsnd = MyWalSnd;
585
586         /* Attempt to send all records flushed to the disk already */
587         SendRqstPtr = GetWriteRecPtr();
588
589         /* Quick exit if nothing to do */
590         if (!XLByteLT(sentPtr, SendRqstPtr))
591                 return true;
592
593         /*
594          * We gather multiple records together by issuing just one XLogRead() of a
595          * suitable size, and send them as one CopyData message. Repeat until
596          * we've sent everything we can.
597          */
598         while (XLByteLT(sentPtr, SendRqstPtr))
599         {
600                 XLogRecPtr      startptr;
601                 XLogRecPtr      endptr;
602                 Size            nbytes;
603
604                 /*
605                  * Figure out how much to send in one message. If there's less than
606                  * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
607                  * MAX_SEND_SIZE bytes, but round to page boundary.
608                  *
609                  * The rounding is not only for performance reasons. Walreceiver
610                  * relies on the fact that we never split a WAL record across two
611                  * messages. Since a long WAL record is split at page boundary into
612                  * continuation records, page boundary is always a safe cut-off point.
613                  * We also assume that SendRqstPtr never points in the middle of a WAL
614                  * record.
615                  */
616                 startptr = sentPtr;
617                 if (startptr.xrecoff >= XLogFileSize)
618                 {
619                         /*
620                          * crossing a logid boundary, skip the non-existent last log
621                          * segment in previous logical log file.
622                          */
623                         startptr.xlogid += 1;
624                         startptr.xrecoff = 0;
625                 }
626
627                 endptr = startptr;
628                 XLByteAdvance(endptr, MAX_SEND_SIZE);
629                 /* round down to page boundary. */
630                 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
631                 /* if we went beyond SendRqstPtr, back off */
632                 if (XLByteLT(SendRqstPtr, endptr))
633                         endptr = SendRqstPtr;
634
635                 /*
636                  * OK to read and send the slice.
637                  *
638                  * We don't need to convert the xlogid/xrecoff from host byte order to
639                  * network byte order because the both server can be expected to have
640                  * the same byte order. If they have different byte order, we don't
641                  * reach here.
642                  */
643                 pq_sendbyte(outMsg, 'w');
644                 pq_sendbytes(outMsg, (char *) &startptr, sizeof(startptr));
645
646                 if (endptr.xlogid != startptr.xlogid)
647                 {
648                         Assert(endptr.xlogid == startptr.xlogid + 1);
649                         nbytes = endptr.xrecoff + XLogFileSize - startptr.xrecoff;
650                 }
651                 else
652                         nbytes = endptr.xrecoff - startptr.xrecoff;
653
654                 sentPtr = endptr;
655
656                 /*
657                  * Read the log directly into the output buffer to prevent extra
658                  * memcpy calls.
659                  */
660                 enlargeStringInfo(outMsg, nbytes);
661
662                 XLogRead(&outMsg->data[outMsg->len], startptr, nbytes);
663                 outMsg->len += nbytes;
664                 outMsg->data[outMsg->len] = '\0';
665
666                 pq_putmessage('d', outMsg->data, outMsg->len);
667                 resetStringInfo(outMsg);
668         }
669
670         /* Update shared memory status */
671         SpinLockAcquire(&walsnd->mutex);
672         walsnd->sentPtr = sentPtr;
673         SpinLockRelease(&walsnd->mutex);
674
675         /* Flush pending output */
676         if (pq_flush())
677                 return false;
678
679         /* Report progress of XLOG streaming in PS display */
680         snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
681                          sentPtr.xlogid, sentPtr.xrecoff);
682         set_ps_display(activitymsg, false);
683
684         return true;
685 }
686
687 /* SIGHUP: set flag to re-read config file at next convenient time */
688 static void
689 WalSndSigHupHandler(SIGNAL_ARGS)
690 {
691         got_SIGHUP = true;
692 }
693
694 /* SIGTERM: set flag to shut down */
695 static void
696 WalSndShutdownHandler(SIGNAL_ARGS)
697 {
698         shutdown_requested = true;
699 }
700
701 /*
702  * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
703  *
704  * Some backend has bought the farm,
705  * so we need to stop what we're doing and exit.
706  */
707 static void
708 WalSndQuickDieHandler(SIGNAL_ARGS)
709 {
710         PG_SETMASK(&BlockSig);
711
712         /*
713          * We DO NOT want to run proc_exit() callbacks -- we're here because
714          * shared memory may be corrupted, so we don't want to try to clean up our
715          * transaction.  Just nail the windows shut and get out of town.  Now that
716          * there's an atexit callback to prevent third-party code from breaking
717          * things by calling exit() directly, we have to reset the callbacks
718          * explicitly to make this work as intended.
719          */
720         on_exit_reset();
721
722         /*
723          * Note we do exit(2) not exit(0).      This is to force the postmaster into a
724          * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
725          * backend.  This is necessary precisely because we don't clean up our
726          * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
727          * should ensure the postmaster sees this as a crash, too, but no harm in
728          * being doubly sure.)
729          */
730         exit(2);
731 }
732
733 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
734 static void
735 WalSndLastCycleHandler(SIGNAL_ARGS)
736 {
737         ready_to_stop = true;
738 }
739
740 /* Set up signal handlers */
741 void
742 WalSndSignals(void)
743 {
744         /* Set up signal handlers */
745         pqsignal(SIGHUP, WalSndSigHupHandler);          /* set flag to read config
746                                                                                                  * file */
747         pqsignal(SIGINT, SIG_IGN);      /* not used */
748         pqsignal(SIGTERM, WalSndShutdownHandler);       /* request shutdown */
749         pqsignal(SIGQUIT, WalSndQuickDieHandler);       /* hard crash time */
750         pqsignal(SIGALRM, SIG_IGN);
751         pqsignal(SIGPIPE, SIG_IGN);
752         pqsignal(SIGUSR1, SIG_IGN); /* not used */
753         pqsignal(SIGUSR2, WalSndLastCycleHandler);      /* request a last cycle and
754                                                                                                  * shutdown */
755
756         /* Reset some signals that are accepted by postmaster but not here */
757         pqsignal(SIGCHLD, SIG_DFL);
758         pqsignal(SIGTTIN, SIG_DFL);
759         pqsignal(SIGTTOU, SIG_DFL);
760         pqsignal(SIGCONT, SIG_DFL);
761         pqsignal(SIGWINCH, SIG_DFL);
762 }
763
764 /* Report shared-memory space needed by WalSndShmemInit */
765 Size
766 WalSndShmemSize(void)
767 {
768         Size            size = 0;
769
770         size = offsetof(WalSndCtlData, walsnds);
771         size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
772
773         return size;
774 }
775
776 /* Allocate and initialize walsender-related shared memory */
777 void
778 WalSndShmemInit(void)
779 {
780         bool            found;
781         int                     i;
782
783         WalSndCtl = (WalSndCtlData *)
784                 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
785
786         if (WalSndCtl == NULL)
787                 ereport(FATAL,
788                                 (errcode(ERRCODE_OUT_OF_MEMORY),
789                                  errmsg("not enough shared memory for walsender")));
790         if (found)
791                 return;                                 /* already initialized */
792
793         /* Initialize the data structures */
794         MemSet(WalSndCtl, 0, WalSndShmemSize());
795
796         for (i = 0; i < max_wal_senders; i++)
797         {
798                 WalSnd     *walsnd = &WalSndCtl->walsnds[i];
799
800                 SpinLockInit(&walsnd->mutex);
801         }
802 }
803
804 /*
805  * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
806  * if none.
807  */
808 XLogRecPtr
809 GetOldestWALSendPointer(void)
810 {
811         XLogRecPtr      oldest = {0, 0};
812         int                     i;
813         bool            found = false;
814
815         for (i = 0; i < max_wal_senders; i++)
816         {
817                 /* use volatile pointer to prevent code rearrangement */
818                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
819                 XLogRecPtr      recptr;
820
821                 if (walsnd->pid == 0)
822                         continue;
823
824                 SpinLockAcquire(&walsnd->mutex);
825                 recptr = walsnd->sentPtr;
826                 SpinLockRelease(&walsnd->mutex);
827
828                 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
829                         continue;
830
831                 if (!found || XLByteLT(recptr, oldest))
832                         oldest = recptr;
833                 found = true;
834         }
835         return oldest;
836 }