OSDN Git Service

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