PostgreSQL Source Code  git master
pg_recvlogical.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_recvlogical.c - receive data from a logical decoding slot in a streaming
4  * fashion and write it to a local file.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/bin/pg_basebackup/pg_recvlogical.c
10  *-------------------------------------------------------------------------
11  */
12 
13 #include "postgres_fe.h"
14 
15 #include <dirent.h>
16 #include <limits.h>
17 #include <sys/stat.h>
18 #include <unistd.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
21 #endif
22 
23 #include "access/xlog_internal.h"
24 #include "common/fe_memutils.h"
25 #include "common/file_perm.h"
26 #include "common/logging.h"
27 #include "fe_utils/option_utils.h"
28 #include "getopt_long.h"
29 #include "libpq-fe.h"
30 #include "libpq/pqsignal.h"
31 #include "pqexpbuffer.h"
32 #include "streamutil.h"
33 
34 /* Time to sleep between reconnection attempts */
35 #define RECONNECT_SLEEP_TIME 5
36 
37 /* Global Options */
38 static char *outfile = NULL;
39 static int verbose = 0;
40 static bool two_phase = false;
41 static int noloop = 0;
42 static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
43 static int fsync_interval = 10 * 1000; /* 10 sec = default */
46 static bool do_create_slot = false;
47 static bool slot_exists_ok = false;
48 static bool do_start_slot = false;
49 static bool do_drop_slot = false;
50 static char *replication_slot = NULL;
51 
52 /* filled pairwise with option, value. value may be NULL */
53 static char **options;
54 static size_t noptions = 0;
55 static const char *plugin = "test_decoding";
56 
57 /* Global State */
58 static int outfd = -1;
59 static volatile sig_atomic_t time_to_abort = false;
60 static volatile sig_atomic_t output_reopen = false;
61 static bool output_isfile;
63 static bool output_needs_fsync = false;
66 
67 static void usage(void);
68 static void StreamLogicalLog(void);
71  bool keepalive, XLogRecPtr lsn);
72 
73 static void
74 usage(void)
75 {
76  printf(_("%s controls PostgreSQL logical decoding streams.\n\n"),
77  progname);
78  printf(_("Usage:\n"));
79  printf(_(" %s [OPTION]...\n"), progname);
80  printf(_("\nAction to be performed:\n"));
81  printf(_(" --create-slot create a new replication slot (for the slot's name see --slot)\n"));
82  printf(_(" --drop-slot drop the replication slot (for the slot's name see --slot)\n"));
83  printf(_(" --start start streaming in a replication slot (for the slot's name see --slot)\n"));
84  printf(_("\nOptions:\n"));
85  printf(_(" -E, --endpos=LSN exit after receiving the specified LSN\n"));
86  printf(_(" -f, --file=FILE receive log into this file, - for stdout\n"));
87  printf(_(" -F --fsync-interval=SECS\n"
88  " time between fsyncs to the output file (default: %d)\n"), (fsync_interval / 1000));
89  printf(_(" --if-not-exists do not error if slot already exists when creating a slot\n"));
90  printf(_(" -I, --startpos=LSN where in an existing slot should the streaming start\n"));
91  printf(_(" -n, --no-loop do not loop on connection lost\n"));
92  printf(_(" -o, --option=NAME[=VALUE]\n"
93  " pass option NAME with optional value VALUE to the\n"
94  " output plugin\n"));
95  printf(_(" -P, --plugin=PLUGIN use output plugin PLUGIN (default: %s)\n"), plugin);
96  printf(_(" -s, --status-interval=SECS\n"
97  " time between status packets sent to server (default: %d)\n"), (standby_message_timeout / 1000));
98  printf(_(" -S, --slot=SLOTNAME name of the logical replication slot\n"));
99  printf(_(" -t, --two-phase enable two-phase decoding when creating a slot\n"));
100  printf(_(" -v, --verbose output verbose messages\n"));
101  printf(_(" -V, --version output version information, then exit\n"));
102  printf(_(" -?, --help show this help, then exit\n"));
103  printf(_("\nConnection options:\n"));
104  printf(_(" -d, --dbname=DBNAME database to connect to\n"));
105  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
106  printf(_(" -p, --port=PORT database server port number\n"));
107  printf(_(" -U, --username=NAME connect as specified database user\n"));
108  printf(_(" -w, --no-password never prompt for password\n"));
109  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
110  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
111  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
112 }
113 
114 /*
115  * Send a Standby Status Update message to server.
116  */
117 static bool
118 sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
119 {
120  static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
121  static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
122 
123  char replybuf[1 + 8 + 8 + 8 + 8 + 1];
124  int len = 0;
125 
126  /*
127  * we normally don't want to send superfluous feedback, but if it's
128  * because of a timeout we need to, otherwise wal_sender_timeout will kill
129  * us.
130  */
131  if (!force &&
132  last_written_lsn == output_written_lsn &&
133  last_fsync_lsn == output_fsync_lsn)
134  return true;
135 
136  if (verbose)
137  pg_log_info("confirming write up to %X/%X, flush to %X/%X (slot %s)",
141 
142  replybuf[len] = 'r';
143  len += 1;
144  fe_sendint64(output_written_lsn, &replybuf[len]); /* write */
145  len += 8;
146  fe_sendint64(output_fsync_lsn, &replybuf[len]); /* flush */
147  len += 8;
148  fe_sendint64(InvalidXLogRecPtr, &replybuf[len]); /* apply */
149  len += 8;
150  fe_sendint64(now, &replybuf[len]); /* sendTime */
151  len += 8;
152  replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
153  len += 1;
154 
156  last_written_lsn = output_written_lsn;
157  last_fsync_lsn = output_fsync_lsn;
158 
159  if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
160  {
161  pg_log_error("could not send feedback packet: %s",
163  return false;
164  }
165 
166  return true;
167 }
168 
169 static void
171 {
172  if (conn != NULL)
173  PQfinish(conn);
174 }
175 
176 static bool
178 {
180 
182 
183  if (fsync_interval <= 0)
184  return true;
185 
186  if (!output_needs_fsync)
187  return true;
188 
189  output_needs_fsync = false;
190 
191  /* can only fsync if it's a regular file */
192  if (!output_isfile)
193  return true;
194 
195  if (fsync(outfd) != 0)
196  pg_fatal("could not fsync file \"%s\": %m", outfile);
197 
198  return true;
199 }
200 
201 /*
202  * Start the log streaming
203  */
204 static void
206 {
207  PGresult *res;
208  char *copybuf = NULL;
209  TimestampTz last_status = -1;
210  int i;
211  PQExpBuffer query;
212 
215 
216  /*
217  * Connect in replication mode to the server
218  */
219  if (!conn)
220  conn = GetConnection();
221  if (!conn)
222  /* Error message already written in GetConnection() */
223  return;
224 
225  /*
226  * Start the replication
227  */
228  if (verbose)
229  pg_log_info("starting log streaming at %X/%X (slot %s)",
232 
233  /* Initiate the replication stream at specified location */
234  query = createPQExpBuffer();
235  appendPQExpBuffer(query, "START_REPLICATION SLOT \"%s\" LOGICAL %X/%X",
237 
238  /* print options if there are any */
239  if (noptions)
240  appendPQExpBufferStr(query, " (");
241 
242  for (i = 0; i < noptions; i++)
243  {
244  /* separator */
245  if (i > 0)
246  appendPQExpBufferStr(query, ", ");
247 
248  /* write option name */
249  appendPQExpBuffer(query, "\"%s\"", options[(i * 2)]);
250 
251  /* write option value if specified */
252  if (options[(i * 2) + 1] != NULL)
253  appendPQExpBuffer(query, " '%s'", options[(i * 2) + 1]);
254  }
255 
256  if (noptions)
257  appendPQExpBufferChar(query, ')');
258 
259  res = PQexec(conn, query->data);
261  {
262  pg_log_error("could not send replication command \"%s\": %s",
263  query->data, PQresultErrorMessage(res));
264  PQclear(res);
265  goto error;
266  }
267  PQclear(res);
268  resetPQExpBuffer(query);
269 
270  if (verbose)
271  pg_log_info("streaming initiated");
272 
273  while (!time_to_abort)
274  {
275  int r;
276  int bytes_left;
277  int bytes_written;
279  int hdr_len;
280  XLogRecPtr cur_record_lsn = InvalidXLogRecPtr;
281 
282  if (copybuf != NULL)
283  {
285  copybuf = NULL;
286  }
287 
288  /*
289  * Potentially send a status message to the primary.
290  */
292 
293  if (outfd != -1 &&
296  {
297  if (!OutputFsync(now))
298  goto error;
299  }
300 
301  if (standby_message_timeout > 0 &&
302  feTimestampDifferenceExceeds(last_status, now,
304  {
305  /* Time to send feedback! */
306  if (!sendFeedback(conn, now, true, false))
307  goto error;
308 
309  last_status = now;
310  }
311 
312  /* got SIGHUP, close output file */
313  if (outfd != -1 && output_reopen && strcmp(outfile, "-") != 0)
314  {
316  if (!OutputFsync(now))
317  goto error;
318  close(outfd);
319  outfd = -1;
320  }
321  output_reopen = false;
322 
323  /* open the output file, if not open yet */
324  if (outfd == -1)
325  {
326  struct stat statbuf;
327 
328  if (strcmp(outfile, "-") == 0)
329  outfd = fileno(stdout);
330  else
331  outfd = open(outfile, O_CREAT | O_APPEND | O_WRONLY | PG_BINARY,
332  S_IRUSR | S_IWUSR);
333  if (outfd == -1)
334  {
335  pg_log_error("could not open log file \"%s\": %m", outfile);
336  goto error;
337  }
338 
339  if (fstat(outfd, &statbuf) != 0)
340  {
341  pg_log_error("could not stat file \"%s\": %m", outfile);
342  goto error;
343  }
344 
345  output_isfile = S_ISREG(statbuf.st_mode) && !isatty(outfd);
346  }
347 
348  r = PQgetCopyData(conn, &copybuf, 1);
349  if (r == 0)
350  {
351  /*
352  * In async mode, and no data available. We block on reading but
353  * not more than the specified timeout, so that we can send a
354  * response back to the client.
355  */
356  fd_set input_mask;
357  TimestampTz message_target = 0;
358  TimestampTz fsync_target = 0;
359  struct timeval timeout;
360  struct timeval *timeoutptr = NULL;
361 
362  if (PQsocket(conn) < 0)
363  {
364  pg_log_error("invalid socket: %s", PQerrorMessage(conn));
365  goto error;
366  }
367 
368  FD_ZERO(&input_mask);
369  FD_SET(PQsocket(conn), &input_mask);
370 
371  /* Compute when we need to wakeup to send a keepalive message. */
373  message_target = last_status + (standby_message_timeout - 1) *
374  ((int64) 1000);
375 
376  /* Compute when we need to wakeup to fsync the output file. */
378  fsync_target = output_last_fsync + (fsync_interval - 1) *
379  ((int64) 1000);
380 
381  /* Now compute when to wakeup. */
382  if (message_target > 0 || fsync_target > 0)
383  {
384  TimestampTz targettime;
385  long secs;
386  int usecs;
387 
388  targettime = message_target;
389 
390  if (fsync_target > 0 && fsync_target < targettime)
391  targettime = fsync_target;
392 
394  targettime,
395  &secs,
396  &usecs);
397  if (secs <= 0)
398  timeout.tv_sec = 1; /* Always sleep at least 1 sec */
399  else
400  timeout.tv_sec = secs;
401  timeout.tv_usec = usecs;
402  timeoutptr = &timeout;
403  }
404 
405  r = select(PQsocket(conn) + 1, &input_mask, NULL, NULL, timeoutptr);
406  if (r == 0 || (r < 0 && errno == EINTR))
407  {
408  /*
409  * Got a timeout or signal. Continue the loop and either
410  * deliver a status packet to the server or just go back into
411  * blocking.
412  */
413  continue;
414  }
415  else if (r < 0)
416  {
417  pg_log_error("%s() failed: %m", "select");
418  goto error;
419  }
420 
421  /* Else there is actually data on the socket */
422  if (PQconsumeInput(conn) == 0)
423  {
424  pg_log_error("could not receive data from WAL stream: %s",
426  goto error;
427  }
428  continue;
429  }
430 
431  /* End of copy stream */
432  if (r == -1)
433  break;
434 
435  /* Failure while reading the copy stream */
436  if (r == -2)
437  {
438  pg_log_error("could not read COPY data: %s",
440  goto error;
441  }
442 
443  /* Check the message type. */
444  if (copybuf[0] == 'k')
445  {
446  int pos;
447  bool replyRequested;
448  XLogRecPtr walEnd;
449  bool endposReached = false;
450 
451  /*
452  * Parse the keepalive message, enclosed in the CopyData message.
453  * We just check if the server requested a reply, and ignore the
454  * rest.
455  */
456  pos = 1; /* skip msgtype 'k' */
457  walEnd = fe_recvint64(&copybuf[pos]);
459 
460  pos += 8; /* read walEnd */
461 
462  pos += 8; /* skip sendTime */
463 
464  if (r < pos + 1)
465  {
466  pg_log_error("streaming header too small: %d", r);
467  goto error;
468  }
469  replyRequested = copybuf[pos];
470 
471  if (endpos != InvalidXLogRecPtr && walEnd >= endpos)
472  {
473  /*
474  * If there's nothing to read on the socket until a keepalive
475  * we know that the server has nothing to send us; and if
476  * walEnd has passed endpos, we know nothing else can have
477  * committed before endpos. So we can bail out now.
478  */
479  endposReached = true;
480  }
481 
482  /* Send a reply, if necessary */
483  if (replyRequested || endposReached)
484  {
485  if (!flushAndSendFeedback(conn, &now))
486  goto error;
487  last_status = now;
488  }
489 
490  if (endposReached)
491  {
493  time_to_abort = true;
494  break;
495  }
496 
497  continue;
498  }
499  else if (copybuf[0] != 'w')
500  {
501  pg_log_error("unrecognized streaming header: \"%c\"",
502  copybuf[0]);
503  goto error;
504  }
505 
506  /*
507  * Read the header of the XLogData message, enclosed in the CopyData
508  * message. We only need the WAL location field (dataStart), the rest
509  * of the header is ignored.
510  */
511  hdr_len = 1; /* msgtype 'w' */
512  hdr_len += 8; /* dataStart */
513  hdr_len += 8; /* walEnd */
514  hdr_len += 8; /* sendTime */
515  if (r < hdr_len + 1)
516  {
517  pg_log_error("streaming header too small: %d", r);
518  goto error;
519  }
520 
521  /* Extract WAL location for this block */
522  cur_record_lsn = fe_recvint64(&copybuf[1]);
523 
524  if (endpos != InvalidXLogRecPtr && cur_record_lsn > endpos)
525  {
526  /*
527  * We've read past our endpoint, so prepare to go away being
528  * cautious about what happens to our output data.
529  */
530  if (!flushAndSendFeedback(conn, &now))
531  goto error;
532  prepareToTerminate(conn, endpos, false, cur_record_lsn);
533  time_to_abort = true;
534  break;
535  }
536 
537  output_written_lsn = Max(cur_record_lsn, output_written_lsn);
538 
539  bytes_left = r - hdr_len;
540  bytes_written = 0;
541 
542  /* signal that a fsync is needed */
543  output_needs_fsync = true;
544 
545  while (bytes_left)
546  {
547  int ret;
548 
549  ret = write(outfd,
550  copybuf + hdr_len + bytes_written,
551  bytes_left);
552 
553  if (ret < 0)
554  {
555  pg_log_error("could not write %d bytes to log file \"%s\": %m",
556  bytes_left, outfile);
557  goto error;
558  }
559 
560  /* Write was successful, advance our position */
561  bytes_written += ret;
562  bytes_left -= ret;
563  }
564 
565  if (write(outfd, "\n", 1) != 1)
566  {
567  pg_log_error("could not write %d bytes to log file \"%s\": %m",
568  1, outfile);
569  goto error;
570  }
571 
572  if (endpos != InvalidXLogRecPtr && cur_record_lsn == endpos)
573  {
574  /* endpos was exactly the record we just processed, we're done */
575  if (!flushAndSendFeedback(conn, &now))
576  goto error;
577  prepareToTerminate(conn, endpos, false, cur_record_lsn);
578  time_to_abort = true;
579  break;
580  }
581  }
582 
583  res = PQgetResult(conn);
585  {
586  PQclear(res);
587 
588  /*
589  * We're doing a client-initiated clean exit and have sent CopyDone to
590  * the server. Drain any messages, so we don't miss a last-minute
591  * ErrorResponse. The walsender stops generating XLogData records once
592  * it sees CopyDone, so expect this to finish quickly. After CopyDone,
593  * it's too late for sendFeedback(), even if this were to take a long
594  * time. Hence, use synchronous-mode PQgetCopyData().
595  */
596  while (1)
597  {
598  int r;
599 
600  if (copybuf != NULL)
601  {
603  copybuf = NULL;
604  }
605  r = PQgetCopyData(conn, &copybuf, 0);
606  if (r == -1)
607  break;
608  if (r == -2)
609  {
610  pg_log_error("could not read COPY data: %s",
612  time_to_abort = false; /* unclean exit */
613  goto error;
614  }
615  }
616 
617  res = PQgetResult(conn);
618  }
620  {
621  pg_log_error("unexpected termination of replication stream: %s",
623  goto error;
624  }
625  PQclear(res);
626 
627  if (outfd != -1 && strcmp(outfile, "-") != 0)
628  {
630 
631  /* no need to jump to error on failure here, we're finishing anyway */
632  OutputFsync(t);
633 
634  if (close(outfd) != 0)
635  pg_log_error("could not close file \"%s\": %m", outfile);
636  }
637  outfd = -1;
638 error:
639  if (copybuf != NULL)
640  {
642  copybuf = NULL;
643  }
644  destroyPQExpBuffer(query);
645  PQfinish(conn);
646  conn = NULL;
647 }
648 
649 /*
650  * Unfortunately we can't do sensible signal handling on windows...
651  */
652 #ifndef WIN32
653 
654 /*
655  * When sigint is called, just tell the system to exit at the next possible
656  * moment.
657  */
658 static void
659 sigint_handler(int signum)
660 {
661  time_to_abort = true;
662 }
663 
664 /*
665  * Trigger the output file to be reopened.
666  */
667 static void
668 sighup_handler(int signum)
669 {
670  output_reopen = true;
671 }
672 #endif
673 
674 
675 int
676 main(int argc, char **argv)
677 {
678  static struct option long_options[] = {
679 /* general options */
680  {"file", required_argument, NULL, 'f'},
681  {"fsync-interval", required_argument, NULL, 'F'},
682  {"no-loop", no_argument, NULL, 'n'},
683  {"verbose", no_argument, NULL, 'v'},
684  {"two-phase", no_argument, NULL, 't'},
685  {"version", no_argument, NULL, 'V'},
686  {"help", no_argument, NULL, '?'},
687 /* connection options */
688  {"dbname", required_argument, NULL, 'd'},
689  {"host", required_argument, NULL, 'h'},
690  {"port", required_argument, NULL, 'p'},
691  {"username", required_argument, NULL, 'U'},
692  {"no-password", no_argument, NULL, 'w'},
693  {"password", no_argument, NULL, 'W'},
694 /* replication options */
695  {"startpos", required_argument, NULL, 'I'},
696  {"endpos", required_argument, NULL, 'E'},
697  {"option", required_argument, NULL, 'o'},
698  {"plugin", required_argument, NULL, 'P'},
699  {"status-interval", required_argument, NULL, 's'},
700  {"slot", required_argument, NULL, 'S'},
701 /* action */
702  {"create-slot", no_argument, NULL, 1},
703  {"start", no_argument, NULL, 2},
704  {"drop-slot", no_argument, NULL, 3},
705  {"if-not-exists", no_argument, NULL, 4},
706  {NULL, 0, NULL, 0}
707  };
708  int c;
709  int option_index;
710  uint32 hi,
711  lo;
712  char *db_name;
713 
714  pg_logging_init(argv[0]);
715  progname = get_progname(argv[0]);
716  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
717 
718  if (argc > 1)
719  {
720  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
721  {
722  usage();
723  exit(0);
724  }
725  else if (strcmp(argv[1], "-V") == 0 ||
726  strcmp(argv[1], "--version") == 0)
727  {
728  puts("pg_recvlogical (PostgreSQL) " PG_VERSION);
729  exit(0);
730  }
731  }
732 
733  while ((c = getopt_long(argc, argv, "E:f:F:nvtd:h:p:U:wWI:o:P:s:S:",
734  long_options, &option_index)) != -1)
735  {
736  switch (c)
737  {
738 /* general options */
739  case 'f':
741  break;
742  case 'F':
743  if (!option_parse_int(optarg, "-F/--fsync-interval", 0,
744  INT_MAX / 1000,
745  &fsync_interval))
746  exit(1);
747  fsync_interval *= 1000;
748  break;
749  case 'n':
750  noloop = 1;
751  break;
752  case 'v':
753  verbose++;
754  break;
755  case 't':
756  two_phase = true;
757  break;
758 /* connection options */
759  case 'd':
761  break;
762  case 'h':
764  break;
765  case 'p':
767  break;
768  case 'U':
770  break;
771  case 'w':
772  dbgetpassword = -1;
773  break;
774  case 'W':
775  dbgetpassword = 1;
776  break;
777 /* replication options */
778  case 'I':
779  if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
780  pg_fatal("could not parse start position \"%s\"", optarg);
781  startpos = ((uint64) hi) << 32 | lo;
782  break;
783  case 'E':
784  if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
785  pg_fatal("could not parse end position \"%s\"", optarg);
786  endpos = ((uint64) hi) << 32 | lo;
787  break;
788  case 'o':
789  {
790  char *data = pg_strdup(optarg);
791  char *val = strchr(data, '=');
792 
793  if (val != NULL)
794  {
795  /* remove =; separate data from val */
796  *val = '\0';
797  val++;
798  }
799 
800  noptions += 1;
801  options = pg_realloc(options, sizeof(char *) * noptions * 2);
802 
803  options[(noptions - 1) * 2] = data;
804  options[(noptions - 1) * 2 + 1] = val;
805  }
806 
807  break;
808  case 'P':
810  break;
811  case 's':
812  if (!option_parse_int(optarg, "-s/--status-interval", 0,
813  INT_MAX / 1000,
815  exit(1);
816  standby_message_timeout *= 1000;
817  break;
818  case 'S':
820  break;
821 /* action */
822  case 1:
823  do_create_slot = true;
824  break;
825  case 2:
826  do_start_slot = true;
827  break;
828  case 3:
829  do_drop_slot = true;
830  break;
831  case 4:
832  slot_exists_ok = true;
833  break;
834 
835  default:
836  /* getopt_long already emitted a complaint */
837  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
838  exit(1);
839  }
840  }
841 
842  /*
843  * Any non-option arguments?
844  */
845  if (optind < argc)
846  {
847  pg_log_error("too many command-line arguments (first is \"%s\")",
848  argv[optind]);
849  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
850  exit(1);
851  }
852 
853  /*
854  * Required arguments
855  */
856  if (replication_slot == NULL)
857  {
858  pg_log_error("no slot specified");
859  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
860  exit(1);
861  }
862 
863  if (do_start_slot && outfile == NULL)
864  {
865  pg_log_error("no target file specified");
866  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
867  exit(1);
868  }
869 
870  if (!do_drop_slot && dbname == NULL)
871  {
872  pg_log_error("no database specified");
873  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
874  exit(1);
875  }
876 
878  {
879  pg_log_error("at least one action needs to be specified");
880  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
881  exit(1);
882  }
883 
885  {
886  pg_log_error("cannot use --create-slot or --start together with --drop-slot");
887  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
888  exit(1);
889  }
890 
892  {
893  pg_log_error("cannot use --create-slot or --drop-slot together with --startpos");
894  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
895  exit(1);
896  }
897 
899  {
900  pg_log_error("--endpos may only be specified with --start");
901  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
902  exit(1);
903  }
904 
905  if (two_phase && !do_create_slot)
906  {
907  pg_log_error("--two-phase may only be specified with --create-slot");
908  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
909  exit(1);
910  }
911 
912  /*
913  * Obtain a connection to server. Notably, if we need a password, we want
914  * to collect it from the user immediately.
915  */
916  conn = GetConnection();
917  if (!conn)
918  /* Error message already written in GetConnection() */
919  exit(1);
920  atexit(disconnect_atexit);
921 
922  /*
923  * Trap signals. (Don't do this until after the initial password prompt,
924  * if one is needed, in GetConnection.)
925  */
926 #ifndef WIN32
927  pqsignal(SIGINT, sigint_handler);
929 #endif
930 
931  /*
932  * Run IDENTIFY_SYSTEM to make sure we connected using a database specific
933  * replication connection.
934  */
935  if (!RunIdentifySystem(conn, NULL, NULL, NULL, &db_name))
936  exit(1);
937 
938  if (db_name == NULL)
939  pg_fatal("could not establish database-specific replication connection");
940 
941  /*
942  * Set umask so that directories/files are created with the same
943  * permissions as directories/files in the source data directory.
944  *
945  * pg_mode_mask is set to owner-only by default and then updated in
946  * GetConnection() where we get the mode from the server-side with
947  * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
948  */
949  umask(pg_mode_mask);
950 
951  /* Drop a replication slot. */
952  if (do_drop_slot)
953  {
954  if (verbose)
955  pg_log_info("dropping replication slot \"%s\"", replication_slot);
956 
958  exit(1);
959  }
960 
961  /* Create a replication slot. */
962  if (do_create_slot)
963  {
964  if (verbose)
965  pg_log_info("creating replication slot \"%s\"", replication_slot);
966 
968  false, false, slot_exists_ok, two_phase))
969  exit(1);
971  }
972 
973  if (!do_start_slot)
974  exit(0);
975 
976  /* Stream loop */
977  while (true)
978  {
980  if (time_to_abort)
981  {
982  /*
983  * We've been Ctrl-C'ed or reached an exit limit condition. That's
984  * not an error, so exit without an errorcode.
985  */
986  exit(0);
987  }
988  else if (noloop)
989  pg_fatal("disconnected");
990  else
991  {
992  /* translator: check source for value for %d */
993  pg_log_info("disconnected; waiting %d seconds to try again",
995  pg_usleep(RECONNECT_SLEEP_TIME * 1000000);
996  }
997  }
998 }
999 
1000 /*
1001  * Fsync our output data, and send a feedback message to the server. Returns
1002  * true if successful, false otherwise.
1003  *
1004  * If successful, *now is updated to the current timestamp just before sending
1005  * feedback.
1006  */
1007 static bool
1009 {
1010  /* flush data to disk, so that we send a recent flush pointer */
1011  if (!OutputFsync(*now))
1012  return false;
1014  if (!sendFeedback(conn, *now, true, false))
1015  return false;
1016 
1017  return true;
1018 }
1019 
1020 /*
1021  * Try to inform the server about our upcoming demise, but don't wait around or
1022  * retry on failure.
1023  */
1024 static void
1026 {
1027  (void) PQputCopyEnd(conn, NULL);
1028  (void) PQflush(conn);
1029 
1030  if (verbose)
1031  {
1032  if (keepalive)
1033  pg_log_info("end position %X/%X reached by keepalive",
1035  else
1036  pg_log_info("end position %X/%X reached by WAL record at %X/%X",
1038  }
1039 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
unsigned int uint32
Definition: c.h:441
#define Max(x, y)
Definition: c.h:980
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
#define PG_BINARY
Definition: c.h:1268
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:446
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:134
int64 TimestampTz
Definition: timestamp.h:39
#define _(x)
Definition: elog.c:89
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6908
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4261
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6934
int PQflush(PGconn *conn)
Definition: fe-exec.c:3861
void PQfreemem(void *ptr)
Definition: fe-exec.c:3891
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3270
void PQclear(PGresult *res)
Definition: fe-exec.c:718
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:3286
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2683
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2627
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2273
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:2004
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2082
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2751
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
int pg_mode_mask
Definition: file_perm.c:25
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
long val
Definition: informix.c:664
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
int i
Definition: isn.c:73
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
exit(1)
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
#define pg_log_info(...)
Definition: logging.h:124
const char * progname
Definition: main.c:50
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
#define pg_fatal(...)
const void size_t len
const void * data
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
static int verbose
static int noloop
static bool do_start_slot
static bool OutputFsync(TimestampTz now)
static bool two_phase
static void StreamLogicalLog(void)
static bool output_needs_fsync
static void sigint_handler(int signum)
static XLogRecPtr endpos
int main(int argc, char **argv)
static const char * plugin
static volatile sig_atomic_t time_to_abort
static bool slot_exists_ok
static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos, bool keepalive, XLogRecPtr lsn)
static int fsync_interval
static bool do_drop_slot
static bool output_isfile
static char * replication_slot
static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now)
static XLogRecPtr output_written_lsn
static void sighup_handler(int signum)
static int outfd
static TimestampTz output_last_fsync
static size_t noptions
static char * outfile
static XLogRecPtr output_fsync_lsn
static bool sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
static void usage(void)
static XLogRecPtr startpos
#define RECONNECT_SLEEP_TIME
static bool do_create_slot
static void disconnect_atexit(void)
static int standby_message_timeout
static volatile sig_atomic_t output_reopen
static char ** options
const char * get_progname(const char *argv0)
Definition: path.c:574
#define printf(...)
Definition: port.h:231
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * c
void pg_usleep(long microsec)
Definition: signal.c:53
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
static void error(void)
Definition: sql-dyntest.c:147
int dbgetpassword
Definition: streamutil.c:52
char * dbhost
Definition: streamutil.c:48
int64 fe_recvint64(char *buf)
Definition: streamutil.c:857
TimestampTz feGetCurrentTimestamp(void)
Definition: streamutil.c:792
char * dbport
Definition: streamutil.c:50
void feTimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: streamutil.c:811
void fe_sendint64(int64 i, char *buf)
Definition: streamutil.c:846
bool feTimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: streamutil.c:833
char * dbname
Definition: streamutil.c:51
PGconn * conn
Definition: streamutil.c:54
bool RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli, XLogRecPtr *startpos, char **db_name)
Definition: streamutil.c:403
char * dbuser
Definition: streamutil.c:49
unsigned short st_mode
Definition: win32_port.h:268
static StringInfo copybuf
Definition: tablesync.c:127
static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
Definition: walsender.c:1047
static void DropReplicationSlot(DropReplicationSlotCmd *cmd)
Definition: walsender.c:1247
#define fsync(fd)
Definition: win32_port.h:76
#define SIGHUP
Definition: win32_port.h:167
#define EINTR
Definition: win32_port.h:351
#define S_IRUSR
Definition: win32_port.h:288
#define fstat
Definition: win32_port.h:282
#define S_ISREG(m)
Definition: win32_port.h:327
#define S_IWUSR
Definition: win32_port.h:291
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28