1 /*-------------------------------------------------------------------------
3 * streamutil.c - utility functions for pg_basebackup, pg_receivewal and
6 * Author: Magnus Hagander <magnus@hagander.net>
8 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
11 * src/bin/pg_basebackup/streamutil.c
12 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
21 #include "receivelog.h"
22 #include "streamutil.h"
24 #include "access/xlog_internal.h"
25 #include "common/fe_memutils.h"
26 #include "datatype/timestamp.h"
27 #include "port/pg_bswap.h"
28 #include "pqexpbuffer.h"
30 #define ERRCODE_DUPLICATE_OBJECT "42710"
34 /* SHOW command for replication connection was introduced in version 10 */
35 #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
38 char *connection_string = NULL;
43 int dbgetpassword = 0; /* 0=auto, -1=never, 1=always */
44 static bool have_password = false;
45 static char password[100];
49 * Connect to the server. Returns a valid PGconn pointer if connected,
50 * or NULL on non-permanent error. On permanent error, the function will
51 * call exit(1) directly.
57 int argcount = 7; /* dbname, replication, fallback_app_name,
58 * host, user, port, password */
60 const char **keywords;
64 PQconninfoOption *conn_opts = NULL;
65 PQconninfoOption *conn_opt;
68 /* pg_recvlogical uses dbname only; others use connection_string only. */
69 Assert(dbname == NULL || connection_string == NULL);
72 * Merge the connection info inputs given in form of connection string,
73 * options and default values (dbname=replication, replication=true, etc.)
74 * Explicitly discard any dbname value in the connection string;
75 * otherwise, PQconnectdbParams() would interpret that value as being
76 * itself a connection string.
79 if (connection_string)
81 conn_opts = PQconninfoParse(connection_string, &err_msg);
82 if (conn_opts == NULL)
84 fprintf(stderr, "%s: %s", progname, err_msg);
88 for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
90 if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
91 strcmp(conn_opt->keyword, "dbname") != 0)
95 keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
96 values = pg_malloc0((argcount + 1) * sizeof(*values));
98 for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
100 if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
101 strcmp(conn_opt->keyword, "dbname") != 0)
103 keywords[i] = conn_opt->keyword;
104 values[i] = conn_opt->val;
111 keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
112 values = pg_malloc0((argcount + 1) * sizeof(*values));
115 keywords[i] = "dbname";
116 values[i] = dbname == NULL ? "replication" : dbname;
118 keywords[i] = "replication";
119 values[i] = dbname == NULL ? "true" : "database";
121 keywords[i] = "fallback_application_name";
122 values[i] = progname;
127 keywords[i] = "host";
133 keywords[i] = "user";
139 keywords[i] = "port";
144 /* If -W was given, force prompt for password, but only the first time */
145 need_password = (dbgetpassword == 1 && !have_password);
149 /* Get a new password if appropriate */
152 simple_prompt("Password: ", password, sizeof(password), false);
153 have_password = true;
154 need_password = false;
157 /* Use (or reuse, on a subsequent connection) password if we have it */
160 keywords[i] = "password";
161 values[i] = password;
169 tmpconn = PQconnectdbParams(keywords, values, true);
172 * If there is too little memory even to allocate the PGconn object
173 * and PQconnectdbParams returns NULL, we call exit(1) directly.
177 fprintf(stderr, _("%s: could not connect to server\n"),
182 /* If we need a password and -w wasn't given, loop back and get one */
183 if (PQstatus(tmpconn) == CONNECTION_BAD &&
184 PQconnectionNeedsPassword(tmpconn) &&
188 need_password = true;
191 while (need_password);
193 if (PQstatus(tmpconn) != CONNECTION_OK)
195 fprintf(stderr, _("%s: could not connect to server: %s"),
196 progname, PQerrorMessage(tmpconn));
201 PQconninfoFree(conn_opts);
209 PQconninfoFree(conn_opts);
212 * Ensure we have the same value of integer_datetimes (now always "on") as
213 * the server we are connecting to.
215 tmpparam = PQparameterStatus(tmpconn, "integer_datetimes");
219 _("%s: could not determine server setting for integer_datetimes\n"),
225 if (strcmp(tmpparam, "on") != 0)
228 _("%s: integer_datetimes compile flag does not match server\n"),
238 * From version 10, explicitly set wal segment size using SHOW wal_segment_size
239 * since ControlFile is not accessible here.
242 RetrieveWalSegSize(PGconn *conn)
249 /* check connection existence */
250 Assert(conn != NULL);
252 /* for previous versions set the default xlog seg size */
253 if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
255 WalSegSz = DEFAULT_XLOG_SEG_SIZE;
259 res = PQexec(conn, "SHOW wal_segment_size");
260 if (PQresultStatus(res) != PGRES_TUPLES_OK)
262 fprintf(stderr, _("%s: could not send replication command \"%s\": %s\n"),
263 progname, "SHOW wal_segment_size", PQerrorMessage(conn));
268 if (PQntuples(res) != 1 || PQnfields(res) < 1)
271 _("%s: could not fetch WAL segment size: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
272 progname, PQntuples(res), PQnfields(res), 1, 1);
278 /* fetch xlog value and unit from the result */
279 if (sscanf(PQgetvalue(res, 0, 0), "%d%s", &xlog_val, xlog_unit) != 2)
281 fprintf(stderr, _("%s: WAL segment size could not be parsed\n"),
286 /* set the multiplier based on unit to convert xlog_val to bytes */
287 if (strcmp(xlog_unit, "MB") == 0)
288 multiplier = 1024 * 1024;
289 else if (strcmp(xlog_unit, "GB") == 0)
290 multiplier = 1024 * 1024 * 1024;
292 /* convert and set WalSegSz */
293 WalSegSz = xlog_val * multiplier;
295 if (!IsValidWalSegSize(WalSegSz))
298 _("%s: WAL segment size must be a power of two between 1MB and 1GB, but the remote server reported a value of %d bytes\n"),
308 * Run IDENTIFY_SYSTEM through a given connection and give back to caller
309 * some result information if requested:
310 * - System identifier
311 * - Current timeline ID
312 * - Start LSN position
313 * - Database name (NULL in servers prior to 9.4)
316 RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
317 XLogRecPtr *startpos, char **db_name)
323 /* Check connection existence */
324 Assert(conn != NULL);
326 res = PQexec(conn, "IDENTIFY_SYSTEM");
327 if (PQresultStatus(res) != PGRES_TUPLES_OK)
329 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
330 progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn));
335 if (PQntuples(res) != 1 || PQnfields(res) < 3)
338 _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
339 progname, PQntuples(res), PQnfields(res), 1, 3);
345 /* Get system identifier */
347 *sysid = pg_strdup(PQgetvalue(res, 0, 0));
349 /* Get timeline ID to start streaming from */
350 if (starttli != NULL)
351 *starttli = atoi(PQgetvalue(res, 0, 1));
353 /* Get LSN start position if necessary */
354 if (startpos != NULL)
356 if (sscanf(PQgetvalue(res, 0, 2), "%X/%X", &hi, &lo) != 2)
359 _("%s: could not parse write-ahead log location \"%s\"\n"),
360 progname, PQgetvalue(res, 0, 2));
365 *startpos = ((uint64) hi) << 32 | lo;
368 /* Get database name, only available in 9.4 and newer versions */
372 if (PQserverVersion(conn) >= 90400)
374 if (PQnfields(res) < 4)
377 _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
378 progname, PQntuples(res), PQnfields(res), 1, 4);
383 if (!PQgetisnull(res, 0, 3))
384 *db_name = pg_strdup(PQgetvalue(res, 0, 3));
393 * Create a replication slot for the given connection. This function
394 * returns true in case of success.
397 CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
398 bool is_temporary, bool is_physical, bool reserve_wal,
404 query = createPQExpBuffer();
406 Assert((is_physical && plugin == NULL) ||
407 (!is_physical && plugin != NULL));
408 Assert(slot_name != NULL);
411 appendPQExpBuffer(query, "CREATE_REPLICATION_SLOT \"%s\"", slot_name);
413 appendPQExpBuffer(query, " TEMPORARY");
416 appendPQExpBuffer(query, " PHYSICAL");
418 appendPQExpBuffer(query, " RESERVE_WAL");
422 appendPQExpBuffer(query, " LOGICAL \"%s\"", plugin);
423 if (PQserverVersion(conn) >= 100000)
424 /* pg_recvlogical doesn't use an exported snapshot, so suppress */
425 appendPQExpBuffer(query, " NOEXPORT_SNAPSHOT");
428 res = PQexec(conn, query->data);
429 if (PQresultStatus(res) != PGRES_TUPLES_OK)
431 const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
433 if (slot_exists_ok &&
435 strcmp(sqlstate, ERRCODE_DUPLICATE_OBJECT) == 0)
437 destroyPQExpBuffer(query);
443 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
444 progname, query->data, PQerrorMessage(conn));
446 destroyPQExpBuffer(query);
452 if (PQntuples(res) != 1 || PQnfields(res) != 4)
455 _("%s: could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
457 PQntuples(res), PQnfields(res), 1, 4);
459 destroyPQExpBuffer(query);
464 destroyPQExpBuffer(query);
470 * Drop a replication slot for the given connection. This function
471 * returns true in case of success.
474 DropReplicationSlot(PGconn *conn, const char *slot_name)
479 Assert(slot_name != NULL);
481 query = createPQExpBuffer();
484 appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
486 res = PQexec(conn, query->data);
487 if (PQresultStatus(res) != PGRES_COMMAND_OK)
489 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
490 progname, query->data, PQerrorMessage(conn));
492 destroyPQExpBuffer(query);
497 if (PQntuples(res) != 0 || PQnfields(res) != 0)
500 _("%s: could not drop replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
502 PQntuples(res), PQnfields(res), 0, 0);
504 destroyPQExpBuffer(query);
509 destroyPQExpBuffer(query);
516 * Frontend version of GetCurrentTimestamp(), since we are not linked with
520 feGetCurrentTimestamp(void)
525 gettimeofday(&tp, NULL);
527 result = (TimestampTz) tp.tv_sec -
528 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
529 result = (result * USECS_PER_SEC) + tp.tv_usec;
535 * Frontend version of TimestampDifference(), since we are not linked with
539 feTimestampDifference(TimestampTz start_time, TimestampTz stop_time,
540 long *secs, int *microsecs)
542 TimestampTz diff = stop_time - start_time;
551 *secs = (long) (diff / USECS_PER_SEC);
552 *microsecs = (int) (diff % USECS_PER_SEC);
557 * Frontend version of TimestampDifferenceExceeds(), since we are not
558 * linked with backend code.
561 feTimestampDifferenceExceeds(TimestampTz start_time,
562 TimestampTz stop_time,
565 TimestampTz diff = stop_time - start_time;
567 return (diff >= msec * INT64CONST(1000));
571 * Converts an int64 to network byte order.
574 fe_sendint64(int64 i, char *buf)
576 uint64 n64 = pg_hton64(i);
578 memcpy(buf, &n64, sizeof(n64));
582 * Converts an int64 from network byte order to native format.
585 fe_recvint64(char *buf)
589 memcpy(&n64, buf, sizeof(n64));
591 return pg_ntoh64(n64);