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