pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Patch: Implement failover on libpq connect level.
165+ messages / 26 participants
[nested] [flat]

* Patch: Implement failover on libpq connect level.
@ 2015-10-14 10:41  Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 3 replies; 165+ messages in thread

From: Victor Wagner @ 2015-10-14 10:41 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 2015.08.18 at 07:18:50 +0300, Victor Wagner wrote:

> Rationale
> =========
> 
> Since introduction of the WAL-based replication into the PostgreSQL, it is
> possible to create high-availability and load-balancing clusters.
> 
> However, there is no support for failover in the client libraries. So, only
> way to provide transparent for client application failover is IP address
> migration. This approach has some limitation, i.e. it requires that
> master and backup servers reside in the same subnet or may not be
> feasible for other reasons.
> 
> Commercial RDBMS, such as Oracle, employ more flexible approach. They
> allow to specify multiple servers in the connect string, so if primary
> server is not available, client library tries to connect to other ones.
> 
> This approach allows to use geographically distributed failover clusters
> and also is a cheap way to implement load-balancing (which is not
> possible with IP address migration).
> 

Attached patch which implements client library failover and
loadbalancing as was described in the proposal
<20150818041850.GA5092@wagner.pp.ru>.

This patch implements following fuctionality:

1. It is allowed to specify several hosts in the connect string, either
in URL-style (separated by comma) or in param=value form (several host
parameters).

2. Each host parameter can be accompanied with port specifier separated
by colon. Port, specified such way takes precedence of port parameter or
default port for this particular host only.

3. There is hostorder parameter with two possible valies 'sequential'
and 'random' (default sequential). 'parallel' hostorder described in the
proposal is not yet implemented in this version of patch.

4. In the URL-style connect string parameter loadBalanceHosts=true is
considered equal to 'hostorder=random' for compatibility with jdbc.

5. Added new parameter readonly=boolean. If this parameter is false (the
default) upon successful connection check is performed that backend is
not in the recovery state. If so, connection is not considered usable
and next host is tried.

6. Added new parameter falover_timeout. If no usable host is found and
this parameter is specified, hosts are retried cyclically until this
timeout expires. It gives some time for claster management software to
promote one of standbys to master if master fails. By default there is
no retries.

Some implementation notes:

1. Field  pghost in the PGconn structure now stores comma separated list
of hosts, which is parsed in the connectDBStart. So, expected results of 
some tests in src/interfaces/libpq/test are changed. 

2. Url with colon  but no port number after the host no more considered
valid.

3. With hostorder=random we have to seed libc random number gernerator.
Some care was taken to not to lose entropy if generator was
initialized by app before connection, and to ensure different random
values if several connections are made from same application in one
second (even in single thread). RNG is seeded by xor of current time,
random value from this rng before seeding (if it was seeded earlier, it
keeps entropy) and address of the connection structure. May be it worth
effort adding thread id or pid, but there is no portable way to doing
so, so it would need testing on all supported platform.

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-1.patch (text/x-diff, 29.8K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 0ee018e..79a99ec 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3030fb..eecafb5 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -1,5 +1,7 @@ /*------------------------------------------------------------------------- * + UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); + * fe-connect.c * functions related to setting up a connection to the backend * @@ -114,6 +116,7 @@ static int ldapServiceLookup(const char *purl, PQconninfoOption *options, #define DefaultSSLMode "disable" #endif + /* ---------- * Definition of the conninfo parameters and their fallback resources. * @@ -299,7 +302,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"readonly", NULL, "0", NULL, + "Read only", "", 1, + offsetof(struct pg_conn, read_only)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timoeut", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -380,6 +392,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -1384,11 +1397,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1430,21 +1449,73 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(conn->pghostaddr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + nodes[nodecount].port = malloc(q - r ); + strncpy(nodes[nodecount].port, r + 1 , q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + nodes[nodecount].host = malloc(r - p + 1); + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1454,33 +1525,73 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes->port); + free(nodes); goto connect_errReturn; } + nodes->port = strdup(portstr); #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + /* add this host addrs to addrs */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1493,12 +1604,23 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; - + if (conn->failover_timeout) { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } else { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), * so that it can easily be re-executed if needed again during the @@ -1597,6 +1719,76 @@ connectDBComplete(PGconn *conn) } } +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "sequential") == 0) + { + if (conn->addr_cur == NULL) + { + conn->addr_cur = conn->addrlist; + return 1; + } + else + { + conn->addr_cur = conn->addr_cur->ai_next; + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + /* If failover timeout is set, retry list of hosts from + * the beginning */ + conn->addr_cur = conn->addrlist; + } + return (conn->addr_cur != NULL); + } + } + else if (strcmp(conn->hostorder, "random") == 0) + { + struct addrinfo *choice = NULL, + *current = conn->addrlist; + int count = 0; + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + while (current != NULL) + { + if (current == conn->addr_cur) + { + current = current->ai_next; + } + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + } + current = current->ai_next; + } + if (choice == NULL) + return 0; + conn->addr_cur = choice; + return 1; + } + else if (strcmp(conn->hostorder, "parallel") == 0) + { + /* Not implemented yet */ + return 0; + } + return 0; + +} + /* ---------------- * PQconnectPoll * @@ -1674,7 +1866,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1712,9 +1905,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1733,7 +1925,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1743,7 +1935,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1754,7 +1946,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1801,7 +1993,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1892,7 +2084,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1938,9 +2130,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2608,8 +2799,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2639,9 +2831,81 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connectionV is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + */ + if (conn->read_only && conn->read_only[0] > '0') + { + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + if (PQresultStatus(res) != PGRES_TUPLES_OK) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + value = PQgetvalue(res, 0, 0); + if (strcmp(value, "true") == 0) + { + conn->status = CONNECTION_NEEDED; + } + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + closePGconn(conn); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -4798,87 +5062,118 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') - { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + host = p; + if (*p==':') { + int portnum; + char *portstr; + *(p++)='\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + prevchar = *p; + *p='\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + } else { + do { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; - } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } - - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* + * "p" has been incremented past optional URI credential information + * at this point and now points at the "netloc" part of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; + /* + * The address may be followed by a port specifier, a comma or a + * slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5008,6 +5303,16 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } /* * Store the value if the corresponding option exists; ignore @@ -5222,7 +5527,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 828c533..20899bc 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 04d056e..164c858 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,10 +386,12 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ - + /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ int be_key; /* key of backend --- needed for cancels */ diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local)
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-14 12:47  Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 1 reply; 165+ messages in thread

From: Shulgin, Oleksandr @ 2015-10-14 12:47 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@postgresql.org>

On Wed, Oct 14, 2015 at 12:41 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:

> On 2015.08.18 at 07:18:50 +0300, Victor Wagner wrote:
>
> > Rationale
> > =========
> >
> > Since introduction of the WAL-based replication into the PostgreSQL, it
> is
> > possible to create high-availability and load-balancing clusters.
> >
> > However, there is no support for failover in the client libraries. So,
> only
> > way to provide transparent for client application failover is IP address
> > migration. This approach has some limitation, i.e. it requires that
> > master and backup servers reside in the same subnet or may not be
> > feasible for other reasons.
> >
> > Commercial RDBMS, such as Oracle, employ more flexible approach. They
> > allow to specify multiple servers in the connect string, so if primary
> > server is not available, client library tries to connect to other ones.
> >
> > This approach allows to use geographically distributed failover clusters
> > and also is a cheap way to implement load-balancing (which is not
> > possible with IP address migration).
> >
>
> Attached patch which implements client library failover and
> loadbalancing as was described in the proposal
> <20150818041850.GA5092@wagner.pp.ru>.
>
> This patch implements following fuctionality:
>
> 1. It is allowed to specify several hosts in the connect string, either
> in URL-style (separated by comma) or in param=value form (several host
> parameters).
>

So what exactly would happen with this command: PGHOST=host1 psql -h host2

Or this one: PGHOST=host1 psql host=host2

What about service files?

2. Each host parameter can be accompanied with port specifier separated
> by colon. Port, specified such way takes precedence of port parameter or
> default port for this particular host only.
>
> 3. There is hostorder parameter with two possible valies 'sequential'
> and 'random' (default sequential). 'parallel' hostorder described in the
> proposal is not yet implemented in this version of patch.
>
> 4. In the URL-style connect string parameter loadBalanceHosts=true is
> considered equal to 'hostorder=random' for compatibility with jdbc.
>
> 5. Added new parameter readonly=boolean. If this parameter is false (the
> default) upon successful connection check is performed that backend is
> not in the recovery state. If so, connection is not considered usable
> and next host is tried.
>
> 6. Added new parameter falover_timeout. If no usable host is found and
> this parameter is specified, hosts are retried cyclically until this
> timeout expires. It gives some time for claster management software to
> promote one of standbys to master if master fails. By default there is
> no retries.
>
> Some implementation notes:
>
> 1. Field  pghost in the PGconn structure now stores comma separated list
> of hosts, which is parsed in the connectDBStart. So, expected results of
> some tests in src/interfaces/libpq/test are changed.
>

 trying postgresql://[::1]:12345/db
-dbname='db' host='::1' port='12345' (inet)
+dbname='db' host='[::1]:12345' (inet)

Such a change doesn't look really nice to me.


> 2. Url with colon  but no port number after the host no more considered
> valid.
>

We could live with that, but is there a good reason for backward
compatibility break in this case?

--
Alex

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-15 07:07  Victor Wagner <vitus@wagner.pp.ru>
  parent: Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
  0 siblings, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2015-10-15 07:07 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 2015.10.14 at 14:47:46 +0200, Shulgin, Oleksandr wrote:

> 
> So what exactly would happen with this command: PGHOST=host1 psql -h host2
> 
> Or this one: PGHOST=host1 psql host=host2

The right thing - value of the PGHOST environment variable is ignored,
and explicitely specified host is used.

> What about service files?

Oops, I've missed something here. Multiple host lines in the service
file do not produce list of alternate hosts.

I'll address this case in the next version of patch.

However, comma-separated list of host in the one host string in the
service file works.


> 
>  trying postgresql://[::1]:12345/db
> -dbname='db' host='::1' port='12345' (inet)
> +dbname='db' host='[::1]:12345' (inet)
> 
> Such a change doesn't look really nice to me.

Really, any alternative would be worse. Only alternative I can imagine
is to replace pghost field in the PGConn structure by array or linked
list of structures with host and port fields.

Now I decided to keep such array local to connectDBStart function, and
store list of host-port pair as string. 

It takes some CPU cycles to reparse this list each time when
reconnection is needed, but this is negligible compared with DNS
resolution of each host name. And we cannot avoid repeated DNS
resolution, because we have to take into account possibility of
DNS-based failover.


> > 2. Url with colon  but no port number after the host no more considered
> > valid.
> >
> 
> We could live with that, but is there a good reason for backward
> compatibility break in this case?

Because we can. Really, I don't see any useful semantic of host with
colon at the end. Null host name with colon and port have useful
semantic (if there is just one host in the  connect string), so it kept
as it was.

In the old version of connection-string parsing code stripping lone
colon of the host name was done by generic code (because port number
have gone to another variable anyway). Now handling of lone
colon is special case, because we just check syntax of host-port pair
list. 

And I have to choose how to handle it - either complain or silently
strip it away. Complaining was similier. We compute port number and
check if it is between 1 and 65535. Zero-length port number is not
integer between 1 and 65535.


> --
> Alex

-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-15 09:13  Craig Ringer <craig@2ndquadrant.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2015-10-15 09:13 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@postgresql.org>

On 14 October 2015 at 18:41, Victor Wagner <vitus@wagner.pp.ru> wrote:

> 5. Added new parameter readonly=boolean. If this parameter is false (the
> default) upon successful connection check is performed that backend is
> not in the recovery state. If so, connection is not considered usable
> and next host is tried.

What constitutes "failed" as far as this is concerned?

Like the PgJDBC approach I wonder how much this'll handle in practice
and how it'll go with less clear-cut failures like disk-full on a
replica that's a member of the failover pool, long delays before
no-route-to-host errors, dns problems, etc.

Had any chance to simulate network failures?

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-15 09:43  Victor Wagner <vitus@wagner.pp.ru>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2015-10-15 09:43 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 2015.10.15 at 17:13:46 +0800, Craig Ringer wrote:

> On 14 October 2015 at 18:41, Victor Wagner <vitus@wagner.pp.ru> wrote:
> 
> > 5. Added new parameter readonly=boolean. If this parameter is false (the
> > default) upon successful connection check is performed that backend is
> > not in the recovery state. If so, connection is not considered usable
> > and next host is tried.
> 
> What constitutes "failed" as far as this is concerned?

failed means "select pg_is_in_recovery() returns true". 
The only reason of adding this parameter is to state that we 
can use  connection to warm-backup slave (or if we cannot).

> Like the PgJDBC approach I wonder how much this'll handle in practice
> and how it'll go with less clear-cut failures like disk-full on a
> replica that's a member of the failover pool, long delays before
> no-route-to-host errors, dns problems, etc.

Really I don't think that disk-full and other such node errors are
problems of client library. It is cluster management software which
should check for these errors and shut down erroneous nodes or at least
disable their listening for connection.

As for long-timeouts on network failures, they can be handled by
existing connect_timeout parameter. 

May be it is worth effort to rewrite this parameter handling. Now it
only used in blocking functions which call connectDBComplete
(PQconnectdb[Params], PQreset and PQsetdbLogin). May be it should be hidden into
PQconnectPoll state machine, so event-driven applications could get its
handling for free.

Really, my initial proposal included hostorder=parallel especially for
this situation. But I've decided not to implement it right now, because
it requires changes in the libpq public API.
 
> Had any chance to simulate network failures?

Testing failover code is really tricky thing. All testing I've done yet
was in the mode "Shudown one of the nodes and see what happens".
It is not too hard to simulate network failures using iptables, but
requires considerable planning of the test scenario.


-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-26 20:25  Peter Eisentraut <peter_e@gmx.net>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 3 replies; 165+ messages in thread

From: Peter Eisentraut @ 2015-10-26 20:25 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 10/14/15 6:41 AM, Victor Wagner wrote:
> 1. It is allowed to specify several hosts in the connect string, either
> in URL-style (separated by comma) or in param=value form (several host
> parameters).

I'm not fond of having URLs that are not valid URLs according to the
applicable standards.  Because then they can't be parsed or composed by
standard libraries.

Also, this assumes that all the components other than host and port are
the same.  Earlier there was a discussion about why the ports would ever
need to be different.  Well, why can't the database names be different?
 I could have use for that.

I think you should just accept multiple URLs.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-26 21:02  Christopher Browne <cbbrowne@gmail.com>
  parent: Peter Eisentraut <peter_e@gmx.net>
  2 siblings, 1 reply; 165+ messages in thread

From: Christopher Browne @ 2015-10-26 21:02 UTC (permalink / raw)
  To: Peter Eisentraut <peter_e@gmx.net>; +Cc: PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On 26 October 2015 at 16:25, Peter Eisentraut <peter_e@gmx.net> wrote:

> On 10/14/15 6:41 AM, Victor Wagner wrote:
> > 1. It is allowed to specify several hosts in the connect string, either
> > in URL-style (separated by comma) or in param=value form (several host
> > parameters).
>
> I'm not fond of having URLs that are not valid URLs according to the
> applicable standards.  Because then they can't be parsed or composed by
> standard libraries.
>
> Also, this assumes that all the components other than host and port are
> the same.  Earlier there was a discussion about why the ports would ever
> need to be different.  Well, why can't the database names be different?
>  I could have use for that.
>
> I think you should just accept multiple URLs.
>

I'd give a "+1" on this...

As an area of new behaviour, I don't see a big problem with declining to
support every wee bit of libpq configuration, and instead requiring the
use of URLs.

Trying to put "multiplicities" into each parameter (and then considering
it at the pg_service level, too) is WAY more complicated, and for a
feature where it seems to me that it is pretty reasonable to have a
series of fully qualified URLs.

Specifying several URLs should be easier to understand, easier to
test, easier to code, and easier to keep from blowing up badly.

I'll observe that this is the way that OpenLDAP supports specifying
multiple clients, so this technique is familiar in other contexts
where people are trying to accomplish the same kind of thing.
Sample docs, perhaps not authoritative, but useful enough...
<http://manpages.courier-mta.org/htmlman5/ldap.conf.5.html;
-- 
When confronted by a difficult problem, solve it by reducing it to the
question, "How would the Lone Ranger handle this?"

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-27 08:42  Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
  parent: Christopher Browne <cbbrowne@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Shulgin, Oleksandr @ 2015-10-27 08:42 UTC (permalink / raw)
  To: Christopher Browne <cbbrowne@gmail.com>; +Cc: Peter Eisentraut <peter_e@gmx.net>; PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On Mon, Oct 26, 2015 at 10:02 PM, Christopher Browne <cbbrowne@gmail.com>
wrote:

>
> On 26 October 2015 at 16:25, Peter Eisentraut <peter_e@gmx.net> wrote:
>
>> On 10/14/15 6:41 AM, Victor Wagner wrote:
>> > 1. It is allowed to specify several hosts in the connect string, either
>> > in URL-style (separated by comma) or in param=value form (several host
>> > parameters).
>>
>> I'm not fond of having URLs that are not valid URLs according to the
>> applicable standards.  Because then they can't be parsed or composed by
>> standard libraries.
>>
>> Also, this assumes that all the components other than host and port are
>> the same.  Earlier there was a discussion about why the ports would ever
>> need to be different.  Well, why can't the database names be different?
>>  I could have use for that.
>>
>> I think you should just accept multiple URLs.
>>
>
> I'd give a "+1" on this...
>
> As an area of new behaviour, I don't see a big problem with declining to
> support every wee bit of libpq configuration, and instead requiring the
> use of URLs.
>
> Trying to put "multiplicities" into each parameter (and then considering
> it at the pg_service level, too) is WAY more complicated, and for a
> feature where it seems to me that it is pretty reasonable to have a
> series of fully qualified URLs.
>
> Specifying several URLs should be easier to understand, easier to
> test, easier to code, and easier to keep from blowing up badly.
>

Setting aside all other concerns, have a +1 from me on that too.

--
Alex

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-27 17:35  Josh Berkus <josh@agliodbs.com>
  parent: Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
  0 siblings, 0 replies; 165+ messages in thread

From: Josh Berkus @ 2015-10-27 17:35 UTC (permalink / raw)
  To: Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>; Christopher Browne <cbbrowne@gmail.com>; +Cc: Peter Eisentraut <peter_e@gmx.net>; PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On 10/27/2015 01:42 AM, Shulgin, Oleksandr wrote:
> On Mon, Oct 26, 2015 at 10:02 PM, Christopher Browne <cbbrowne@gmail.com
> <mailto:cbbrowne@gmail.com>> wrote:
> 
> 
>     On 26 October 2015 at 16:25, Peter Eisentraut <peter_e@gmx.net
>     <mailto:peter_e@gmx.net>> wrote:
> 
>         On 10/14/15 6:41 AM, Victor Wagner wrote:
>         > 1. It is allowed to specify several hosts in the connect string, either
>         > in URL-style (separated by comma) or in param=value form (several host
>         > parameters).
> 
>         I'm not fond of having URLs that are not valid URLs according to the
>         applicable standards.  Because then they can't be parsed or
>         composed by
>         standard libraries.
> 
>         Also, this assumes that all the components other than host and
>         port are
>         the same.  Earlier there was a discussion about why the ports
>         would ever
>         need to be different.  Well, why can't the database names be
>         different?
>          I could have use for that.
> 
>         I think you should just accept multiple URLs.
> 
> 
>     I'd give a "+1" on this...
> 
>     As an area of new behaviour, I don't see a big problem with declining to
>     support every wee bit of libpq configuration, and instead requiring the
>     use of URLs.
> 
>     Trying to put "multiplicities" into each parameter (and then considering
>     it at the pg_service level, too) is WAY more complicated, and for a
>     feature where it seems to me that it is pretty reasonable to have a
>     series of fully qualified URLs.
> 
>     Specifying several URLs should be easier to understand, easier to
>     test, easier to code, and easier to keep from blowing up badly.
> 
> 
> Setting aside all other concerns, have a +1 from me on that too.

I'm good with this.  +1


-- 
Josh Berkus
PostgreSQL Experts Inc.
http://pgexperts.com


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-28 08:18  Victor Wagner <vitus@wagner.pp.ru>
  parent: Peter Eisentraut <peter_e@gmx.net>
  2 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2015-10-28 08:18 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 26 Oct 2015 16:25:57 -0400
Peter Eisentraut <peter_e@gmx.net> wrote:

> Also, this assumes that all the components other than host and port
> are the same.  Earlier there was a discussion about why the ports
> would ever need to be different.  Well, why can't the database names
> be different? I could have use for that.

Because of way postgresql replication is implemented.

This multihost feature is for clusters. Either for automatic switch
from one cluster node to another when master node fails and one of the
standbys get promoted to master, or for load balancing between hot
standby nodes.

Postgresql allows different replicas listen on different ports, because
each replica has its own postgresql conf, but repication works on the
node level, not on the database level, so all the databases from master
node would be replicated with their original names.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-29 19:29  Peter Eisentraut <peter_e@gmx.net>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Peter Eisentraut @ 2015-10-29 19:29 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org

On 10/28/15 4:18 AM, Victor Wagner wrote:
> On Mon, 26 Oct 2015 16:25:57 -0400
> Peter Eisentraut <peter_e@gmx.net> wrote:
> 
>> Also, this assumes that all the components other than host and port
>> are the same.  Earlier there was a discussion about why the ports
>> would ever need to be different.  Well, why can't the database names
>> be different? I could have use for that.
> 
> Because of way postgresql replication is implemented.

There are multiple types of PostgreSQL replication, and there will be
others in the future.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-30 13:26  Robert Haas <robertmhaas@gmail.com>
  parent: Peter Eisentraut <peter_e@gmx.net>
  0 siblings, 3 replies; 165+ messages in thread

From: Robert Haas @ 2015-10-30 13:26 UTC (permalink / raw)
  To: Peter Eisentraut <peter_e@gmx.net>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Oct 29, 2015 at 8:29 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> On 10/28/15 4:18 AM, Victor Wagner wrote:
>> On Mon, 26 Oct 2015 16:25:57 -0400
>> Peter Eisentraut <peter_e@gmx.net> wrote:
>>
>>> Also, this assumes that all the components other than host and port
>>> are the same.  Earlier there was a discussion about why the ports
>>> would ever need to be different.  Well, why can't the database names
>>> be different? I could have use for that.
>>
>> Because of way postgresql replication is implemented.
>
> There are multiple types of PostgreSQL replication, and there will be
> others in the future.

That's true, but doesn't allowing every parameter to be multiply
specified greatly increase the implementation complexity for a pretty
marginal benefit?  I think host and IP would hit 98% of the use cases
here.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-30 14:09  Victor Wagner <vitus@wagner.pp.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2015-10-30 14:09 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Fri, 30 Oct 2015 14:26:45 +0100
Robert Haas <robertmhaas@gmail.com> wrote:

> On Thu, Oct 29, 2015 at 8:29 PM, Peter Eisentraut <peter_e@gmx.net>
> wrote:

> 
> That's true, but doesn't allowing every parameter to be multiply
> specified greatly increase the implementation complexity for a pretty
> marginal benefit?  I think host and IP would hit 98% of the use cases
> here.

As far as I can tell from the experience of writing this patch, it
would greatly increase complexity.

If there should be only need to have multiple hosts, I could almost
completely incapsulate changes into DNS resolving code (which already
allows to handle several addresses). Need to support different port for
each host already required change of internal storage, and as a
consequence changes in the regression test suite
(src/interfaces/libpq/test/regress.out)

But both host and port are used in the same place - in the connect
system call. If we add possibility to different values per host for some
parameter, such as database name, which should be used significantly
later, i.e. during sending of first protocol message, size of patch
would grow may be twice.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-30 15:29  Christopher Browne <cbbrowne@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 2 replies; 165+ messages in thread

From: Christopher Browne @ 2015-10-30 15:29 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On 30 October 2015 at 09:26, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Thu, Oct 29, 2015 at 8:29 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> > On 10/28/15 4:18 AM, Victor Wagner wrote:
> >> On Mon, 26 Oct 2015 16:25:57 -0400
> >> Peter Eisentraut <peter_e@gmx.net> wrote:
> >>
> >>> Also, this assumes that all the components other than host and port
> >>> are the same.  Earlier there was a discussion about why the ports
> >>> would ever need to be different.  Well, why can't the database names
> >>> be different? I could have use for that.
> >>
> >> Because of way postgresql replication is implemented.
> >
> > There are multiple types of PostgreSQL replication, and there will be
> > others in the future.
>
> That's true, but doesn't allowing every parameter to be multiply
> specified greatly increase the implementation complexity for a pretty
> marginal benefit?  I think host and IP would hit 98% of the use cases
> here.

I think it makes the feature WORSE.  I am getting more and more convinced
that the Correct Solution is for this feature to be handled by submitting
multiple URIs, and my argument isn't even based on any aspects of
implementation complexity.

Take as example the case where I have two database servers I want to
be considered.

a) Database with URI
   postgresql://cbbrowne@server-a.example.info:5432/my-first-database

b) Database with URL
   postgresql://robert@server-b.example.info:7032/my-second-database

With all the "per-variable multiplicities", this would turn into a
combinatorial explosion of combinations, some 2^4, or 16 possible servers,
some of which likely don't exist, and others of which aren't proper (e.g. -
trying to connect to database a) using robert's credentials).

Possibly some of those combinations are outright improper.

I'm not going to claim it's terribly wise to be doing the cross-credential
bit; I'd think it likely to be rather dumb for the application to use one
user when connecting to one database and another when connecting to
another.  But the notion of it being nondeterministic is just awful.

I head back to... "the way OpenLDAP does this"...
  They let you specify multiple LDAP servers...
    ldap://server1.example.info:389 ldap://server2.example.info:389
where URIs are separated by whitespace.

Seems like Best Goodness for Postgres to do something analogous...
   postgresql://cbbrowne@server-a.example.info:5432/my-first-database
postgresql://robert@server-b.example.info:7032/my-second-database

Is it a bit long?  Sure.  But it is unambiguous, and requires *only*
whitespace parsing to separate the URIs.  I'd think it fine for Postgres to
support this via multiple "-d" options; that would be about as good.

That can cover 100% of cases, and I don't see it needing to interact
specially with odd bits such as "was that a replication slot?"  You can
always choose to shoot yourself in the foot, but this doesn't spin the
roulette for you...
--
When confronted by a difficult problem, solve it by reducing it to the
question, "How would the Lone Ranger handle this?"

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-30 16:23  David Fetter <david@fetter.org>
  parent: Christopher Browne <cbbrowne@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: David Fetter @ 2015-10-30 16:23 UTC (permalink / raw)
  To: Christopher Browne <cbbrowne@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On Fri, Oct 30, 2015 at 11:29:09AM -0400, Christopher Browne wrote:
> On 30 October 2015 at 09:26, Robert Haas <robertmhaas@gmail.com> wrote:
> >
> > On Thu, Oct 29, 2015 at 8:29 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> > > On 10/28/15 4:18 AM, Victor Wagner wrote:
> > >> On Mon, 26 Oct 2015 16:25:57 -0400
> > >> Peter Eisentraut <peter_e@gmx.net> wrote:
> > >>
> > >>> Also, this assumes that all the components other than host and port
> > >>> are the same.  Earlier there was a discussion about why the ports
> > >>> would ever need to be different.  Well, why can't the database names
> > >>> be different? I could have use for that.
> > >>
> > >> Because of way postgresql replication is implemented.
> > >
> > > There are multiple types of PostgreSQL replication, and there will be
> > > others in the future.
> >
> > That's true, but doesn't allowing every parameter to be multiply
> > specified greatly increase the implementation complexity for a pretty
> > marginal benefit?  I think host and IP would hit 98% of the use cases
> > here.
> 
> I think it makes the feature WORSE.  I am getting more and more convinced
> that the Correct Solution is for this feature to be handled by submitting
> multiple URIs, and my argument isn't even based on any aspects of
> implementation complexity.
> 
> Take as example the case where I have two database servers I want to
> be considered.
> 
> a) Database with URI
>    postgresql://cbbrowne@server-a.example.info:5432/my-first-database
> 
> b) Database with URL
>    postgresql://robert@server-b.example.info:7032/my-second-database
> 
> With all the "per-variable multiplicities", this would turn into a
> combinatorial explosion of combinations, some 2^4, or 16 possible servers,
> some of which likely don't exist, and others of which aren't proper (e.g. -
> trying to connect to database a) using robert's credentials).
> 
> Possibly some of those combinations are outright improper.

Let's say that the chances of their all both existing and being proper
are close enough to zero not to matter.

> Seems like Best Goodness for Postgres to do something analogous...
>    postgresql://cbbrowne@server-a.example.info:5432/my-first-database
> postgresql://robert@server-b.example.info:7032/my-second-database

Yes.

> Is it a bit long?  Sure.  But it is unambiguous, and requires *only*
> whitespace parsing to separate the URIs.  I'd think it fine for Postgres to
> support this via multiple "-d" options; that would be about as good.

Indeed.  Is there any risk of losing ordering information in the
standard command line processing libraries?

> That can cover 100% of cases, and I don't see it needing to interact
> specially with odd bits such as "was that a replication slot?"  You can
> always choose to shoot yourself in the foot, but this doesn't spin the
> roulette for you...

An evocative image, if not a pretty one.

Cheers,
David.
-- 
David Fetter <david@fetter.org> http://fetter.org/
Phone: +1 415 235 3778  AIM: dfetter666  Yahoo!: dfetter
Skype: davidfetter      XMPP: david.fetter@gmail.com

Remember to vote!
Consider donating to Postgres: http://www.postgresql.org/about/donate


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-10-30 17:21  Josh Berkus <josh@agliodbs.com>
  parent: Christopher Browne <cbbrowne@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Josh Berkus @ 2015-10-30 17:21 UTC (permalink / raw)
  To: Christopher Browne <cbbrowne@gmail.com>; Robert Haas <robertmhaas@gmail.com>; PostgreSQL Mailing Lists <pgsql-hackers@postgresql.org>

On 10/30/2015 08:29 AM, Christopher Browne wrote:
> I think it makes the feature WORSE.  I am getting more and more convinced
> that the Correct Solution is for this feature to be handled by submitting
> multiple URIs, and my argument isn't even based on any aspects of
> implementation complexity.

+1

-- 
Josh Berkus
PostgreSQL Experts Inc.
http://pgexperts.com


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-02 17:15  Peter Eisentraut <peter_e@gmx.net>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 2 replies; 165+ messages in thread

From: Peter Eisentraut @ 2015-11-02 17:15 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 10/30/15 9:26 AM, Robert Haas wrote:
> That's true, but doesn't allowing every parameter to be multiply
> specified greatly increase the implementation complexity for a pretty
> marginal benefit?

Well, the way I would have approached is that after all the parsing you
end up with a list of PQconninfoOption arrays and you you loop over that
list and call connectDBStart() until you have a connection that
satisfies you.

I see that the patch doesn't do that and it looks quite messy as a result.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-03 15:24  Robert Haas <robertmhaas@gmail.com>
  parent: Peter Eisentraut <peter_e@gmx.net>
  1 sibling, 0 replies; 165+ messages in thread

From: Robert Haas @ 2015-11-03 15:24 UTC (permalink / raw)
  To: Peter Eisentraut <peter_e@gmx.net>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Nov 2, 2015 at 12:15 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> On 10/30/15 9:26 AM, Robert Haas wrote:
>> That's true, but doesn't allowing every parameter to be multiply
>> specified greatly increase the implementation complexity for a pretty
>> marginal benefit?
>
> Well, the way I would have approached is that after all the parsing you
> end up with a list of PQconninfoOption arrays and you you loop over that
> list and call connectDBStart() until you have a connection that
> satisfies you.
>
> I see that the patch doesn't do that and it looks quite messy as a result.

Hmm, I see.  That approach certainly seems worth considering.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-05 15:12  Victor Wagner <vitus@wagner.pp.ru>
  parent: Peter Eisentraut <peter_e@gmx.net>
  1 sibling, 2 replies; 165+ messages in thread

From: Victor Wagner @ 2015-11-05 15:12 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 2015.11.02 at 12:15:48 -0500, Peter Eisentraut wrote:

>> That's true, but doesn't allowing every parameter to be multiply
>> specified greatly increase the implementation complexity for a pretty
>> marginal benefit?  

>Well, the way I would have approached is that after all the parsing you
>end up with a list of PQconninfoOption arrays and you you loop over that
>list and call connectDBStart() until you have a connection that
>satisfies you.

>I see that the patch doesn't do that and it looks quite messy as a
>result.

There are some drawbacks with this approach

1. You are suggesting usage of two nested loops, instead of one straight
loop - outer loop over the URLs in the connect string, inner loop over
the IP addresses each URL resolves into. (This inner loop already
presents there for several versions of the postgres).

2. You are suggesting that it should be possible to specify all options 
separately for each of the fallback hosts. 

But some options control how
next host should be choosen (i.e. use random order for load-balancing
or sequential order for high availability), so they should be specified
only once per connect string.

Some other options are
connection level rather then node-level (i.e. if you are using
replication mode of the connection, there is no sense to specify it for
one host and not specify for other). These options should be better
specified such way, that it would be not possible to use conflicting
values.

Third category of options are specified per-cluster much more often
than per node. But are quite often changed from compiled in default.
Typically there are authentication credentials (even you use
trigger-based replication, user information would probably be
replicated), database name (if you use WAL-level replication), client
encoding (which depends on more on the client than on server), etc.

It would be pain if we would need specify them for each host separately.
Syntax, implemented in the my patch allows even to specify
nonstandard-port once for all hosts (using port= parameter in the query
string) and override it for particular host in the list using colon
syntax.

3. Last, but not least. There is more than one postgresql client
implementation. Apart of libpq we have jdbc, native GO language client
etc. And I think that maintaining compatibility of the connect string
between them is good thing. So, I've modelled syntax of multihost
feature in the libpq URL-style syntax after jdbc syntax.
-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-06 05:34  Robert Haas <robertmhaas@gmail.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 1 reply; 165+ messages in thread

From: Robert Haas @ 2015-11-06 05:34 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 5, 2015 at 10:12 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> There are some drawbacks with this approach
>
> 1. You are suggesting usage of two nested loops, instead of one straight
> loop - outer loop over the URLs in the connect string, inner loop over
> the IP addresses each URL resolves into. (This inner loop already
> presents there for several versions of the postgres).

This isn't really a problem.

> 2. You are suggesting that it should be possible to specify all options
> separately for each of the fallback hosts.
>
> But some options control how
> next host should be choosen (i.e. use random order for load-balancing
> or sequential order for high availability), so they should be specified
> only once per connect string.

But this seems like a point worthy of consideration.

> Third category of options are specified per-cluster much more often
> than per node. But are quite often changed from compiled in default.
> Typically there are authentication credentials (even you use
> trigger-based replication, user information would probably be
> replicated), database name (if you use WAL-level replication), client
> encoding (which depends on more on the client than on server), etc.
>
> It would be pain if we would need specify them for each host separately.
> Syntax, implemented in the my patch allows even to specify
> nonstandard-port once for all hosts (using port= parameter in the query
> string) and override it for particular host in the list using colon
> syntax.

This, too.

> 3. Last, but not least. There is more than one postgresql client
> implementation. Apart of libpq we have jdbc, native GO language client
> etc. And I think that maintaining compatibility of the connect string
> between them is good thing. So, I've modelled syntax of multihost
> feature in the libpq URL-style syntax after jdbc syntax.

Also this.

I'm not sure what the right decision is here - I can see both sides of
it to some degree.  But I think your points deserve to be taken
seriously.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-06 05:43  Craig Ringer <craig@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2015-11-06 05:43 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 6 November 2015 at 13:34, Robert Haas <robertmhaas@gmail.com> wrote:

>> But some options control how
>> next host should be choosen (i.e. use random order for load-balancing
>> or sequential order for high availability), so they should be specified
>> only once per connect string.
>
> But this seems like a point worthy of consideration.

This makes me think that trying to wedge this into the current API
using a funky connection string format might be a mistake.

Lots of these issues would go away if you could provide more than just
a connstring.

>> Third category of options are specified per-cluster much more often
>> than per node. But are quite often changed from compiled in default.
>
> This, too.

Like this. If you have a global set of connection options, then
per-connection options, it's a lot simpler.

I guess that can be hacked in with a more dramatic change in the
connstring format, otherwise, incorporating subsections or something.
I'm not keen on doing anything like that, but there are all sorts of
options...

"global:[user=fred port=5432] host1:[host=somehost user=user1]
host2:[host=localhost]"


(puts head in brown paper bag)

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-06 15:38  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Alvaro Herrera @ 2015-11-06 15:38 UTC (permalink / raw)
  To: Craig Ringer <craig@2ndquadrant.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

Craig Ringer wrote:
> On 6 November 2015 at 13:34, Robert Haas <robertmhaas@gmail.com> wrote:
> 
> >> But some options control how
> >> next host should be choosen (i.e. use random order for load-balancing
> >> or sequential order for high availability), so they should be specified
> >> only once per connect string.
> >
> > But this seems like a point worthy of consideration.
> 
> This makes me think that trying to wedge this into the current API
> using a funky connection string format might be a mistake.
> 
> Lots of these issues would go away if you could provide more than just
> a connstring.

Yes, I agree.  I wonder if the failover aspect couldn't be better
covered by something more powerful than a single URI, such as the
service file format.  Maybe just allow the contents of a service file to
be passed as a "connection string", so that the application/environment
can continue to maintain the connection info as a string somewhere
instead of having to have an actual file.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-06 20:59  Robert Haas <robertmhaas@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2015-11-06 20:59 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Craig Ringer <craig@2ndquadrant.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Fri, Nov 6, 2015 at 10:38 AM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Craig Ringer wrote:
>> On 6 November 2015 at 13:34, Robert Haas <robertmhaas@gmail.com> wrote:
>>
>> >> But some options control how
>> >> next host should be choosen (i.e. use random order for load-balancing
>> >> or sequential order for high availability), so they should be specified
>> >> only once per connect string.
>> >
>> > But this seems like a point worthy of consideration.
>>
>> This makes me think that trying to wedge this into the current API
>> using a funky connection string format might be a mistake.
>>
>> Lots of these issues would go away if you could provide more than just
>> a connstring.
>
> Yes, I agree.  I wonder if the failover aspect couldn't be better
> covered by something more powerful than a single URI, such as the
> service file format.  Maybe just allow the contents of a service file to
> be passed as a "connection string", so that the application/environment
> can continue to maintain the connection info as a string somewhere
> instead of having to have an actual file.

This gets pretty far from the concept of a connection string, which is
supposed to be a sort of universal format for telling anything
PostgreSQL how to find the database server.  For example, psql accepts
a connection string, but you wouldn't want to have to pass the entire
contents of a file, newlines and all, as a command-line argument.
Now, we could design some kind of new connection string format that
would work, like:

psql 'alternatives failovertime=1 (host=192.168.10.49 user=rhaas)
(host=192.168.10.52 user=bob)'

There are a couple of problems with this.  One, it can't be parsed
anything like a normal connection string.  Lots of software will have
to be rewritten to use whatever parser we come up with for the new
format.  Two, it's nothing like the existing JDBC syntax that already
does more or less what people want here.  Three, I think that
implementing it is likely to be an extraordinarily large project.  The
whole data structure that libpq uses to store a parsed connection
string probably needs to change in fairly major ways.

So, I really wonder why we're not happy with the ability to substitute
out just the host and IP.

http://www.postgresql.org/message-id/4DFA5A86.9030301@acm.org
https://jdbc.postgresql.org/documentation/94/connect.html (bottom of page)

Yes, it's possible that some people might need to change some other
parameter when the host or IP changes.  But those people aren't
prohibited from writing their own function that tries to connect to
multiple PostgreSQL servers one after the other using any system
they'd like.  I don't think we really need to cater to every possible
use case in core.  The JDBC feature has been out for several years and
people seem to like it OK - the fact that we can think of things it
doesn't do doesn't make it a bad idea.  I'd rather have a feature that
can do 95% of what people want in the real world next month than 99%
of what people want in 2019, and I'm starting to think we're setting
the bar awfully high.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-09 07:14  Craig Ringer <craig@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2015-11-09 07:14 UTC (permalink / raw)
  To: ; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 7 November 2015 at 04:59, Robert Haas <robertmhaas@gmail.com> wrote:

> So, I really wonder why we're not happy with the ability to substitute
> out just the host and IP.

I tend to agree. That solves 95% of the problem and doesn't foreclose
solving the other 5% some other way if someone really cares later.

I'd rather not see convoluted and complex connstrings, per my prior
post. The JDBC extended URL style seems good enough.

IMO the biggest problem is that client-side failover is way more
complex than "got -ECONNREFUSED, try next host". I think we're all
focusing on not being able to twiddle arbitrary settings while
ignoring the real problem with client failover, i.e. making it
actually work in the real world.

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-09 09:44  Victor Wagner <vitus@wagner.pp.ru>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2015-11-09 09:44 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 9 Nov 2015 15:14:02 +0800
Craig Ringer <craig@2ndquadrant.com> wrote:


> 
> I'd rather not see convoluted and complex connstrings, per my prior
> post. The JDBC extended URL style seems good enough.

It is what my patch implements.
 
> IMO the biggest problem is that client-side failover is way more
> complex than "got -ECONNREFUSED, try next host". I think we're all
> focusing on not being able to twiddle arbitrary settings while
> ignoring the real problem with client failover, i.e. making it
> actually work in the real world.
> 
I've tried to deal with some of these problems. 

My patch have support for following things:

1. Check whether database instance is in the recovery/standby mode and
try to find another one if so.
2. Let cluster management software to have some time to promote one of
the standbys to master. I.e. there can be failover timeout specified to
allow retry after some time if no working master found.

Really there is room for some improvements in handling of connect
timeout (which became much more important thing when ability to try
next host appears). Now it is handled only by blocking-mode connect
functions, not by async state machine. But I decided to publish patch
without these improvements to get feedback from community.




-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-17 20:20  Peter Eisentraut <peter_e@gmx.net>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Peter Eisentraut @ 2015-11-17 20:20 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Craig Ringer <craig@2ndquadrant.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 11/6/15 3:59 PM, Robert Haas wrote:
> So, I really wonder why we're not happy with the ability to substitute
> out just the host and IP.

One of my concerns is that the proposed URLs are not valid URLs anymore
that can be parsed or composed with a URL library, which would be sad.

The other issue is that I think it's taking the implementation down the
wrong path.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-17 20:23  Peter Eisentraut <peter_e@gmx.net>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 0 replies; 165+ messages in thread

From: Peter Eisentraut @ 2015-11-17 20:23 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On 11/5/15 10:12 AM, Victor Wagner wrote:
> 2. You are suggesting that it should be possible to specify all options 
> separately for each of the fallback hosts. 

I'm not necessarily suggesting that.  I think it could very well be

conn="postgresql://foo postgresql://bar order=random"



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-11-18 20:55  Robert Haas <robertmhaas@gmail.com>
  parent: Peter Eisentraut <peter_e@gmx.net>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2015-11-18 20:55 UTC (permalink / raw)
  To: Peter Eisentraut <peter_e@gmx.net>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Craig Ringer <craig@2ndquadrant.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 17, 2015 at 3:20 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> On 11/6/15 3:59 PM, Robert Haas wrote:
>> So, I really wonder why we're not happy with the ability to substitute
>> out just the host and IP.
>
> One of my concerns is that the proposed URLs are not valid URLs anymore
> that can be parsed or composed with a URL library, which would be sad.

I agree that's sad.  But compatibility with JDBC is happy, which is
something to think about, at least.

> The other issue is that I think it's taking the implementation down the
> wrong path.

Well, I don't object to the idea of having some kind of a function
that can take a set of connection strings or URLs and try them all.
But then it's not really a connection string any more.  I mean, with
the proposal where we allow the host option to be multiply specified,
you can just plug this feature into any utility whatever that
understands connection strings, and regardless of whether you are
using the classic connection string format or the URL format, it will
work.  And it's a pretty simple extension of what we support already.

psql 'host=foo host=bar failovertime=1'

If we do what you're proposing, then I'm really not clear on how this
works.  Certainly, there can be new libpq functions that take a list
of connection strings or URLs as an argument... but what would this
look like if you wanted to invoke psql this way?

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-07 20:26  Korry Douglas <korry.douglas@enterprisedb.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 2 replies; 165+ messages in thread

From: Korry Douglas @ 2015-12-07 20:26 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org


> I've tried to deal with some of these problems.
>
> My patch have support for following things:
>
> 1. Check whether database instance is in the recovery/standby mode and
> try to find another one if so.
> 2. Let cluster management software to have some time to promote one of
> the standbys to master. I.e. there can be failover timeout specified to
> allow retry after some time if no working master found.
>
> Really there is room for some improvements in handling of connect
> timeout (which became much more important thing when ability to try
> next host appears). Now it is handled only by blocking-mode connect
> functions, not by async state machine. But I decided to publish patch
> without these improvements to get feedback from community.
A bit of testing on this turns up a problem.

Consider a connection string that specifies two hosts and a read/write 
connection:

   postgresql://korry@127.0.0.1:5301,127.0.0.1:5300/edb?readonly=0

If the first host is a healthy standby (meaning that I can connect to it 
but pg_is_in_recovery() returns 't'), the state machine will never move 
on to the second host.

The problem seems to be in PQconnectPoll() in the case for 
CONNECTION_AUTH_OK, specifically this code:

   /* We can release the address list now. */
   pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
   conn->addrlist = NULL;
   conn->addr_cur = NULL;

That frees up the list of alternative host addresses.  The state machine 
then progresses to CONNECTION_CHECK_RO (which invokes 
pg_is_in_recovery()), then CONNECTION_CHECK_RW (waiting for the response 
from the server).  Since we just connected to a standby replica, 
pg_is_in_recovery() returns 't' and the state changes to 
CONNECTION_NEEDED.  The next call to try_next_address() will fail to 
find a next address because we freed the list in the case for 
CONNECTION_AUTH_OK.

A related issue:  when the above sequence occurs, no error message is 
returned (because the case for CONNECTION_NEEDED thinks "an appropriate 
error message is already set up").

In short, if you successfully connect to standby replica (and specify 
readonly=0), the remaining hosts are ignored, even though one of those 
hosts is a master.

And one comment about the code itself - in connectDBStart(), you've 
added quite a bit of code to parse multiple hosts/ports. I would 
recommend adding a comment that shows the expected format, and then 
choosing better variable names (better than 'p', 'q', and 'r'); perhaps 
the variable names could refer to components of the connection string 
that you are parsing (like 'host', 'port', 'delimiter', ...).  That 
would make the code much easier to read/maintain.

Thanks.


                 -- Korry



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-07 21:12  Korry Douglas <korry.douglas@enterprisedb.com>
  parent: Korry Douglas <korry.douglas@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Korry Douglas @ 2015-12-07 21:12 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org




>
>> I've tried to deal with some of these problems.
>>
>> My patch have support for following things:
>>
>> 1. Check whether database instance is in the recovery/standby mode and
>> try to find another one if so.
>> 2. Let cluster management software to have some time to promote one of
>> the standbys to master. I.e. there can be failover timeout specified to
>> allow retry after some time if no working master found.
>>
>> Really there is room for some improvements in handling of connect
>> timeout (which became much more important thing when ability to try
>> next host appears). Now it is handled only by blocking-mode connect
>> functions, not by async state machine. But I decided to publish patch
>> without these improvements to get feedback from community.
> A bit of testing on this turns up a problem.
>
> Consider a connection string that specifies two hosts and a read/write 
> connection:
>
>   postgresql://korry@127.0.0.1:5301,127.0.0.1:5300/edb?readonly=0
>
> If the first host is a healthy standby (meaning that I can connect to 
> it but pg_is_in_recovery() returns 't'), the state machine will never 
> move on to the second host.
>
> The problem seems to be in PQconnectPoll() in the case for 
> CONNECTION_AUTH_OK, specifically this code:
>
>   /* We can release the address list now. */
>   pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
>   conn->addrlist = NULL;
>   conn->addr_cur = NULL;
>
> That frees up the list of alternative host addresses.  The state 
> machine then progresses to CONNECTION_CHECK_RO (which invokes 
> pg_is_in_recovery()), then CONNECTION_CHECK_RW (waiting for the 
> response from the server).  Since we just connected to a standby 
> replica, pg_is_in_recovery() returns 't' and the state changes to 
> CONNECTION_NEEDED.  The next call to try_next_address() will fail to 
> find a next address because we freed the list in the case for 
> CONNECTION_AUTH_OK.
>
> A related issue:  when the above sequence occurs, no error message is 
> returned (because the case for CONNECTION_NEEDED thinks "an 
> appropriate error message is already set up").
>
> In short, if you successfully connect to standby replica (and specify 
> readonly=0), the remaining hosts are ignored, even though one of those 
> hosts is a master.

A follow-up - the conn->addrlist is also freed when the case for 
CONNECTION_CHECK_RW decides that conn->status != CONNECTION_OK and calls 
closePGConn().


                 -- Korry


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-10 04:54  Victor Wagner <vitus@wagner.pp.ru>
  parent: Korry Douglas <korry.douglas@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2015-12-10 04:54 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 07 Dec 2015 15:26:33 -0500
Korry Douglas <korry.douglas@enterprisedb.com> wrote:


> The problem seems to be in PQconnectPoll() in the case for 
> CONNECTION_AUTH_OK, specifically this code:
> 
>    /* We can release the address list now. */
>    pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
>    conn->addrlist = NULL;
>    conn->addr_cur = NULL;
> That frees up the list of alternative host addresses.  The state
> machine then progresses to CONNECTION_CHECK_RO (which invokes 
> pg_is_in_recovery()), then CONNECTION_CHECK_RW (waiting for the

Thank you for pointing to this problem. I've overlooked it. Probably
I should improve my testing scenario.

I', attaching new version of the patch, which, hopefully, handles
address list freeing correctly.




-- 
                                   Victor Wagner <vitus@wagner.pp.ru>

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-5.patch (text/x-patch, 35.1K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 9c0e4c8..162bd4f 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7165,6 +7241,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 4a1a0272..ffc5daf 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"readonly", NULL, "0", NULL, + "Read only", "", 1, + offsetof(struct pg_conn, read_only)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timoeut", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -1390,11 +1401,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1453,78 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(conn->pghostaddr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + /* Parse comma-separated list of host-port pairs into + function-local array of records */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + nodes[nodecount].port = malloc(q - r ); + strncpy(nodes[nodecount].port, r + 1 , q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1534,73 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes->port); + free(nodes); goto connect_errReturn; } + nodes->port = strdup(portstr); #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + struct addrinfo *this_node_addrs; + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,12 +1613,23 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; - + if (conn->failover_timeout) { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } else { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), * so that it can easily be re-executed if needed again during the @@ -1603,6 +1728,76 @@ connectDBComplete(PGconn *conn) } } +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "sequential") == 0) + { + if (conn->addr_cur == NULL) + { + conn->addr_cur = conn->addrlist; + return 1; + } + else + { + conn->addr_cur = conn->addr_cur->ai_next; + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + /* If failover timeout is set, retry list of hosts from + * the beginning */ + conn->addr_cur = conn->addrlist; + } + return (conn->addr_cur != NULL); + } + } + else if (strcmp(conn->hostorder, "random") == 0) + { + struct addrinfo *choice = NULL, + *current = conn->addrlist; + int count = 0; + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + while (current != NULL) + { + if (current == conn->addr_cur) + { + current = current->ai_next; + } + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + } + current = current->ai_next; + } + if (choice == NULL) + return 0; + conn->addr_cur = choice; + return 1; + } + else if (strcmp(conn->hostorder, "parallel") == 0) + { + /* Not implemented yet */ + return 0; + } + return 0; + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +1875,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +1914,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +1934,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +1944,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +1955,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2002,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1898,7 +2093,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2139,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2599,10 +2793,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +2804,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +2836,101 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + * RO connection is OK if readonly connection is explicitely + * requested or if replication option is set. + */ + if ((conn->read_only && conn->read_only[0] > '0') + ||(conn->replication && conn->replication[0]) + ) + { + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + /* Call PQgetResult second time to clear connection + * state. Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res)!=1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } else { + value = PQgetvalue(res, 0, 0); <<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<<<< + if (value[0] == 't') ======= COMMON ANCESTOR content follows ============================ + if (strcmp(value, "true") == 0) ======= MERGED IN content follows ================================== + if (value[0]=='t') >>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + { + conn->status = CONNECTION_NEEDED; + } + } + if (res) PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn,true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2936,21 +3219,17 @@ freePGconn(PGconn *conn) WSACleanup(); #endif } - /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ -static void -closePGconn(PGconn *conn) -{ - PGnotify *notify; - pgParameterStatus *pstatus; + +static void pqTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3245,25 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,6 +3276,7 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; @@ -3969,6 +4268,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4389,29 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + /* Set flag that we get value of host option + from this service file, so subsequent + host lines should be appended to it, + not ignored + */ + if (strcmp(key,"host")==0) + hostflag=true; + } + else if (strcmp(key,"host") == 0 && hostflag) + { + /* Old host value is from same service file, + so append new one to it */ + char *old=options[i].val; + int oldlen=strlen(old); + options[i].val=malloc(oldlen+1+strlen(val)+1); + strncpy(options[i].val,old,oldlen); + options[i].val[oldlen]=','; + strcpy(options[i].val+oldlen+1,val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4804,87 +5127,118 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') - { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + host = p; + if (*p==':') { + int portnum; + char *portstr; + *(p++)='\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + prevchar = *p; + *p='\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + } else { + do { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; - } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; - - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + if (*p == ',') + p++; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* + * "p" has been incremented past optional URI credential information + * at this point and now points at the "netloc" part of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; + /* + * The address may be followed by a port specifier, a comma or a + * slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5014,6 +5368,16 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } /* * Store the value if the corresponding option exists; ignore @@ -5228,7 +5592,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 3a521d4..224db09 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 98ea6b1..dde4db5 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -333,7 +333,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -381,10 +385,12 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ - + /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ int be_key; /* key of backend --- needed for cancels */ diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local)
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-21 14:18  Teodor Sigaev <teodor@sigaev.ru>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Teodor Sigaev @ 2015-12-21 14:18 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org

Sorry, but there is something wrong with your patch:
% patch -p1 -C < ~/Downloads/libpq-failover-5.patch
....
--------------------------
|diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
...
Hunk #18 succeeded at 2804.
patch: **** malformed patch at line 666: <<<<<<< BEGIN MERGE CONFLICT: local 
copy shown first <<<<<<<<<<<<<<<

Victor Wagner wrote:
> On Mon, 07 Dec 2015 15:26:33 -0500
> Korry Douglas <korry.douglas@enterprisedb.com> wrote:
>
>
>> The problem seems to be in PQconnectPoll() in the case for
>> CONNECTION_AUTH_OK, specifically this code:
>>
>>     /* We can release the address list now. */
>>     pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
>>     conn->addrlist = NULL;
>>     conn->addr_cur = NULL;
>> That frees up the list of alternative host addresses.  The state
>> machine then progresses to CONNECTION_CHECK_RO (which invokes
>> pg_is_in_recovery()), then CONNECTION_CHECK_RW (waiting for the
>
> Thank you for pointing to this problem. I've overlooked it. Probably
> I should improve my testing scenario.
>
> I', attaching new version of the patch, which, hopefully, handles
> address list freeing correctly.
>
>
>
>
>
>
>

-- 
Teodor Sigaev                                   E-mail: teodor@sigaev.ru
                                                    WWW: http://www.sigaev.ru/


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-21 14:50  Victor Wagner <vitus@wagner.pp.ru>
  parent: Teodor Sigaev <teodor@sigaev.ru>
  0 siblings, 3 replies; 165+ messages in thread

From: Victor Wagner @ 2015-12-21 14:50 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 21 Dec 2015 17:18:37 +0300
Teodor Sigaev <teodor@sigaev.ru> wrote:

> Sorry, but there is something wrong with your patch:
> % patch -p1 -C < ~/Downloads/libpq-failover-5.patch

Really, somehow broken version of the patch got into message.

Here is correct one.

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-5.patch (text/x-patch, 34.8K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 9c0e4c8..162bd4f 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7165,6 +7241,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 4a1a0272..ffc5daf 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"readonly", NULL, "0", NULL, + "Read only", "", 1, + offsetof(struct pg_conn, read_only)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timoeut", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -1390,11 +1401,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1453,78 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(conn->pghostaddr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + /* Parse comma-separated list of host-port pairs into + function-local array of records */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + nodes[nodecount].port = malloc(q - r ); + strncpy(nodes[nodecount].port, r + 1 , q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1534,73 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes->port); + free(nodes); goto connect_errReturn; } + nodes->port = strdup(portstr); #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + struct addrinfo *this_node_addrs; + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,12 +1613,23 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; - + if (conn->failover_timeout) { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } else { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), * so that it can easily be re-executed if needed again during the @@ -1603,6 +1728,76 @@ connectDBComplete(PGconn *conn) } } +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "sequential") == 0) + { + if (conn->addr_cur == NULL) + { + conn->addr_cur = conn->addrlist; + return 1; + } + else + { + conn->addr_cur = conn->addr_cur->ai_next; + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + /* If failover timeout is set, retry list of hosts from + * the beginning */ + conn->addr_cur = conn->addrlist; + } + return (conn->addr_cur != NULL); + } + } + else if (strcmp(conn->hostorder, "random") == 0) + { + struct addrinfo *choice = NULL, + *current = conn->addrlist; + int count = 0; + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + while (current != NULL) + { + if (current == conn->addr_cur) + { + current = current->ai_next; + } + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + } + current = current->ai_next; + } + if (choice == NULL) + return 0; + conn->addr_cur = choice; + return 1; + } + else if (strcmp(conn->hostorder, "parallel") == 0) + { + /* Not implemented yet */ + return 0; + } + return 0; + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +1875,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +1914,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +1934,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +1944,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +1955,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2002,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1898,7 +2093,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2139,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2599,10 +2793,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +2804,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +2836,101 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + * RO connection is OK if readonly connection is explicitely + * requested or if replication option is set. + */ + if ((conn->read_only && conn->read_only[0] > '0') + ||(conn->replication && conn->replication[0]) + ) + { + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + /* Call PQgetResult second time to clear connection + * state. Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res)!=1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } else { + value = PQgetvalue(res, 0, 0); + if (value[0]=='t') + { + conn->status = CONNECTION_NEEDED; + } + } + if (res) PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn,true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2936,21 +3219,17 @@ freePGconn(PGconn *conn) WSACleanup(); #endif } - /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ -static void -closePGconn(PGconn *conn) -{ - PGnotify *notify; - pgParameterStatus *pstatus; + +static void pqTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3245,25 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,6 +3276,7 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; @@ -3969,6 +4268,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4389,29 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + /* Set flag that we get value of host option + from this service file, so subsequent + host lines should be appended to it, + not ignored + */ + if (strcmp(key,"host")==0) + hostflag=true; + } + else if (strcmp(key,"host") == 0 && hostflag) + { + /* Old host value is from same service file, + so append new one to it */ + char *old=options[i].val; + int oldlen=strlen(old); + options[i].val=malloc(oldlen+1+strlen(val)+1); + strncpy(options[i].val,old,oldlen); + options[i].val[oldlen]=','; + strcpy(options[i].val+oldlen+1,val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4804,87 +5127,118 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') - { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + host = p; + if (*p==':') { + int portnum; + char *portstr; + *(p++)='\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + prevchar = *p; + *p='\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + } else { + do { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; - } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; - - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + if (*p == ',') + p++; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* + * "p" has been incremented past optional URI credential information + * at this point and now points at the "netloc" part of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; + /* + * The address may be followed by a port specifier, a comma or a + * slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5014,6 +5368,16 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } /* * Store the value if the corresponding option exists; ignore @@ -5228,7 +5592,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 3a521d4..224db09 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 98ea6b1..dde4db5 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -333,7 +333,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -381,10 +385,12 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ - + /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ int be_key; /* key of backend --- needed for cancels */ diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local)
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-21 18:12  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 0 replies; 165+ messages in thread

From: Alvaro Herrera @ 2015-12-21 18:12 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

Victor Wagner wrote:
> On Mon, 21 Dec 2015 17:18:37 +0300
> Teodor Sigaev <teodor@sigaev.ru> wrote:
> 
> > Sorry, but there is something wrong with your patch:
> > % patch -p1 -C < ~/Downloads/libpq-failover-5.patch
> 
> Really, somehow broken version of the patch got into message.

It would be good to add a few test cases of this new functionality to
libpq's regress.in file.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2015-12-22 06:16  Michael Paquier <michael.paquier@gmail.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 0 replies; 165+ messages in thread

From: Michael Paquier @ 2015-12-22 06:16 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL mailing lists <pgsql-hackers@postgresql.org>

On Mon, Dec 21, 2015 at 11:50 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Mon, 21 Dec 2015 17:18:37 +0300
> Teodor Sigaev <teodor@sigaev.ru> wrote:
>
>> Sorry, but there is something wrong with your patch:
>> % patch -p1 -C < ~/Downloads/libpq-failover-5.patch
>
> Really, somehow broken version of the patch got into message.
>
> Here is correct one.

Patch is moved to next CF as you are still working on it.
-- 
Michael


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-19 14:34  Thom Brown <thom@linux.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  2 siblings, 2 replies; 165+ messages in thread

From: Thom Brown @ 2016-01-19 14:34 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 21 December 2015 at 14:50, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Mon, 21 Dec 2015 17:18:37 +0300
> Teodor Sigaev <teodor@sigaev.ru> wrote:
>
>> Sorry, but there is something wrong with your patch:
>> % patch -p1 -C < ~/Downloads/libpq-failover-5.patch
>
> Really, somehow broken version of the patch got into message.
>
> Here is correct one.

The segfault issue I originally reported now appears to be resolved.

But now I have another one:

psql 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
-c 'show port'

Segmentation fault

This is where no nodes are available.  If I remove hostorder=random,
or replace it with hostorder=sequential, it doesn't segfault.
However, it then tries to connect to PGHOST on PGPORT repeatedly, even
if I bring up one of the nodes it should be looking for.  Not only
this, but it seems to do it forever if failover_timeout is greater
than 0.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-21 09:49  Victor Wagner <vitus@wagner.pp.ru>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-01-21 09:49 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Tue, 19 Jan 2016 14:34:54 +0000
Thom Brown <thom@linux.com> wrote:

> The segfault issue I originally reported now appears to be resolved.
> 
> But now I have another one:
> 
> psql
> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
> -c 'show port'
> 
> Segmentation fault

This segfault appears to be a simple programming error. 
which comes out only when  we need to retry address list (which happens
when no node is available at the time of first scan)

There is code which prevents random hostorder to connect same node
twice a row

        while (current != NULL)
        {
            if (current == conn->addr_cur)
            {
                current = current->ai_next;
            }
            count++;
            if ((rand()&0xffff) < 0x10000 / count)
            {
                choice = current;
            }
            current = current->ai_next;
        }


There should be continue;  after first current = current->ai_next;
 
> This is where no nodes are available.  If I remove hostorder=random,
> or replace it with hostorder=sequential, it doesn't segfault.
> However, it then tries to connect to PGHOST on PGPORT repeatedly, even
> if I bring up one of the nodes it should be looking for.  Not only
> this, but it seems to do it forever if failover_timeout is greater
> than 0.

But this turns out to be more complicated matter, so I'm not ready to
provide next version of patch yet.







-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-22 19:30  Victor Wagner <vitus@wagner.pp.ru>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 2 replies; 165+ messages in thread

From: Victor Wagner @ 2016-01-22 19:30 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org; +Cc: Thom Brown <thom@linux.com>

On Tue, 19 Jan 2016 14:34:54 +0000
Thom Brown <thom@linux.com> wrote:

> 
> The segfault issue I originally reported now appears to be resolved.
> 
> But now I have another one:
> 
> psql
> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
> -c 'show port'

Here is new version of the patch. Now I've reworked hostorder=random and
it seems to work as well as sequential. failover_timeout works too.
I've also found a case when attempt to connect fail when receiving
FATAL message from server which is not properly up yet. So, it is fixed
too.

Addititonally, error messages from all failed connect attempts are not
accumulated now. Only last one is returned.





-- 
                                   Victor Wagner <vitus@wagner.pp.ru>

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-6.patch (text/x-patch, 35.8K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 2328d8f..3c7bd15 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7165,6 +7241,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 5ad4755..9140ad8 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"readonly", NULL, "0", NULL, + "Read only", "", 1, + offsetof(struct pg_conn, read_only)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timoeut", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -1390,11 +1401,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1453,78 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(conn->pghostaddr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + /* Parse comma-separated list of host-port pairs into + function-local array of records */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + nodes[nodecount].port = malloc(q - r ); + strncpy(nodes[nodecount].port, r + 1 , q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1534,73 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes->port); + free(nodes); goto connect_errReturn; } + nodes->port = strdup(portstr); #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + struct addrinfo *this_node_addrs; + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,12 +1613,23 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; - + if (conn->failover_timeout) { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } else { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), * so that it can easily be re-executed if needed again during the @@ -1603,6 +1728,94 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo *get_next_element(struct addrinfo **list,char + *order) { + struct addrinfo *choice = NULL, *prev, *current, *prechoice = NULL; + int count = 0; + if (*list == NULL) return NULL; + if (strcmp(order,"random") == 0) { + /* Peek random element from the list. */ + for (current = *list,prev = NULL; current != NULL; + prev=current, current=current->ai_next) + { + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + /* If prechoice is not NULL, selected element is not + first in the list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next=choice->ai_next; + choice->ai_next=*list; + *list=choice; + } + } + /* We always return first elemet of the list */ + return *list; +} +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder,"random")==0) { + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + /* If failover timeout is set, retry list of hosts from + * the beginning */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) { + /* Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + return 1; + } else { + return 0; + } + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +1893,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +1932,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +1952,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +1962,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +1973,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2020,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1898,7 +2111,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2157,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +2808,19 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + /* If we have more than one host in the connect + * string, fatal message from one of them is not + * really fatal + */ + if (try_next_address(conn)) { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +2832,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +2864,101 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + * RO connection is OK if readonly connection is explicitely + * requested or if replication option is set. + */ + if ((conn->read_only && conn->read_only[0] > '0') + ||(conn->replication && conn->replication[0]) + ) + { + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + /* Call PQgetResult second time to clear connection + * state. Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res)!=1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } else { + value = PQgetvalue(res, 0, 0); + if (value[0]=='t') + { + conn->status = CONNECTION_NEEDED; + } + } + if (res) PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn,true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2936,21 +3247,17 @@ freePGconn(PGconn *conn) WSACleanup(); #endif } - /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ -static void -closePGconn(PGconn *conn) -{ - PGnotify *notify; - pgParameterStatus *pstatus; + +static void pqTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3273,25 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,6 +3304,7 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; @@ -3969,6 +4296,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4417,29 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + /* Set flag that we get value of host option + from this service file, so subsequent + host lines should be appended to it, + not ignored + */ + if (strcmp(key,"host")==0) + hostflag=true; + } + else if (strcmp(key,"host") == 0 && hostflag) + { + /* Old host value is from same service file, + so append new one to it */ + char *old=options[i].val; + int oldlen=strlen(old); + options[i].val=malloc(oldlen+1+strlen(val)+1); + strncpy(options[i].val,old,oldlen); + options[i].val[oldlen]=','; + strcpy(options[i].val+oldlen+1,val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4804,87 +5155,118 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') - { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + host = p; + if (*p==':') { + int portnum; + char *portstr; + *(p++)='\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + prevchar = *p; + *p='\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + } else { + do { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; - } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; - - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + if (*p == ',') + p++; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* + * "p" has been incremented past optional URI credential information + * at this point and now points at the "netloc" part of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; + /* + * The address may be followed by a port specifier, a comma or a + * slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5014,6 +5396,16 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } /* * Store the value if the corresponding option exists; ignore @@ -5228,7 +5620,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 6bf34b3..bf70696 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 6c9bbf7..5c79df9 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -333,7 +333,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -381,6 +385,8 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local)
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-22 19:36  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 1 reply; 165+ messages in thread

From: Alvaro Herrera @ 2016-01-22 19:36 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org, Thom Brown <thom@linux.com>

You're editing the expected file for the libpq-regress thingy, but you
haven't added any new lines to test the new capability.  I think it'd be
good to add some there.  (I already said this earlier in the thread; is
there any reason you ignored it the first time?)

If the test program requires improvement to handle the new stuff, let's
do that.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-23 03:32  Thom Brown <thom@linux.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 2 replies; 165+ messages in thread

From: Thom Brown @ 2016-01-23 03:32 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 22 January 2016 at 19:30, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Tue, 19 Jan 2016 14:34:54 +0000
> Thom Brown <thom@linux.com> wrote:
>
>>
>> The segfault issue I originally reported now appears to be resolved.
>>
>> But now I have another one:
>>
>> psql
>> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
>> -c 'show port'
>
> Here is new version of the patch. Now I've reworked hostorder=random and
> it seems to work as well as sequential. failover_timeout works too.
> I've also found a case when attempt to connect fail when receiving
> FATAL message from server which is not properly up yet. So, it is fixed
> too.
>
> Addititonally, error messages from all failed connect attempts are not
> accumulated now. Only last one is returned.

I can't connect to a standby with the patch applied:

thom@swift:~/Development/test$ psql -p 5531 postgres
psql: thom@swift:~/Development/test$

No error message, nothing in the logs.  I find this is the case with
any standby, but doesn't affect primaries.

So this has broken existing functionality somewhere.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-23 04:23  Thom Brown <thom@linux.com>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Thom Brown @ 2016-01-23 04:23 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 23 January 2016 at 03:32, Thom Brown <thom@linux.com> wrote:
> On 22 January 2016 at 19:30, Victor Wagner <vitus@wagner.pp.ru> wrote:
>> On Tue, 19 Jan 2016 14:34:54 +0000
>> Thom Brown <thom@linux.com> wrote:
>>
>>>
>>> The segfault issue I originally reported now appears to be resolved.
>>>
>>> But now I have another one:
>>>
>>> psql
>>> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
>>> -c 'show port'
>>
>> Here is new version of the patch. Now I've reworked hostorder=random and
>> it seems to work as well as sequential. failover_timeout works too.
>> I've also found a case when attempt to connect fail when receiving
>> FATAL message from server which is not properly up yet. So, it is fixed
>> too.
>>
>> Addititonally, error messages from all failed connect attempts are not
>> accumulated now. Only last one is returned.
>
> I can't connect to a standby with the patch applied:
>
> thom@swift:~/Development/test$ psql -p 5531 postgres
> psql: thom@swift:~/Development/test$
>
> No error message, nothing in the logs.  I find this is the case with
> any standby, but doesn't affect primaries.
>
> So this has broken existing functionality somewhere.

Okay, I've tested my original complaints, and they appear to be
resolved.  The timeout works fine, the sequential and random orders
behave as expected, and the readonly setting is also working.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 09:18  Victor Wagner <vitus@wagner.pp.ru>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-01-24 09:18 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>

On Fri, 22 Jan 2016 16:36:15 -0300
Alvaro Herrera <alvherre@2ndquadrant.com> wrote:

> You're editing the expected file for the libpq-regress thingy, but you
> haven't added any new lines to test the new capability.  I think it'd
> be good to add some there.  (I already said this earlier in the
> thread; is there any reason you ignored it the first time?)

I seriously doubt that this program can be used to test new
capabilities.

All it does, it calls PQconninfoParse and than examines some fields of
PGconn structure.

The only reason I've to modify expected output is that I changed usage
of one of these field, and keep there comma-separated list of host:port
pairs instead of just hostname.

Thus contents this field after parsing of some existing URIs is
changed, while semantic of URIs is same.

If I add some new uris, than only thing I can test is that comma is
properly copied from the URI to this field. And may be that some syntax
errors are properly detected.

 
> If the test program requires improvement to handle the new stuff,
> let's do that.

The only improvement I can think of, is to examine list of the addrinfo
structures into which host list is eventually parsed. But it is quite
problematic, because it depends on many factors which are outside of
our control. 

It stores addresses resolved via OS's name resolver.

For example, if we specify 'localhost' there it can be parsed into one
or to records, depending on presence of IPv6 support.

If we use some other hostname here, we'll rely on internet connectivity
and DNS system. And we cannot ensure that any name to IP mapping will
persist for a long enough time. 

So, I think that new functionality need other approach for testing.
There should be test of real connection to real temporary cluster.
Probably, based on Perl TAP framework which is actively used in the
Postgres recently.
> 



-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 15:30  Thom Brown <thom@linux.com>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 2 replies; 165+ messages in thread

From: Thom Brown @ 2016-01-24 15:30 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 23 January 2016 at 03:32, Thom Brown <thom@linux.com> wrote:
> On 22 January 2016 at 19:30, Victor Wagner <vitus@wagner.pp.ru> wrote:
>> On Tue, 19 Jan 2016 14:34:54 +0000
>> Thom Brown <thom@linux.com> wrote:
>>
>>>
>>> The segfault issue I originally reported now appears to be resolved.
>>>
>>> But now I have another one:
>>>
>>> psql
>>> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
>>> -c 'show port'
>>
>> Here is new version of the patch. Now I've reworked hostorder=random and
>> it seems to work as well as sequential. failover_timeout works too.
>> I've also found a case when attempt to connect fail when receiving
>> FATAL message from server which is not properly up yet. So, it is fixed
>> too.
>>
>> Addititonally, error messages from all failed connect attempts are not
>> accumulated now. Only last one is returned.
>
> I can't connect to a standby with the patch applied:
>
> thom@swift:~/Development/test$ psql -p 5531 postgres
> psql: thom@swift:~/Development/test$
>
> No error message, nothing in the logs.  I find this is the case with
> any standby, but doesn't affect primaries.
>
> So this has broken existing functionality somewhere.

Okay, I've tested this again with additional logging.  Again, I'm just
running "psql -p 5531 postgres", which connects to a standby.  This
immediately exits psql, and the logs show:

2016-01-24 15:04:59.879 GMT - [unknown] - [unknown] LOG:  00000:
connection received: host=[local]
2016-01-24 15:04:59.879 GMT - [unknown] - [unknown] LOCATION:
BackendInitialize, postmaster.c:4081
2016-01-24 15:04:59.880 GMT - thom - postgres LOG:  00000: connection
authorized: user=thom database=postgres
2016-01-24 15:04:59.880 GMT - thom - postgres LOCATION:
PerformAuthentication, postinit.c:272
2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000: statement:
SELECT pg_catalog.pg_is_in_recovery()
2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
exec_simple_query, postgres.c:935
2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000: duration: 0.583 ms
2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
exec_simple_query, postgres.c:1164
2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000:
disconnection: session time: 0:00:00.007 user=thom database=postgres
host=[local]
2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
log_disconnections, postgres.c:4458

This shouldn't be checking whether it's a standby.  I also noticed that with:

psql 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535/postgres?hostorder=random&readonly=1'
-c 'show port'

The standby at port 5533 shows in the logs that it's checking whether
it's a standby when it happens to hit it.  Shouldn't this be
unnecessary if we've set "readonly" to 1?  The result of the query
doesn't appear to be useful for anything.

Another thing I've noticed is that the PORT variable (shown by \set)
always shows PGPORT, but I expect it to equal the port of whichever
host we successfully connected to.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 15:58  Thom Brown <thom@linux.com>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Thom Brown @ 2016-01-24 15:58 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 24 January 2016 at 15:30, Thom Brown <thom@linux.com> wrote:
> On 23 January 2016 at 03:32, Thom Brown <thom@linux.com> wrote:
>> On 22 January 2016 at 19:30, Victor Wagner <vitus@wagner.pp.ru> wrote:
>>> On Tue, 19 Jan 2016 14:34:54 +0000
>>> Thom Brown <thom@linux.com> wrote:
>>>
>>>>
>>>> The segfault issue I originally reported now appears to be resolved.
>>>>
>>>> But now I have another one:
>>>>
>>>> psql
>>>> 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533/postgres?hostorder=random&readonly=1&failover_timeout=5'
>>>> -c 'show port'
>>>
>>> Here is new version of the patch. Now I've reworked hostorder=random and
>>> it seems to work as well as sequential. failover_timeout works too.
>>> I've also found a case when attempt to connect fail when receiving
>>> FATAL message from server which is not properly up yet. So, it is fixed
>>> too.
>>>
>>> Addititonally, error messages from all failed connect attempts are not
>>> accumulated now. Only last one is returned.
>>
>> I can't connect to a standby with the patch applied:
>>
>> thom@swift:~/Development/test$ psql -p 5531 postgres
>> psql: thom@swift:~/Development/test$
>>
>> No error message, nothing in the logs.  I find this is the case with
>> any standby, but doesn't affect primaries.
>>
>> So this has broken existing functionality somewhere.
>
> Okay, I've tested this again with additional logging.  Again, I'm just
> running "psql -p 5531 postgres", which connects to a standby.  This
> immediately exits psql, and the logs show:
>
> 2016-01-24 15:04:59.879 GMT - [unknown] - [unknown] LOG:  00000:
> connection received: host=[local]
> 2016-01-24 15:04:59.879 GMT - [unknown] - [unknown] LOCATION:
> BackendInitialize, postmaster.c:4081
> 2016-01-24 15:04:59.880 GMT - thom - postgres LOG:  00000: connection
> authorized: user=thom database=postgres
> 2016-01-24 15:04:59.880 GMT - thom - postgres LOCATION:
> PerformAuthentication, postinit.c:272
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000: statement:
> SELECT pg_catalog.pg_is_in_recovery()
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
> exec_simple_query, postgres.c:935
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000: duration: 0.583 ms
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
> exec_simple_query, postgres.c:1164
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000:
> disconnection: session time: 0:00:00.007 user=thom database=postgres
> host=[local]
> 2016-01-24 15:04:59.886 GMT - thom - postgres LOCATION:
> log_disconnections, postgres.c:4458
>
> This shouldn't be checking whether it's a standby.  I also noticed that with:
>
> psql 'postgresql://thom@127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535/postgres?hostorder=random&readonly=1'
> -c 'show port'
>
> The standby at port 5533 shows in the logs that it's checking whether
> it's a standby when it happens to hit it.  Shouldn't this be
> unnecessary if we've set "readonly" to 1?  The result of the query
> doesn't appear to be useful for anything.
>
> Another thing I've noticed is that the PORT variable (shown by \set)
> always shows PGPORT, but I expect it to equal the port of whichever
> host we successfully connected to.

Actually, the same goes for the HOST variable, which is currently
showing the list of hosts:ports.

Output of \set variables without patch:

HOST = '127.0.0.1'
PORT = '5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'

And with patch:

HOST = '127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
PORT = '5488'

They're both wrong, but I'm hoping we can just show the right information here.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 19:46  Victor Wagner <vitus@wagner.pp.ru>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-01-24 19:46 UTC (permalink / raw)
  To: PostgreSQL-development <pgsql-hackers@postgresql.org>; +Cc: Thom Brown <thom@linux.com>

On Sun, 24 Jan 2016 15:30:22 +0000
Thom Brown <thom@linux.com> wrote:

в
> Okay, I've tested this again with additional logging.  Again, I'm just
> running "psql -p 5531 postgres", which connects to a standby.  This
> immediately exits psql, and the logs show:

> 2016-01-24 15:04:59.886 GMT - thom - postgres LOG:  00000: statement:
> SELECT pg_catalog.pg_is_in_recovery()
> This shouldn't be checking whether it's a standby.  I also noticed
> that with:

This is, of course, incompatibility with previous behavior. Probably,
I should modify this patch, so it would imply readonly flag if only one
host/port pair is specified in the command line.

Now it does check for standby regardless of number of hosts specified.



-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 19:53  Victor Wagner <vitus@wagner.pp.ru>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-01-24 19:53 UTC (permalink / raw)
  To: PostgreSQL-development <pgsql-hackers@postgresql.org>; +Cc: Thom Brown <thom@linux.com>

On Sun, 24 Jan 2016 15:58:10 +0000
Thom Brown <thom@linux.com> wrote:


> 
> Output of \set variables without patch:
> 
> HOST = '127.0.0.1'
> PORT =
> '5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
> 
> And with patch:
> 
> HOST =
> '127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
> PORT = '5488'
> 
> They're both wrong, but I'm hoping we can just show the right
> information here.

I think we should show right information here, but it is not so simple.

Problem is that I never keep symbolic representation of individual
host/port pair. And when we connect successfully, we have only struct
sockaddr representation of the it, which contain right IP
address, but doesn't contain symbolic host name.

Moreover, one hostname from connect string can produce more than one
addrinfo structures. For example, on the machines with IPv6 support,
'localhost' hostname is resolved into both 127.0.0.1 IPv4 address and
[::1] IPv6, and produces two records. 

So would do any name, which have both A and AAAA records in DNS. And
nothing prevent domain administrator to put more than one A record for
same hostname into DNS zone.


So, it is just same information which can be retrieved from the backend
via 

select inet_client_addr();
select inet_client_port();

What is really interesting for HOST and PORT variable - it is the name
of host and port number used to make actual connection, as they were
specified in the connect string or service file.


> 
> Thom



-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 20:11  Thom Brown <thom@linux.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Thom Brown @ 2016-01-24 20:11 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 24 January 2016 at 19:53, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Sun, 24 Jan 2016 15:58:10 +0000
> Thom Brown <thom@linux.com> wrote:
>
>
>>
>> Output of \set variables without patch:
>>
>> HOST = '127.0.0.1'
>> PORT =
>> '5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
>>
>> And with patch:
>>
>> HOST =
>> '127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
>> PORT = '5488'
>>
>> They're both wrong, but I'm hoping we can just show the right
>> information here.
>
> I think we should show right information here, but it is not so simple.
>
> Problem is that I never keep symbolic representation of individual
> host/port pair. And when we connect successfully, we have only struct
> sockaddr representation of the it, which contain right IP
> address, but doesn't contain symbolic host name.
>
> Moreover, one hostname from connect string can produce more than one
> addrinfo structures. For example, on the machines with IPv6 support,
> 'localhost' hostname is resolved into both 127.0.0.1 IPv4 address and
> [::1] IPv6, and produces two records.
>
> So would do any name, which have both A and AAAA records in DNS. And
> nothing prevent domain administrator to put more than one A record for
> same hostname into DNS zone.
>
>
> So, it is just same information which can be retrieved from the backend
> via
>
> select inet_client_addr();
> select inet_client_port();

I think you mean:

select inet_server_addr();
select inet_server_port();

> What is really interesting for HOST and PORT variable - it is the name
> of host and port number used to make actual connection, as they were
> specified in the connect string or service file.

And this is probably not the correct thing for it to report.  The
documentation says "The database server host you are currently
connected to." and "The database server port to which you are
currently connected.", so yeah, I'd expect to see those set to
whatever those 2 functions resolve to.  That being said, if one
connects via a domain socket, those appear to come back blank with
those functions, yet HOST and PORT report the correct information in
those cases (without passing in multiple hosts).  Is that a
pre-existing bug?

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-01-24 20:17  Thom Brown <thom@linux.com>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Thom Brown @ 2016-01-24 20:17 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 24 January 2016 at 20:11, Thom Brown <thom@linux.com> wrote:
> On 24 January 2016 at 19:53, Victor Wagner <vitus@wagner.pp.ru> wrote:
>> On Sun, 24 Jan 2016 15:58:10 +0000
>> Thom Brown <thom@linux.com> wrote:
>>
>>
>>>
>>> Output of \set variables without patch:
>>>
>>> HOST = '127.0.0.1'
>>> PORT =
>>> '5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
>>>
>>> And with patch:
>>>
>>> HOST =
>>> '127.0.0.1:5530,127.0.0.1:5531,127.0.0.1:5532,127.0.0.1:5533,127.0.0.1:5534,127.0.0.1:5535'
>>> PORT = '5488'
>>>
>>> They're both wrong, but I'm hoping we can just show the right
>>> information here.
>>
>> I think we should show right information here, but it is not so simple.
>>
>> Problem is that I never keep symbolic representation of individual
>> host/port pair. And when we connect successfully, we have only struct
>> sockaddr representation of the it, which contain right IP
>> address, but doesn't contain symbolic host name.
>>
>> Moreover, one hostname from connect string can produce more than one
>> addrinfo structures. For example, on the machines with IPv6 support,
>> 'localhost' hostname is resolved into both 127.0.0.1 IPv4 address and
>> [::1] IPv6, and produces two records.
>>
>> So would do any name, which have both A and AAAA records in DNS. And
>> nothing prevent domain administrator to put more than one A record for
>> same hostname into DNS zone.
>>
>>
>> So, it is just same information which can be retrieved from the backend
>> via
>>
>> select inet_client_addr();
>> select inet_client_port();
>
> I think you mean:
>
> select inet_server_addr();
> select inet_server_port();
>
>> What is really interesting for HOST and PORT variable - it is the name
>> of host and port number used to make actual connection, as they were
>> specified in the connect string or service file.
>
> And this is probably not the correct thing for it to report.  The
> documentation says "The database server host you are currently
> connected to." and "The database server port to which you are
> currently connected.", so yeah, I'd expect to see those set to
> whatever those 2 functions resolve to.  That being said, if one
> connects via a domain socket, those appear to come back blank with
> those functions, yet HOST and PORT report the correct information in
> those cases (without passing in multiple hosts).  Is that a
> pre-existing bug?

I've just checked, and can see that this doesn't appear to be a bug.
As per network.c:

/*
 * IP address that the server accepted the connection on (NULL if Unix socket)
 */

and

/*
 * port that the server accepted the connection on (NULL if Unix socket)
 */

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-02-01 22:05  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Alvaro Herrera @ 2016-02-01 22:05 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

Victor Wagner wrote:
> On Fri, 22 Jan 2016 16:36:15 -0300
> Alvaro Herrera <alvherre@2ndquadrant.com> wrote:
> 
> > You're editing the expected file for the libpq-regress thingy, but you
> > haven't added any new lines to test the new capability.  I think it'd
> > be good to add some there.  (I already said this earlier in the
> > thread; is there any reason you ignored it the first time?)
> 
> I seriously doubt that this program can be used to test new
> capabilities.
> 
> All it does, it calls PQconninfoParse and than examines some fields of
> PGconn structure.

Ah, you're right, I didn't remember that.

> If I add some new uris, than only thing I can test is that comma is
> properly copied from the URI to this field. And may be that some syntax
> errors are properly detected.

Yeah, we should do that.

> So, I think that new functionality need other approach for testing.
> There should be test of real connection to real temporary cluster.
> Probably, based on Perl TAP framework which is actively used in the
> Postgres recently.

Yes, agreed.  So please have a look at that one and share your opinion
about it.  It'd be useful.

Meanwhile I'm moving the patch to the next commitfest.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-03-09 23:11  David Steele <david@pgmasters.net>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: David Steele @ 2016-03-09 23:11 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

Hi Victor,

On 2/1/16 5:05 PM, Alvaro Herrera wrote:
> Victor Wagner wrote:
>> On Fri, 22 Jan 2016 16:36:15 -0300
>> Alvaro Herrera <alvherre@2ndquadrant.com> wrote:
>>
>>> You're editing the expected file for the libpq-regress thingy, but you
>>> haven't added any new lines to test the new capability.  I think it'd
>>> be good to add some there.  (I already said this earlier in the
>>> thread; is there any reason you ignored it the first time?)
>> I seriously doubt that this program can be used to test new
>> capabilities.
>>
>> All it does, it calls PQconninfoParse and than examines some fields of
>> PGconn structure.
> Ah, you're right, I didn't remember that.
>
>> If I add some new uris, than only thing I can test is that comma is
>> properly copied from the URI to this field. And may be that some syntax
>> errors are properly detected.
> Yeah, we should do that.
>
>> So, I think that new functionality need other approach for testing.
>> There should be test of real connection to real temporary cluster.
>> Probably, based on Perl TAP framework which is actively used in the
>> Postgres recently.
> Yes, agreed.  So please have a look at that one and share your opinion
> about it.  It'd be useful.
>
> Meanwhile I'm moving the patch to the next commitfest.

There hasn't been any movement on this patch in a while.  Will you have 
a new tests ready for review soon?

Thanks,

-- 
-David
david@pgmasters.net

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-03-10 12:34  Simon Riggs <simon@2ndQuadrant.com>
  parent: David Steele <david@pgmasters.net>
  0 siblings, 1 reply; 165+ messages in thread

From: Simon Riggs @ 2016-03-10 12:34 UTC (permalink / raw)
  To: David Steele <david@pgmasters.net>; Thom Brown <thom@linux.com>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; PostgreSQL-development <pgsql-hackers@postgresql.org>

On 9 March 2016 at 23:11, David Steele <david@pgmasters.net> wrote:


> There hasn't been any movement on this patch in a while.  Will you have a
> new tests ready for review soon?
>

I see the value in this feature, but the patch itself needs work and
probably some slimming down/reality and a good spellcheck.

If someone takes this on soon it can go into 9.6, otherwise I vote to
reject this early to avoid wasting review time.

-- 
Simon Riggs                http://www.2ndQuadrant.com/
<http://www.2ndquadrant.com/;
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-03-16 23:17  David Steele <david@pgmasters.net>
  parent: Simon Riggs <simon@2ndQuadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: David Steele @ 2016-03-16 23:17 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: Simon Riggs <simon@2ndQuadrant.com>; Thom Brown <thom@linux.com>; PostgreSQL-development <pgsql-hackers@postgresql.org>

On 3/10/16 7:34 AM, Simon Riggs wrote:
> On 9 March 2016 at 23:11, David Steele <david@pgmasters.net
> <mailto:david@pgmasters.net>> wrote:
>
>     There hasn't been any movement on this patch in a while.  Will you
>     have a new tests ready for review soon?
>
>
> I see the value in this feature, but the patch itself needs work and
> probably some slimming down/reality and a good spellcheck.
>
> If someone takes this on soon it can go into 9.6, otherwise I vote to
> reject this early to avoid wasting review time.

Since there has been no response from the author I have marked this 
patch "returned with feedback".  Please feel free to resubmit for 9.7!

-- 
-David
david@pgmasters.net


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-08-26 04:40  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: David Steele <david@pgmasters.net>
  0 siblings, 3 replies; 165+ messages in thread

From: Mithun Cy @ 2016-08-26 04:40 UTC (permalink / raw)
  To: David Steele <david@pgmasters.net>; Victor Wagner <vitus@wagner.pp.ru>; +Cc: Simon Riggs <simon@2ndquadrant.com>; Thom Brown <thom@linux.com>; PostgreSQL-development <pgsql-hackers@postgresql.org>

On Thu, Mar 17, 2016 at 4:47 AM, David Steele <david@pgmasters.net> wrote:
>Since there has been no response from the author I have marked this patch
"returned with feedback".  Please feel free >to resubmit for 9.7!
I have started to work on this patch, and tried to fix some of the issues
discussed above. The most recent patch 06 has fixed many issues which was
raised previously which include indefinite looping, crashes. And, some of
the issues which remain pending are.

1. Connection status functions PQport, PQhost do not give corresponding
values of established connection. -- Have attached the patch for same.

2. Default value of readonly parameter is 0, which means should connect to
master only. So absence of parameter in connection string in simple cases
like "./psql -p PORT database" fails to connect to hot standby server.  I
think since if readonly=1 means connect to any. and readonly=0 means
connect to master only, we should change the default value  to 1, to handle
the cases when parameter is not specified.

JFYI Interestingly PostgreSql JDBC driver have following options
targetServerType=any|master|slave|preferSlave for same purpose.

Also did a little bit of patch clean-up.

Also found some minor issues related to build which I am working on.
1. make check-world @src/interfaces/ecpg/test/connect fails with following
error:
gcc -Wall -Wmissing-prototypes -Wpointer-arith
-Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute
-Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard
-g -O0 -pthread -D_REENTRANT -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS
test1.o -L../../ecpglib -L../../pgtypeslib
-L../../../../../src/interfaces/libpq
-L../../../../../src/port -L../../../../../src/common -Wl,--as-needed
-Wl,-rpath,'/home/mithun/edbsrc/patch6bin/lib',--enable-new-dtags  -lecpg
-lpgtypes -lpq -lpgcommon -lpgport -lz -lrt -lcrypt -ldl -lm   -o test1
../../../../../src/interfaces/libpq/libpq.so: undefined reference to
`pg_usleep'
collect2: error: ld returned 1 exit status
make[3]: *** [test1] Error 1
make[3]: Leaving directory `/home/mithun/mynewpost/p1/
src/interfaces/ecpg/test/connect'

patch has used pg_usleep() which is in L../../../../../src/port  I think
dependency is not captured rightly.

Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-07.patch (text/x-patch, 40.2K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index f22e3da..835061d 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7212,6 +7288,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 76b61bd..b8a9cf5 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -300,6 +300,18 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + + {"readonly", NULL, "0", NULL, + "Read only", "", 1, /* should be just '0' or '1' */ + offsetof(struct pg_conn, read_only)}, + + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, /* strlen(INT32_MAX) == 10 */ + offsetof(struct pg_conn, failover_timeout)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +348,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); +static void freenodes(PGconn * conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +394,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -1394,7 +1409,7 @@ connectDBStart(PGconn *conn) char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *node; int ret; if (!conn) @@ -1436,21 +1451,102 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + conn->nodes = calloc(sizeof(struct nodeinfo), 2); + conn->nodes->host = strdup(conn->pghostaddr); + conn->nodes->port = strdup(portstr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost; + char *q; + char *r; + int nodecount = 0, + nodesallocated = 4; + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records. + */ + conn->nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + /* + * If there is IPv6, colons before close bracket are part of + * address. + */ + if (*q == ']') + r = NULL; + q++; + } + + if (r) + { + /* Host has explicitely specified port */ + conn->nodes[nodecount].port = malloc(q - r ); + strncpy(conn->nodes[nodecount].port, r + 1 , q - r); + conn->nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + conn->nodes[nodecount].port = NULL; + } + + /* + * If port is not given we use portstr. Save it now will be useful + * for PQport(). + */ + if (!conn->nodes[nodecount].port) + conn->nodes[nodecount].port = strdup(portstr); + else if (conn->nodes[nodecount].port[0] == '\0') + { + free(conn->nodes[nodecount].port); + conn->nodes[nodecount].port = strdup(portstr); + } + + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + + /* Fill node record */ + conn->nodes[nodecount].host = malloc(r - p + 1); + strncpy(conn->nodes[nodecount].host, p, r - p); + conn->nodes[nodecount].host[r - p] = 0; + + if (*q) /* skip a comma. */ + q++; + nodecount++; + if (nodecount == nodesallocated) + conn->nodes + = realloc(conn->nodes, + sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + + /* Fill end-of-host list marker */ + conn->nodes[nodecount].host = NULL; + conn->nodes[nodecount].port = NULL; + conn->nodes[nodecount].this_addr = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + conn->nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,29 +1556,89 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(conn->nodes); goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + conn->nodes = calloc(sizeof(struct nodeinfo), 2); + conn->nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ + conn->nodes->port = strdup(portstr); } - /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* + * Use pg_getaddrinfo_all() to resolve each of the the address in node + * list. + */ + for (node = conn->nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + struct addrinfo *curr_addr; + + ret = pg_getaddrinfo_all(node->host, node->port, &hint, + &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + node->this_addr = NULL; + continue; + } + + /* + * Save all pointers to addrinfo's in an array, which will be used + * later to map conn->addr_cur to its corresponding node info. + */ + node->num_this_addr = 0; + curr_addr = this_node_addrs; + while (curr_addr) + { + node->num_this_addr++; + curr_addr = curr_addr->ai_next; + } + + if (node->num_this_addr) + { + int i; + node->this_addr + = malloc(sizeof(struct addrinfo *) * node->num_this_addr); + curr_addr = this_node_addrs; + for (i = 0; i < node->num_this_addr; i++) + { + node->this_addr[i] = curr_addr; + curr_addr = curr_addr->ai_next; + } + } + + /* Add this host addrs to addrs field of PGconn structure. */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + + /* Check if we've found at least one usable address. */ + if (!addrs) + { + freenodes(conn); conn->options_valid = false; goto connect_errReturn; } @@ -1499,11 +1655,26 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1603,6 +1774,159 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to the + * beginning (and putting its addres into given pointer. Returns address of + * first list element. + */ +static struct addrinfo *get_next_element(struct addrinfo **list, char *order) +{ + struct addrinfo *choice = NULL, *prev, *current, *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order,"random") == 0) + { + /* Peek random element from the list. */ + for (current = *list,prev = NULL; current != NULL; + prev=current, current=current->ai_next) + { + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the list. + * We have to move it to he head. + */ + if (prechoice != NULL) + { + prechoice->ai_next=choice->ai_next; + choice->ai_next=*list; + *list=choice; + } + } + + /* We always return first elemet of the list */ + return *list; +} + +/* ------------- + * set_host_and_port + * Set conn->pghost and conn->pgport which are needed for PQhost + * and PQport calls. + */ +static void +set_host_and_port(PGconn *conn) +{ + bool found_node = false; + struct nodeinfo *node; + + if (!conn->nodes) + return; + + for (node = conn->nodes; + (node->host != NULL || node->port != NULL) && !found_node; node++) + { + /* + * For each node check whether it corresponds to same addr_curr. + * And then set connected_node details appropriately. + */ + struct addrinfo **addrs = node->this_addr; + int i = 0; + while (i < node->num_this_addr) + { + if (addrs[i] == conn->addr_cur) + { + found_node = true; + + if (conn->connected_node.port) + free(conn->connected_node.port); + if (node->port) + conn->connected_node.port = strdup(node->port); + else + conn->connected_node.port = NULL; + + if (conn->connected_node.host) + free(conn->connected_node.host); + if (node->host) + conn->connected_node.host = strdup(node->host); + else + conn->connected_node.host = NULL; + break; + } + + i++; + } + } +} + + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder,"random")==0) { + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + + if (conn->addr_cur) + set_host_and_port(conn); + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + + /* + * If failover timeout is set, retry list of hosts from + * the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* Clean up error message buffer. */ + set_host_and_port(conn); + resetPQExpBuffer(&conn->errorMessage); + return 1; + } + else + return 0; +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +2004,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +2043,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +2063,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2073,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2084,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2131,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1898,7 +2222,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2268,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,14 +2919,22 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * FATAL message from one of them is not really FATAL. + */ + if (try_next_address(conn)) + { + /* Must drop the old connection. */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2614,8 +2945,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +2977,121 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * Move the state whether we need a read-only or read-write + * connection. And if that can be satisfied. + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + * RO connection is OK if readonly connection is explicitely + * requested or if replication option is set. + */ + if ((conn->read_only && conn->read_only[0] > '0') + ||(conn->replication && conn->replication[0]) + ) + { + /* We can release the nodes and address list now. */ + freenodes(conn); + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Ok we need a read-write connection. We can find whether the + * server accept such a connection by its results for + * "SELECT pg_catalog.pg_is_in_recovery()" + */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored. + */ + + PQgetResult(conn); + + if (!res || + (PQresultStatus(res) != PGRES_TUPLES_OK) || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one. + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0]=='t') + { + conn->status = CONNECTION_NEEDED; + } + } + + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn,true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + + /* We can release the nodes and address list now. */ + freenodes(conn); + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2937,20 +3381,43 @@ freePGconn(PGconn *conn) #endif } + /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * freenodes + * - Free memory used to store all given hostname and service port. */ static void -closePGconn(PGconn *conn) +freenodes(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + struct nodeinfo *node; + + if (!conn->nodes) + return; + + for (node = conn->nodes; + (node->host != NULL || node->port != NULL); node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + if (node->this_addr) + free(node->this_addr); + } + free(conn->nodes); + conn->nodes = NULL; +} + + +/* + * pqTerminateConn + * - send terminate message to the backend, but do not free any transient + * state of PGconn object, which can be needed to reconnect. + */ +static void +pqTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2958,13 +3425,30 @@ closePGconn(PGconn *conn) if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK) { /* - * Try to send "close connection" message to backend. Ignore any - * error. + * Try to send "close connection" message to backend. Ignore any error. */ pqPutMsgStart('X', false, conn); pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -2983,6 +3467,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + freenodes(conn); pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4455,9 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + + /* true if 'host' parameter is seen in service file. */ + bool hostflag = false; FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4577,33 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored. + */ + if (!strcmp(key,"host")) + hostflag = true; + } + else if (!strcmp(key,"host") && hostflag) + { + /* + * Existing host value is from same service file, + * so append new one to it. + */ + char *old=options[i].val; + int oldlen=strlen(old); + + options[i].val=malloc(oldlen+1+strlen(val)+1); + strncpy(options[i].val,old,oldlen); + options[i].val[oldlen]=','; + strcpy(options[i].val+oldlen+1,val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4809,86 +5324,129 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, p = start; } - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; - } - if (p == host) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); - goto cleanup; - } + int portnum; + char *portstr; - /* Cut off the bracket and advance */ *(p++) = '\0'; + portstr = p; + portnum = 0; - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part of + * the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - while (*p && *p != '/' && *p != '?') - ++p; + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ + + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; } - if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5019,6 +5577,17 @@ conninfo_uri_parse_params(char *params, value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + /* * Store the value if the corresponding option exists; ignore * otherwise. At this point both keyword and value are not @@ -5232,7 +5801,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; @@ -5353,7 +5937,7 @@ PQhost(const PGconn *conn) if (!conn) return NULL; if (conn->pghost != NULL && conn->pghost[0] != '\0') - return conn->pghost; + return conn->connected_node.host; else { #ifdef HAVE_UNIX_SOCKETS @@ -5372,7 +5956,12 @@ PQport(const PGconn *conn) { if (!conn) return NULL; - return conn->pgport; +#ifdef HAVE_UNIX_SOCKETS + if (IS_AF_UNIX(conn->addrlist_family)) + return conn->pgport; + else +#endif + return conn->connected_node.port; } char * diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 1183323..c68f976 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -292,6 +292,22 @@ typedef struct pgDataValue const char *value; /* data value, without zero-termination */ } PGdataValue; + +typedef struct nodeinfo +{ + char *host; + char *port; + + /* + * All of the addrinfos corresponding to this node are saved here. The + * function try_next_address rearranges the conn->addrlist at global level. + * And, after that reverse mapping of addrinfo to nodeinfo will not be + * possible if we store them as it is. + */ + struct addrinfo **this_addr; /* addresses of above host and port. */ + int num_this_addr; +} nodeinfo; + /* * PGconn stores all the state data associated with a single connection * to a backend. @@ -334,7 +350,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -378,10 +398,20 @@ struct pg_conn bool sigpipe_so; /* have we masked SIGPIPE via SO_NOSIGPIPE? */ bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */ + /* + * This variable stores information about host node to which client is + * connected. We cannot use pghost and pgport as we need them unmodified + * to do connection reset. + */ + nodeinfo connected_node; + /* Transient state needed while establishing connection */ struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + nodeinfo *nodes; /* needed for PQport, PQhost */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local)
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-08-26 04:47  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-08-26 04:47 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Fri, 26 Aug 2016 10:10:33 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Thu, Mar 17, 2016 at 4:47 AM, David Steele <david@pgmasters.net>
> wrote:
> >Since there has been no response from the author I have marked this
> >patch
> "returned with feedback".  Please feel free >to resubmit for 9.7!
> I have started to work on this patch, and tried to fix some of the
> issues discussed above. The most recent patch 06 has fixed many
> issues which was raised previously which include indefinite looping,
> crashes. And, some of the issues which remain pending are.

Although I have not resubmutted my patch yet, I've continue to work on
it, so you can see my last version on 

https://www.wagner.pp.ru/fossil/pgfailover.

It seems that I've already fixed some of issues you mentioned below.
Also I've added testsuite, which is incomplete.

> JFYI Interestingly PostgreSql JDBC driver have following options
> targetServerType=any|master|slave|preferSlave for same purpose.

Probably we should havbe a comptibility alias.


-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-08-30 09:24  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-08-30 09:24 UTC (permalink / raw)
  To: David Steele <david@pgmasters.net>; Victor Wagner <vitus@wagner.pp.ru>; +Cc: Simon Riggs <simon@2ndquadrant.com>; Thom Brown <thom@linux.com>; PostgreSQL-development <pgsql-hackers@postgresql.org>

On Fri, Aug 26, 2016 at 10:10 AM, Mithun Cy <mithun.cy@enterprisedb.com>
wrote:
>
> >rpath,'/home/mithun/edbsrc/patch6bin/lib',--enable-new-dtags  -lecpg
> -lpgtypes -lpq -lpgcommon -lpgport -lz -lrt -lcrypt -ldl -lm   -o test1
> >../../../../../src/interfaces/libpq/libpq.so: undefined reference to
> `pg_usleep'
>

As similar to psql I have added -lpq for compilation. So now ecpg tests
compiles and make check-world has passed.
-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-ecpg-make-01.patch (application/octet-stream, 605B) download diff --git a/src/interfaces/ecpg/test/Makefile.regress b/src/interfaces/ecpg/test/Makefile.regress index b3d7c1e..7bc67a0 100644 --- a/src/interfaces/ecpg/test/Makefile.regress +++ b/src/interfaces/ecpg/test/Makefile.regress @@ -20,7 +20,7 @@ ECPG_TEST_DEPENDENCIES = ../../preproc/ecpg$(X) \ $(srcdir)/../../include/sql3types.h %: %.o - $(CC) $(CFLAGS) $< $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@ + $(CC) $(CFLAGS) $< $(libpq_pgport) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@ # Caution: this build rule is overridden in some child Makefiles # where it's necessary to use nondefault switches to ecpg;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-08-31 08:13  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-08-31 08:13 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Tue, 30 Aug 2016 14:54:57 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Fri, Aug 26, 2016 at 10:10 AM, Mithun Cy
> <mithun.cy@enterprisedb.com> wrote:
> >  
> > >rpath,'/home/mithun/edbsrc/patch6bin/lib',--enable-new-dtags
> > >-lecpg  
> > -lpgtypes -lpq -lpgcommon -lpgport -lz -lrt -lcrypt -ldl -lm   -o
> > test1  
> > >../../../../../src/interfaces/libpq/libpq.so: undefined reference
> > >to  
> > `pg_usleep'
> >  
> 
> As similar to psql I have added -lpq for compilation. So now ecpg
> tests compiles and make check-world has passed.

Thanks, I've added this to 7-th (yet unpublished here) version of my
patch, available on my site.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-08-31 08:13  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-08-31 08:13 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Fri, 26 Aug 2016 10:10:33 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Thu, Mar 17, 2016 at 4:47 AM, David Steele <david@pgmasters.net>
> wrote:
> >Since there has been no response from the author I have marked this
> >patch  
> "returned with feedback".  Please feel free >to resubmit for 9.7!
> I have started to work on this patch, and tried to fix some of the
> issues discussed above. The most recent patch 06 has fixed many
> issues which was raised previously which include indefinite looping,
> crashes. And, some of the issues which remain pending are.
> 
> 1. Connection status functions PQport, PQhost do not give
> corresponding values of established connection. -- Have attached the
> patch for same.
> 
> 2. Default value of readonly parameter is 0, which means should
> connect to master only. So absence of parameter in connection string
> in simple cases like "./psql -p PORT database" fails to connect to
> hot standby server.  I think since if readonly=1 means connect to
> any. and readonly=0 means connect to master only, we should change
> the default value  to 1, to handle the cases when parameter is not
> specified.
> 
> JFYI Interestingly PostgreSql JDBC driver have following options
> targetServerType=any|master|slave|preferSlave for same purpose.
> 
> Also did a little bit of patch clean-up.
> 
> Also found some minor issues related to build which I am working on.
> 1. make check-world @src/interfaces/ecpg/test/connect fails with
> following error:
> gcc -Wall -Wmissing-prototypes -Wpointer-arith
> -Wdeclaration-after-statement -Wendif-labels
> -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing
> -fwrapv -fexcess-precision=standard -g -O0 -pthread -D_REENTRANT
> -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS test1.o -L../../ecpglib
> -L../../pgtypeslib -L../../../../../src/interfaces/libpq
> -L../../../../../src/port -L../../../../../src/common -Wl,--as-needed
> -Wl,-rpath,'/home/mithun/edbsrc/patch6bin/lib',--enable-new-dtags
> -lecpg -lpgtypes -lpq -lpgcommon -lpgport -lz -lrt -lcrypt -ldl -lm
> -o test1 ../../../../../src/interfaces/libpq/libpq.so: undefined
> reference to `pg_usleep'
> collect2: error: ld returned 1 exit status
> make[3]: *** [test1] Error 1
> make[3]: Leaving directory `/home/mithun/mynewpost/p1/
> src/interfaces/ecpg/test/connect'
> 
> patch has used pg_usleep() which is in L../../../../../src/port  I
> think dependency is not captured rightly.
> 
> Thanks and Regards
> Mithun C Y
> EnterpriseDB: http://www.enterprisedb.com



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-05 02:29  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-09-05 02:29 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers <pgsql-hackers@postgresql.org>

On Aug 31, 2016 1:44 PM, "Victor Wagner" <vitus@wagner.pp.ru> wrote:
> Thanks, I've added this to 7-th (yet unpublished here) version of my
> patch.
Hi victor, just wanted know what your plan for your patch 07. Would you
like to submit it to the community. I have just signed up as a reviewer for
your patch.

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-05 04:22  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-09-05 04:22 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 5 Sep 2016 07:59:02 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Aug 31, 2016 1:44 PM, "Victor Wagner" <vitus@wagner.pp.ru> wrote:
> > Thanks, I've added this to 7-th (yet unpublished here) version of my
> > patch.
> Hi victor, just wanted know what your plan for your patch 07. Would
> you like to submit it to the community. I have just signed up as a
> reviewer for your patch.

As community shows an interest with this patch, and it has been
included in the current commitfest, I've to submit it.

This version of patch includes

1. Most important - a tap test suite (really small enough and has a
room for improvements).

2. Compatibility with older versions - now readonly check is skipped if
only one hostname is specified in the connect string

3. pg_host and pg_port variables now show host name and port library
was connected to.

4. Your fix with compilation of ecpg tests.

Patch is attached.



-- 
                                   Victor Wagner <vitus@wagner.pp.ru>

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-7.patch (text/x-patch, 54.4K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index f22e3da..835061d 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;readonly=1 </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-readonly"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-readonly" xreflabel="readonly"> + <term><literal>readonly</literal></term> + <listitem> + <para> + If this parameter is 0 (the default), upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + non-zero, connection to warm standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>falover_timeout</literal></term> + <listitem> + <para> + Maximum time to cycilically retry all the hosts in commect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7212,6 +7288,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/ecpg/test/Makefile.regress b/src/interfaces/ecpg/test/Makefile.regress index b3d7c1e..7bc67a0 100644 --- a/src/interfaces/ecpg/test/Makefile.regress +++ b/src/interfaces/ecpg/test/Makefile.regress @@ -20,7 +20,7 @@ ECPG_TEST_DEPENDENCIES = ../../preproc/ecpg$(X) \ $(srcdir)/../../include/sql3types.h %: %.o - $(CC) $(CFLAGS) $< $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@ + $(CC) $(CFLAGS) $< $(libpq_pgport) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@ # Caution: this build rule is overridden in some child Makefiles # where it's necessary to use nondefault switches to ecpg; diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index 0b4065e..7a5682f 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 76b61bd..608fdc0 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"readonly", NULL, "0", NULL, + "Read only", "", 1, + offsetof(struct pg_conn, read_only)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timoeut", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,8 +817,10 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, - conn->dbName, conn->pguser); + conn->pgpass = PasswordFromFile( + conn->actualhost? conn->actualhost:conn->pghost, + conn->actualport? conn->actualport:conn->pgport, + conn->dbName, conn->pguser); if (conn->pgpass == NULL) { conn->pgpass = strdup(DefaultPassword); @@ -1173,6 +1186,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1405,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1457,78 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(conn->pghostaddr); hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + /* Parse comma-separated list of host-port pairs into + function-local array of records */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + nodes[nodecount].port = malloc(q - r ); + strncpy(nodes[nodecount].port, r + 1 , q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1538,80 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes->port); + free(nodes); goto connect_errReturn; } + nodes->port = strdup(portstr); #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + nodes->host = strdup(DefaultHost); hint.ai_family = AF_UNSPEC; #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + struct addrinfo *this_node_addrs; + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + if (node->host) { + struct addrinfo *n; + for (n=this_node_addrs;n != NULL; n=n->ai_next) { + n->ai_canonname = strdup(node->host); + } + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + for (p = addrs; p->ai_next != NULL; p = p->ai_next); + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,12 +1624,23 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; - + if (conn->failover_timeout) { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } else { + conn->failover_finish_time = (time_t)0; /* it is in past, so its ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), * so that it can easily be re-executed if needed again during the @@ -1522,6 +1658,14 @@ connect_errReturn: } +static char* get_port_from_addrinfo(struct addrinfo *ai) +{ + char port[6]; + sprintf(port,"%d", htons(((struct sockaddr_in *)ai->ai_addr)->sin_port)); + return strdup(port); +} + + /* * connectDBComplete * @@ -1603,6 +1747,98 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo *get_next_element(struct addrinfo **list,char + *order) { + struct addrinfo *choice = NULL, *prev, *current, *prechoice = NULL; + int count = 0; + if (*list == NULL) return NULL; + if (strcmp(order,"random") == 0) { + /* Peek random element from the list. */ + for (current = *list,prev = NULL; current != NULL; + prev=current, current=current->ai_next) + { + count++; + if ((rand()&0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + /* If prechoice is not NULL, selected element is not + first in the list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next=choice->ai_next; + choice->ai_next=*list; + *list=choice; + } + } + /* We always return first element of the list */ + return *list; +} +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder,"random")==0) { + /* Initialize random number generator in case if nobody have + * done it before. Use value from rand along with time in case + * random number have been initialized by application. + * Use address of conn structure to load-balance different + * connections in the same app + */ + srand((unsigned int)((long int)conn ^ (long int) time(NULL) ^ + (long int)rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) { + /* If failover timeout is set, retry list of hosts from + * the beginning */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) { + /* Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } else { + return 0; + } + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +1916,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +1955,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +1975,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +1985,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +1996,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2043,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2119,8 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + /* Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2136,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2182,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +2833,19 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + /* If we have more than one host in the connect + * string, fatal message from one of them is not + * really fatal + */ + if (try_next_address(conn)) { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +2857,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +2889,120 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK + * RO connection is OK if readonly connection is explicitely + * requested or if replication option is set, or just one + * host is specified in the connect string. + */ + if ((conn->pghost==NULL || strchr(conn->pghost,',')==NULL) || + ((conn->read_only && conn->read_only[0] > '0')) + ||(conn->replication && conn->replication[0]) + ) + { + + /* We can release the address list now. + * but first make a copy of name of host we are + * connected to or it would be freed with list + */ + if (conn->actualhost) { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + /* Call PQgetResult second time to clear connection + * state. Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res)!=1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } else { + value = PQgetvalue(res, 0, 0); + if (value[0]=='t') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"),conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + if (res) PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn,true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2936,21 +3291,17 @@ freePGconn(PGconn *conn) WSACleanup(); #endif } - /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ -static void -closePGconn(PGconn *conn) -{ - PGnotify *notify; - pgParameterStatus *pstatus; + +static void pqTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3317,25 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3348,23 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* If addrlist is not freed, actualhost points in there. + Otherwice it is allocated and should be freed */ + if (conn->addrlist == NULL && conn->actualhost !=NULL) { + free(conn->actualhost); + conn->actualhost = NULL; + } + if (conn->actualport) { + free(conn->actualport); + conn->actualport = NULL; + } pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4351,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4472,29 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + /* Set flag that we get value of host option + from this service file, so subsequent + host lines should be appended to it, + not ignored + */ + if (strcmp(key,"host")==0) + hostflag=true; + } + else if (strcmp(key,"host") == 0 && hostflag) + { + /* Old host value is from same service file, + so append new one to it */ + char *old=options[i].val; + int oldlen=strlen(old); + options[i].val=malloc(oldlen+1+strlen(val)+1); + strncpy(options[i].val,old,oldlen); + options[i].val[oldlen]=','; + strcpy(options[i].val+oldlen+1,val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4808,87 +5214,118 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') - { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + host = p; + if (*p==':') { + int portnum; + char *portstr; + *(p++)='\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum <1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } + prevchar = *p; + *p='\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)); - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + } else { + do { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; - } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } - - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* + * "p" has been incremented past optional URI credential information + * at this point and now points at the "netloc" part of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + p++; + /* + * The address may be followed by a port specifier, a comma or a + * slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum <1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) + + if (*host && + !conninfo_storeval(options, "host", host, + errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5455,16 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5679,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; @@ -5352,7 +5814,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +5836,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 1183323..53d8891 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,11 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *read_only; /* If true, we could work with readonly + * standby server */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +386,12 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list + *waiting for new master to appear */ + char *actualhost; /* Name of host we are actually connected + * to (if there is list in the pghost) */ + char *actualport; /* Port number we are actually + * connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/t/001-multihost.pl b/src/interfaces/libpq/t/001-multihost.pl new file mode 100644 index 0000000..5cf237b --- /dev/null +++ b/src/interfaces/libpq/t/001-multihost.pl @@ -0,0 +1,403 @@ +# Minimal test testing streaming replication +use strict; +use warnings; +use PostgresNode; +use TestLib; +use Test::More tests => 28; +# Initialize master node + +my $node_master = get_new_node('master'); +$node_master->init(allows_streaming => 1, use_tcp =>1); +$node_master->start; +my $backup_name = 'my_backup'; + +# Take backup +$node_master->backup($backup_name); +# Create streaming standby linking to master +my $node_standby_1 = get_new_node('standby_1'); + +$node_standby_1->init_from_backup($node_master, $backup_name, + has_streaming => 1, use_tcp=>1); +$node_standby_1->start; +# Take backup of standby 1 (not mandatory, but useful to check if +# pg_basebackup works on a standby). +$node_standby_1->backup($backup_name); + +# Create second standby node linking to standby 1 +my $node_standby_2 = get_new_node('standby_2'); +$node_standby_2->init_from_backup($node_standby_1, $backup_name, + has_streaming => 1,use_tcp=>1); +$node_standby_2->start; + + +sub get_host_port { + my $node = shift; + return "$PostgresNode::test_localhost:".$node->port +} + +sub multiconnstring { + my $nodes = shift; + my $database = shift || "postgres"; + my $params=shift; + my $extra=""; + if ($params) { + my @cs; + while (my ($key,$val) = each %$params) { + push @cs, $key ."=".$val; + } + $extra = "?".join("&",@cs); + } + my $str= "postgresql://".join(",",map({get_host_port($_)} @$nodes))."/$database$extra"; + return $str; + +} + +sub connstring2 { + my $nodes = shift; + my $database = shift; + my $params = shift; + my @args=(); + for my $n (@$nodes) { + push @args, "host=".get_host_port($n); + } + push @args, "dbname=$database" if defined($database); + while (my ($key,$val) = each %$params) { + push @args,"$key=$val"; + } + return join(" ",@args); +} + +# +# Copied from PosgresNode.pm passing explicit connect-string instead of +# constructed from object +# + +sub psql +{ + # We expect dbname to be part of connstr + my ($connstr, $sql, %params) = @_; + + my $stdout = $params{stdout}; + my $stderr = $params{stderr}; + my $timeout = undef; + my $timeout_exception = 'psql timed out'; + my @psql_params = + ('psql', '-XAtq', '-d', $connstr, '-f', '-'); + + # If the caller wants an array and hasn't passed stdout/stderr + # references, allocate temporary ones to capture them so we + # can return them. Otherwise we won't redirect them at all. + if (wantarray) + { + if (!defined($stdout)) + { + my $temp_stdout = ""; + $stdout = \$temp_stdout; + } + if (!defined($stderr)) + { + my $temp_stderr = ""; + $stderr = \$temp_stderr; + } + } + + $params{on_error_stop} = 1 unless defined $params{on_error_stop}; + $params{on_error_die} = 0 unless defined $params{on_error_die}; + + push @psql_params, '-v', 'ON_ERROR_STOP=1' if $params{on_error_stop}; + push @psql_params, @{ $params{extra_params} } + if defined $params{extra_params}; + + $timeout = + IPC::Run::timeout($params{timeout}, exception => $timeout_exception) + if (defined($params{timeout})); + + ${ $params{timed_out} } = 0 if defined $params{timed_out}; + + # IPC::Run would otherwise append to existing contents: + $$stdout = "" if ref($stdout); + $$stderr = "" if ref($stderr); + + my $ret; + + # Run psql and capture any possible exceptions. If the exception is + # because of a timeout and the caller requested to handle that, just return + # and set the flag. Otherwise, and for any other exception, rethrow. + # + # For background, see + # http://search.cpan.org/~ether/Try-Tiny-0.24/lib/Try/Tiny.pm + do + { + local $@; + eval { + my @ipcrun_opts = (\@psql_params, '<', \$sql); + push @ipcrun_opts, '>', $stdout if defined $stdout; + push @ipcrun_opts, '2>', $stderr if defined $stderr; + push @ipcrun_opts, $timeout if defined $timeout; + + IPC::Run::run @ipcrun_opts; + $ret = $?; + }; + my $exc_save = $@; + if ($exc_save) + { + + # IPC::Run::run threw an exception. re-throw unless it's a + # timeout, which we'll handle by testing is_expired + die $exc_save + if (blessed($exc_save) || $exc_save ne $timeout_exception); + + $ret = undef; + + die "Got timeout exception '$exc_save' but timer not expired?!" + unless $timeout->is_expired; + + if (defined($params{timed_out})) + { + ${ $params{timed_out} } = 1; + } + else + { + die "psql timed out: stderr: '$$stderr'\n" + . "while running '@psql_params'"; + } + } + }; + + if (defined $$stdout) + { + chomp $$stdout; + $$stdout =~ s/\r//g if $TestLib::windows_os; + } + + if (defined $$stderr) + { + chomp $$stderr; + $$stderr =~ s/\r//g if $TestLib::windows_os; + } + + # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR + # We don't use IPC::Run::Simple to limit dependencies. + # + # We always die on signal. + my $core = $ret & 128 ? " (core dumped)" : ""; + die "psql exited with signal " + . ($ret & 127) + . "$core: '$$stderr' while running '@psql_params'" + if $ret & 127; + $ret = $ret >> 8; + + if ($ret && $params{on_error_die}) + { + die "psql error: stderr: '$$stderr'\nwhile running '@psql_params'" + if $ret == 1; + die "connection error: '$$stderr'\nwhile running '@psql_params'" + if $ret == 2; + die "error running SQL: '$$stderr'\nwhile running '@psql_params'" + if $ret == 3; + die "psql returns $ret: '$$stderr'\nwhile running '@psql_params'"; + } + + if (wantarray) + { + return ($ret, $$stdout, $$stderr); + } + else + { + return $ret; + } +} + +sub psql_conninfo { + my ($connstr) = shift; + my ($timed_out); + my ($retcode,$stdout,$stderr)=psql($connstr,'\conninfo', + timed_out=>\$timed_out); + if ($retcode==0 && $stdout =~ /on host "([^"]*)" at port "([^"]*)"/s) { + return "$1:$2"; + } else { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} + +sub psql_server_addr { + my ($connstr) = shift; + my ($timed_out); + my $sql = "select abbrev(inet_server_addr()) ||':'||inet_server_port();\n"; + my ($retcode,$stdout,$stderr)=psql($connstr,$sql, + timed_out=>\$timed_out); + if ($retcode==0 ) { + return $stdout; + } else { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} +my $conninfo; +# Test 1.1 - all hosts available, master first, readwrite requested + $conninfo=psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2])); + is($conninfo,get_host_port($node_master),"master first, rw, conninfo"); +# Test 1.2 + $conninfo=psql_server_addr(multiconnstring([$node_master,$node_standby_1,$node_standby_2])); + is($conninfo,get_host_port($node_master),"master first, rw, server funcs"); + +# Test 2.1 - use symbolic name for master and IP for slave + $conninfo=psql_conninfo("postgresql://localhost:".$node_master->port. + ",127.0.0.1:".$node_standby_1->port."/postgres"); + + is($conninfo,"localhost:".$node_master->port, "master symbolic, rw, conninfo"); +# Test 2.2 - check server-side connect info (would return numeric IP) + $conninfo=psql_server_addr("postgresql://localhost:".$node_master->port. + ",127.0.0.1:".$node_standby_1->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,'master symbolic, rw server funcs'); + +# Test 3.1 - all nodes available, master second, readwrite requested + $conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + + is($conninfo,get_host_port($node_master),"master second,rw, conninfo" ); +# Test 3.2 Check server-side connection info + $conninfo=psql_server_addr(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + + is($conninfo,get_host_port($node_master),"master second, rw, server funcs"); +# Test 4.1 - use symbolic name for slave and IP for smaster + $conninfo=psql_conninfo("postgresql://localhost:".$node_standby_1->port. + ",127.0.0.1:".$node_master->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,"slave symbolic, rw,conninfo"); + +# Test 4.2 - check server-side connect info + $conninfo=psql_server_addr("postgresql://localhost:".$node_standby_1->port. + ",127.0.0.1:".$node_master->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,"slave symbolic rw, server funcs"); + +# Test 5 - all nodes available, master first, readonly requested + + $conninfo=psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2],undef,{readonly=>1})); + + is($conninfo,get_host_port($node_master),"master first, ro, conninfo"); + +# Test 6 - all nodes available, master second, readonly requested + $conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2],undef,{readonly=>1})); + + is($conninfo,get_host_port($node_standby_1),"master second, ro conninfo"); + +# Test 7.1 - all nodes available, random order, readonly. +# Expect that during six attempts any of three nodes would be collected +# at least once + +my %conncount=(); +for (my $i=0;$i<9;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{readonly=>1,hostorder=>'random'})); + $conncount{$conn}++; +} +is(scalar(keys(%conncount)),3,'random order, readonly connect'); +# Test 7.2 - alternate (jdbc compatible) syntax for randomized hosts + +for (my $i=0;$i<6;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{readonly=>1,loadBalanceHosts=>"true"})); + $conncount{$conn}++; +} +#diag(join(",",keys %conncount)); +is(scalar(keys %conncount),3,"alternate JDBC-compatible syntax for random order"); + +# Test 8 - all nodes available, random order, readwrite +# Expect all six connections go to the master + +%conncount = (); +for (my $i=0;$i<6;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{hostorder=>'random'})); + $conncount{$conn}++; +} + +is(length(keys %conncount),1,'random order, rw connect only one node'); +ok(exists $conncount{get_host_port($node_master)},'random order, rw connects master'); + +# Test 8.1 one host in URL, master +$conninfo=psql_conninfo(multiconnstring([$node_master])); +is($conninfo,get_host_port($node_master),"old behavoir compat - master"); + + +# Test 8.2 one host in URL, slave +$conninfo=psql_conninfo(multiconnstring([$node_standby_1])); +is($conninfo,get_host_port($node_standby_1),"old behavoir compat - slave"); + +# Test 9 - try to connect only slaves in rw mode + +$conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_standby_2])); +is($conninfo,"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1","cannot connect just slaves in RW mode"); + + + +# Test 10 - one of slaves is not available +$node_standby_1->stop(); + +# Test 10.1 + +$conninfo= psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + +is($conninfo,get_host_port($node_master),"first node is unavailable"); + +# Test 10.2 + +$conninfo = psql_conninfo(multiconnstring([$node_standby_2,$node_standby_1,$node_master])); + +is($conninfo,get_host_port($node_master),"first node standby, second unavailable"); + +# Test 10.3 + +$conninfo = psql_conninfo(multiconnstring([$node_standby_1,$node_standby_2,$node_master],undef,{readonly=>1})); +is($conninfo,get_host_port($node_standby_2),"first node unavailable, second standmby, readonly mode"); + +$node_standby_1->start(); + +$node_master->stop(); + +$conninfo= psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + +is($conninfo,"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1","master unavialble, cannot connect just slaves in RW mode"); + +$conninfo= psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2],undef,{readonly=>1})); + +is($conninfo,get_host_port($node_standby_1),"Master unavailable, read only "); + +$node_master->start(); + +# Test 11 Alternate syntax + +$conninfo = psql_conninfo(connstring2([$node_standby_1,$node_standby_2,$node_master])); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master third, rw"); + + + +$conninfo = psql_conninfo(connstring2([$node_master, $node_standby_1,$node_standby_2])); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master first, rw"); + + + +$conninfo = +psql_conninfo(connstring2([$node_standby_1,$node_standby_2,$node_master],undef, +{readonly => 1})); + +is ($conninfo, get_host_port($node_standby_1),"Alternate syntax, master third, ro"); + + + +$conninfo = psql_conninfo(connstring2([$node_master, $node_standby_1,$node_standby_2], undef,{readonly=>1})); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master first, ro"); + + +# Test 11.5 one host in URL, master +$conninfo=psql_conninfo(connstring2([$node_master])); +is($conninfo,get_host_port($node_master),"alt syntax old behavoir compat - master"); + + +# Test 11.6 one host in URL, slave +$conninfo=psql_conninfo(connstring2([$node_standby_1])); +is($conninfo,get_host_port($node_standby_1),"alt syntax old behavoir compat - slave"); + + + diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index fede1e6..5d88c9a 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -392,7 +392,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; - + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -424,7 +424,11 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp} ) { + print $conf "listen_addresses = '$test_localhost'\n"; + } else { + print $conf "listen_addresses = ''\n"; + } } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-05 11:03  Aleksander Alekseev <a.alekseev@postgrespro.ru>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 2 replies; 165+ messages in thread

From: Aleksander Alekseev @ 2016-09-05 11:03 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

Hello, Victor.

> As community shows an interest with this patch, and it has been
> included in the current commitfest, I've to submit it.

Naturally we show interest in this patch. It's a great feature that
would be very nice to have!

> This version of patch includes
> 
> 1. Most important - a tap test suite (really small enough and has a
> room for improvements).
> 
> 2. Compatibility with older versions - now readonly check is skipped if
> only one hostname is specified in the connect string
> 
> 3. pg_host and pg_port variables now show host name and port library
> was connected to.
> 
> 4. Your fix with compilation of ecpg tests.
> 
> Patch is attached.

After a brief examination I've found following ways to improve the
patch.

1) It looks like code is not properly formatted.

2)

> +      <term><literal>readonly</literal></term>
> +      <listitem>
> +      <para>
> +      If this parameter is 0 (the default), upon successful connection
> +      library checks if host is in recovery state, and if it is so, 
> +      tries next host in the connect string. If this parameter is
> +      non-zero, connection to warm standby nodes are considered
> +      successful.

IIRC the are "warm" and "hot" standby's in PostgreSQL terminology. The
difference is that you can't execute any queries on a "warm" standby. So
the description is probably wrong. I suggest to fix it to just "...
connection to standby nodes are...".

3)

> +     <term><literal>falover_timeout</literal></term>
> +     <listitem>
> +     <para>
> +     Maximum time to cycilically retry all the hosts in commect string.
> +     (as decimal integer number of seconds). If not specified, then
> +     hosts are tried just once.
> +     </para>

Typos: cycilically, commect

4) 

>  static int 
>  connectDBStart(PGconn *conn)
>  {
> +       struct nodeinfo
> +       {
> +               char       *host;
> +               char       *port;
> +       };

Not sure if all compilers we support can parse this. I suggest to
declare nodinfo structure outside of procedure, just to be safe.

5)

> +               nodes = calloc(sizeof(struct nodeinfo), 2); 
> +               nodes->host = strdup(conn->pghostaddr);
>                 hint.ai_family = AF_UNSPEC;

> +               /* Parse comma-separated list of host-port pairs into
> +                  function-local array of records */
> +               nodes = malloc(sizeof(struct nodeinfo) * 4); 


>                 /* pghostaddr and pghost are NULL, so use Unix domain
>  * socket */
> -               node = NULL;
> +               nodes = calloc(sizeof(struct nodeinfo), 2); 

> +       sprintf(port,"%d", htons(((struct sockaddr_in
> *)ai->ai_addr)->sin_port));
> +       return strdup(port);

You should check return values of malloc, calloc and strdup procedures,
or use safe pg_* equivalents.

6) 

> +                       for (p = addrs; p->ai_next != NULL; p =
>   p->ai_next);
> +                       p->ai_next = this_node_addrs;

Looks a bit scary. I suggest to add an empty scope ( {} ) and a comment
to make our intention clear here.

7) Code compiles with following warnings (CLang 3.8):

> 1 warning generated.
> fe-connect.c:5239:39: warning: if statement has empty body
> [-Wempty-body]
>                                                                    errorMessage,
> false, true));
>                                                                                               ^
> fe-connect.c:5239:39: note: put the semicolon on a separate line to
> silence this warning
> 1 warning generated.

8) get_next_element procedure implementation is way too smart (read
"complicated"). You could probably just store current list length and
generate a random number between 0 and length-1.

-- 
Best regards,
Aleksander Alekseev


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-06 02:28  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Aleksander Alekseev <a.alekseev@postgrespro.ru>
  1 sibling, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-09-06 02:28 UTC (permalink / raw)
  To: Aleksander Alekseev <a.alekseev@postgrespro.ru>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers <pgsql-hackers@postgresql.org>

On Mon, Sep 5, 2016 at 4:33 PM, Aleksander Alekseev <
a.alekseev@postgrespro.ru> wrote:
>After a brief examination I've found following ways to improve the patch.
Adding to above comments.

1)
+ /*
+ * consult connection options and check if RO connection is OK
+ * RO connection is OK if readonly connection is explicitely
+ * requested or if replication option is set, or just one
+ * host is specified in the connect string.
+ */
+ if ((conn->pghost==NULL || strchr(conn->pghost,',')==NULL) ||
+ ((conn->read_only && conn->read_only[0] > '0'))
+ ||(conn->replication && conn->replication[0])
+ )
+ {

Now if only one host is in connection string and it ask for read_write
connection(connect to master) I mean read_only is set 0 explicitly. With
above logic we will allow it to connect to standby?. I still think psql
connection to standby should be handled by changing the default value of
readonly to 1 (which means connect to any). Thinking further probably
replacing readonly parameter with targetServerType=any|master (with default
being any) should clear some confusions and bring consistency since same is
used in JDBC multi host connection string.

2)
@@ -1460,33 +1538,80 @@ connectDBStart(PGconn *conn)
   portstr,
   (int) (UNIXSOCK_PATH_BUFLEN - 1));
  conn->options_valid = false;
+ free(nodes->port);

nodes->port was not allocated at this point.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-06 05:03  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-09-06 05:03 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Tue, 6 Sep 2016 07:58:28 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> 
> Now if only one host is in connection string and it ask for read_write
> connection(connect to master) I mean read_only is set 0 explicitly.
> With above logic we will allow it to connect to standby?. I still
> think psql connection to standby should be handled by changing the
> default value of readonly to 1 (which means connect to any). 

It would definitely be more logical, but I haven't found easy way to do
it. May be I should return to this place and rethink. I don't like and
idea to explicitely ignore connection string parameter due to some
condition. 

Really, I think, test for replication connection can be either
removed from this part of code now.  


> Thinking
> further probably replacing readonly parameter with
> targetServerType=any|master (with default being any) should clear
> some confusions and bring consistency since same is used in JDBC
> multi host connection string.

It seems that in this context change readonly=0|1 to
targetServerType=any|master  makes sense.


 
> 2)
> @@ -1460,33 +1538,80 @@ connectDBStart(PGconn *conn)
>    portstr,
>    (int) (UNIXSOCK_PATH_BUFLEN - 1));
>   conn->options_valid = false;
> + free(nodes->port);
> 
> nodes->port was not allocated at this point.
> 

I'll recheck it.

-- 
                                   Victor Wagner <vitus@wagner.pp.ru>


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-07 13:56  Victor Wagner <vitus@wagner.pp.ru>
  parent: Aleksander Alekseev <a.alekseev@postgrespro.ru>
  1 sibling, 2 replies; 165+ messages in thread

From: Victor Wagner @ 2016-09-07 13:56 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Mon, 5 Sep 2016 14:03:11 +0300
Aleksander Alekseev <a.alekseev@postgrespro.ru> wrote:

> Hello, Victor.
> 
> 
> 1) It looks like code is not properly formatted.
> 

Thanks for pointing to the documentation and formatting problems. I'll
fix them 
 
> >  static int 
> >  connectDBStart(PGconn *conn)
> >  {
> > +       struct nodeinfo
> > +       {
> > +               char       *host;
> > +               char       *port;
> > +       };  
> 
> Not sure if all compilers we support can parse this. I suggest to
> declare nodinfo structure outside of procedure, just to be safe.
> 

Block-local structs  are part of C language standard. I don't remember
when they appeared first (may be in K&R C), but at least since C89 AFAIR
they are allowed explicitely.

And using most local scope possible is always a good thing.

So, I'll leave this structure function local for now.


> 
> You should check return values of malloc, calloc and strdup
> procedures, or use safe pg_* equivalents.

Thanks, I'll fix this one.
 
> 6) 
> 
> > +                       for (p = addrs; p->ai_next != NULL; p =
> >   p->ai_next);
> > +                       p->ai_next = this_node_addrs;  
> 
> Looks a bit scary. I suggest to add an empty scope ( {} ) and a
> comment to make our intention clear here.

Ok, it really would make code more clear.
 
> 7) Code compiles with following warnings (CLang 3.8):
> 
> > 1 warning generated.
> > fe-connect.c:5239:39: warning: if statement has empty body
> > [-Wempty-body]
> >                                                                    errorMessage,
> > false, true));
> >                                                                                               ^
> > fe-connect.c:5239:39: note: put the semicolon on a separate line to
> > silence this warning
> > 1 warning generated.  

Oops, it looks like logic error, which should be fixed. Thanks for
testing my patch by more picky compiler.

> 8) get_next_element procedure implementation is way too smart (read
> "complicated"). You could probably just store current list length and
> generate a random number between 0 and length-1.

No, algorithm here is more complicated. It must ensure that there would
not be second attempt to connect to host, for which unsuccessful
connection attempt was done. So, there is list rearrangement.

Algorithm for pick random list element by single pass is quite trivial.




-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-07 14:32  Aleksander Alekseev <a.alekseev@postgrespro.ru>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 0 replies; 165+ messages in thread

From: Aleksander Alekseev @ 2016-09-07 14:32 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

> > 8) get_next_element procedure implementation is way too smart (read
> > "complicated"). You could probably just store current list length and
> > generate a random number between 0 and length-1.
> 
> No, algorithm here is more complicated. It must ensure that there would
> not be second attempt to connect to host, for which unsuccessful
> connection attempt was done. So, there is list rearrangement.
> 
> Algorithm for pick random list element by single pass is quite trivial.

Great! In this case I would be _trivial_ for you to write a comment that
describes how this procedure works, what makes you think that it gives a
good distribution in all possible cases (e.g. if there is more than
0x10000 elements in a list - why not), etc. Right? :)

-- 
Best regards,
Aleksander Alekseev


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-08 11:24  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-09-08 11:24 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Tue, 6 Sep 2016 07:58:28 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Mon, Sep 5, 2016 at 4:33 PM, Aleksander Alekseev <
> a.alekseev@postgrespro.ru> wrote:
> >After a brief examination I've found following ways to improve the
> >patch.  
> Adding to above comments.
> 
I'm sending new version of patch.

I've replaced readonly option with target_server_type (with JDBC
compatibility alias targetServerType), 

use logic of setting defaults based on number of hosts in the connect
string instead of complicated condition in the state machine,

added checks for return values of memory allocation function.

Also, I've solved pg_usleep problem by linking pgsleep.c into libpq
along with some other libpgport objects which are already linked there.

Thus client applications don't need to link with libpgport and libpq
shared library is self-containted.
 

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-8.patch (text/x-patch, 58.6K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..f0df877 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal> upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + <literaL>any</literal>, connection to standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in connect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7303,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..815a827 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 9668b52..9490ec0 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -888,7 +901,21 @@ connectOptions2(PGconn *conn) if (!conn->client_encoding_initial) goto oom_error; } - + /* + * Validate target_server_mode option + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in @@ -1173,6 +1200,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1419,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1471,126 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].port, r + 1, q - r); + /* FIXME need to check that port is numeric */ + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitely, set + * target_server_type to "master" + */ + conn->target_server_type = strdup("master"); + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1600,104 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + nodes->port = strdup(portstr); + if (nodes->port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1710,27 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1522,6 +1749,16 @@ connect_errReturn: } +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + return strdup(port); +} + + /* * connectDBComplete * @@ -1603,6 +1840,117 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char + *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator in case if nobody have done it + * before. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +2028,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +2067,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +2087,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2097,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2108,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2155,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2231,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2250,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2296,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +2947,21 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +2973,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +3005,125 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * consult connection options and check if RO connection is OK RO + * connection is OK if readonly connection is explicitely + * requested or if replication option is set, or just one host is + * specified in the connect string. + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now. but first make a copy + * of name of host we are connected to or it would be freed + * with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3414,17 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3440,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3472,27 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4479,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4600,33 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4808,87 +5346,126 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5595,22 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5825,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; @@ -5352,7 +5960,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +5982,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index a94ead0..658f9f8 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +387,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/t/001-multihost.pl b/src/interfaces/libpq/t/001-multihost.pl new file mode 100644 index 0000000..a57f7c3 --- /dev/null +++ b/src/interfaces/libpq/t/001-multihost.pl @@ -0,0 +1,417 @@ +# Minimal test testing streaming replication +use strict; +use warnings; +use PostgresNode; +use TestLib; +use Test::More tests => 29; +# Initialize master node + +my $node_master = get_new_node('master'); +$node_master->init(allows_streaming => 1, use_tcp =>1); +$node_master->start; +my $backup_name = 'my_backup'; + +# Take backup +$node_master->backup($backup_name); +# Create streaming standby linking to master +my $node_standby_1 = get_new_node('standby_1'); + +$node_standby_1->init_from_backup($node_master, $backup_name, + has_streaming => 1, use_tcp=>1); +$node_standby_1->start; +# Take backup of standby 1 (not mandatory, but useful to check if +# pg_basebackup works on a standby). +$node_standby_1->backup($backup_name); + +# Create second standby node linking to standby 1 +my $node_standby_2 = get_new_node('standby_2'); +$node_standby_2->init_from_backup($node_standby_1, $backup_name, + has_streaming => 1,use_tcp=>1); +$node_standby_2->start; + + +sub get_host_port { + my $node = shift; + return "$PostgresNode::test_localhost:".$node->port +} + +sub multiconnstring { + my $nodes = shift; + my $database = shift || "postgres"; + my $params=shift; + my $extra=""; + if ($params) { + my @cs; + while (my ($key,$val) = each %$params) { + push @cs, $key ."=".$val; + } + $extra = "?".join("&",@cs); + } + my $str= "postgresql://".join(",",map({get_host_port($_)} @$nodes))."/$database$extra"; + return $str; + +} + +sub connstring2 { + my $nodes = shift; + my $database = shift; + my $params = shift; + my @args=(); + for my $n (@$nodes) { + push @args, "host=".get_host_port($n); + } + push @args, "dbname=$database" if defined($database); + while (my ($key,$val) = each %$params) { + push @args,"$key=$val"; + } + return join(" ",@args); +} + +# +# Copied from PosgresNode.pm passing explicit connect-string instead of +# constructed from object +# + +sub psql +{ + # We expect dbname to be part of connstr + my ($connstr, $sql, %params) = @_; + + my $stdout = $params{stdout}; + my $stderr = $params{stderr}; + my $timeout = undef; + my $timeout_exception = 'psql timed out'; + my @psql_params = + ('psql', '-XAtq', '-d', $connstr, '-f', '-'); + + # If the caller wants an array and hasn't passed stdout/stderr + # references, allocate temporary ones to capture them so we + # can return them. Otherwise we won't redirect them at all. + if (wantarray) + { + if (!defined($stdout)) + { + my $temp_stdout = ""; + $stdout = \$temp_stdout; + } + if (!defined($stderr)) + { + my $temp_stderr = ""; + $stderr = \$temp_stderr; + } + } + + $params{on_error_stop} = 1 unless defined $params{on_error_stop}; + $params{on_error_die} = 0 unless defined $params{on_error_die}; + + push @psql_params, '-v', 'ON_ERROR_STOP=1' if $params{on_error_stop}; + push @psql_params, @{ $params{extra_params} } + if defined $params{extra_params}; + + $timeout = + IPC::Run::timeout($params{timeout}, exception => $timeout_exception) + if (defined($params{timeout})); + + ${ $params{timed_out} } = 0 if defined $params{timed_out}; + + # IPC::Run would otherwise append to existing contents: + $$stdout = "" if ref($stdout); + $$stderr = "" if ref($stderr); + + my $ret; + + # Run psql and capture any possible exceptions. If the exception is + # because of a timeout and the caller requested to handle that, just return + # and set the flag. Otherwise, and for any other exception, rethrow. + # + # For background, see + # http://search.cpan.org/~ether/Try-Tiny-0.24/lib/Try/Tiny.pm + do + { + local $@; + eval { + my @ipcrun_opts = (\@psql_params, '<', \$sql); + push @ipcrun_opts, '>', $stdout if defined $stdout; + push @ipcrun_opts, '2>', $stderr if defined $stderr; + push @ipcrun_opts, $timeout if defined $timeout; + + IPC::Run::run @ipcrun_opts; + $ret = $?; + }; + my $exc_save = $@; + if ($exc_save) + { + + # IPC::Run::run threw an exception. re-throw unless it's a + # timeout, which we'll handle by testing is_expired + die $exc_save + if (blessed($exc_save) || $exc_save ne $timeout_exception); + + $ret = undef; + + die "Got timeout exception '$exc_save' but timer not expired?!" + unless $timeout->is_expired; + + if (defined($params{timed_out})) + { + ${ $params{timed_out} } = 1; + } + else + { + die "psql timed out: stderr: '$$stderr'\n" + . "while running '@psql_params'"; + } + } + }; + + if (defined $$stdout) + { + chomp $$stdout; + $$stdout =~ s/\r//g if $TestLib::windows_os; + } + + if (defined $$stderr) + { + chomp $$stderr; + $$stderr =~ s/\r//g if $TestLib::windows_os; + } + + # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR + # We don't use IPC::Run::Simple to limit dependencies. + # + # We always die on signal. + my $core = $ret & 128 ? " (core dumped)" : ""; + die "psql exited with signal " + . ($ret & 127) + . "$core: '$$stderr' while running '@psql_params'" + if $ret & 127; + $ret = $ret >> 8; + + if ($ret && $params{on_error_die}) + { + die "psql error: stderr: '$$stderr'\nwhile running '@psql_params'" + if $ret == 1; + die "connection error: '$$stderr'\nwhile running '@psql_params'" + if $ret == 2; + die "error running SQL: '$$stderr'\nwhile running '@psql_params'" + if $ret == 3; + die "psql returns $ret: '$$stderr'\nwhile running '@psql_params'"; + } + + if (wantarray) + { + return ($ret, $$stdout, $$stderr); + } + else + { + return $ret; + } +} + +sub psql_conninfo { + my ($connstr) = shift; + my ($timed_out); + my ($retcode,$stdout,$stderr)=psql($connstr,'\conninfo', + timed_out=>\$timed_out); + if ($retcode==0 && $stdout =~ /on host "([^"]*)" at port "([^"]*)"/s) { + return "$1:$2"; + } else { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} + +sub psql_server_addr { + my ($connstr) = shift; + my ($timed_out); + my $sql = "select abbrev(inet_server_addr()) ||':'||inet_server_port();\n"; + my ($retcode,$stdout,$stderr)=psql($connstr,$sql, + timed_out=>\$timed_out); + if ($retcode==0 ) { + return $stdout; + } else { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} +my $conninfo; +diag("master is".get_host_port($node_master)); +diag("slave 1 is".get_host_port($node_standby_1)); +diag("slave 2 is".get_host_port($node_standby_2)); + +# +# Test 0 parsing invalid connection string +# + +$conninfo=psql_conninfo(multiconnstring([$node_master,$node_standby_1, +$node_standby_2],undef,{target_server_type=>"foo"})); + +is($conninfo,"STDOUT:\nSTDERR:psql: invalid target_server_type value: \"foo\" should be \"any\" or \"master\"","invalid target_server_type_value"); + +# Test 1.1 - all hosts available, master first, readwrite requested + $conninfo=psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2])); + is($conninfo,get_host_port($node_master),"master first, rw, conninfo"); +# Test 1.2 + $conninfo=psql_server_addr(multiconnstring([$node_master,$node_standby_1,$node_standby_2])); + is($conninfo,get_host_port($node_master),"master first, rw, server funcs"); + +# Test 2.1 - use symbolic name for master and IP for slave + $conninfo=psql_conninfo("postgresql://localhost:".$node_master->port. + ",127.0.0.1:".$node_standby_1->port."/postgres"); + + is($conninfo,"localhost:".$node_master->port, "master symbolic, rw, conninfo"); +# Test 2.2 - check server-side connect info (would return numeric IP) + $conninfo=psql_server_addr("postgresql://localhost:".$node_master->port. + ",127.0.0.1:".$node_standby_1->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,'master symbolic, rw server funcs'); + +# Test 3.1 - all nodes available, master second, readwrite requested + $conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + + is($conninfo,get_host_port($node_master),"master second,rw, conninfo" ); +# Test 3.2 Check server-side connection info + $conninfo=psql_server_addr(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + + is($conninfo,get_host_port($node_master),"master second, rw, server funcs"); +# Test 4.1 - use symbolic name for slave and IP for smaster + $conninfo=psql_conninfo("postgresql://localhost:".$node_standby_1->port. + ",127.0.0.1:".$node_master->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,"slave symbolic, rw,conninfo"); + +# Test 4.2 - check server-side connect info + $conninfo=psql_server_addr("postgresql://localhost:".$node_standby_1->port. + ",127.0.0.1:".$node_master->port."/postgres"); + is($conninfo,"127.0.0.1:".$node_master->port,"slave symbolic rw, server funcs"); + +# Test 5 - all nodes available, master first, readonly requested + + $conninfo=psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2],undef,{target_server_type=>"any"})); + + is($conninfo,get_host_port($node_master),"master first, ro, conninfo"); + +# Test 6 - all nodes available, master second, readonly requested + $conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2],undef,{target_server_type=>"any"})); + + is($conninfo,get_host_port($node_standby_1),"master second, ro conninfo"); + +# Test 7.1 - all nodes available, random order, readonly. +# Expect that during six attempts any of three nodes would be collected +# at least once + +my %conncount=(); +for (my $i=0;$i<9;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{target_server_type=>'any',hostorder=>'random'})); + $conncount{$conn}++; +} +is(scalar(keys(%conncount)),3,'random order, readonly connect'); +# Test 7.2 - alternate (jdbc compatible) syntax for randomized hosts + +for (my $i=0;$i<6;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{targetServerType=>'any',loadBalanceHosts=>"true"})); + $conncount{$conn}++; +} +#diag(join(",",keys %conncount)); +is(scalar(keys %conncount),3,"alternate JDBC-compatible syntax for random order"); + +# Test 8 - all nodes available, random order, readwrite +# Expect all six connections go to the master + +%conncount = (); +for (my $i=0;$i<6;$i++) { + my $conn = psql_conninfo(multiconnstring([$node_master,$node_standby_1, + $node_standby_2],undef,{hostorder=>'random'})); + $conncount{$conn}++; +} + +is(length(keys %conncount),1,'random order, rw connect only one node'); +ok(exists $conncount{get_host_port($node_master)},'random order, rw connects master'); + +# Test 8.1 one host in URL, master +$conninfo=psql_conninfo(multiconnstring([$node_master])); +is($conninfo,get_host_port($node_master),"old behavoir compat - master"); + + +# Test 8.2 one host in URL, slave +$conninfo=psql_conninfo(multiconnstring([$node_standby_1])); +is($conninfo,get_host_port($node_standby_1),"old behavoir compat - slave"); + +# Test 9 - try to connect only slaves in rw mode + +$conninfo=psql_conninfo(multiconnstring([$node_standby_1,$node_standby_2])); +is($conninfo,"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1","cannot connect just slaves in RW mode"); + + + +# Test 10 - one of slaves is not available +$node_standby_1->stop(); + +# Test 10.1 + +$conninfo= psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + +is($conninfo,get_host_port($node_master),"first node is unavailable"); + +# Test 10.2 + +$conninfo = psql_conninfo(multiconnstring([$node_standby_2,$node_standby_1,$node_master])); + +is($conninfo,get_host_port($node_master),"first node standby, second unavailable"); + +# Test 10.3 + +$conninfo = +psql_conninfo(multiconnstring([$node_standby_1,$node_standby_2,$node_master],undef,{target_server_type=>"any"})); +is($conninfo,get_host_port($node_standby_2),"first node unavailable, second standby, readonly mode"); + +$node_standby_1->start(); + +$node_master->stop(); + +$conninfo= psql_conninfo(multiconnstring([$node_standby_1,$node_master,$node_standby_2])); + +is($conninfo,"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1","master unavialble, cannot connect just slaves in RW mode"); + +$conninfo= psql_conninfo(multiconnstring([$node_master,$node_standby_1,$node_standby_2],undef,{target_server_type=>"any"})); + +is($conninfo,get_host_port($node_standby_1),"Master unavailable, read only "); + +$node_master->start(); + +# Test 11 Alternate syntax + +$conninfo = psql_conninfo(connstring2([$node_standby_1,$node_standby_2,$node_master])); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master third, rw"); + + + +$conninfo = psql_conninfo(connstring2([$node_master, $node_standby_1,$node_standby_2])); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master first, rw"); + + + +$conninfo = +psql_conninfo(connstring2([$node_standby_1,$node_standby_2,$node_master],undef, +{target_server_type => 'any'})); + +is ($conninfo, get_host_port($node_standby_1),"Alternate syntax, master third, ro"); + + + +$conninfo = psql_conninfo(connstring2([$node_master, $node_standby_1,$node_standby_2], undef,{target_server_type=>'any'})); + +is ($conninfo, get_host_port($node_master),"Alternate syntax, master first, ro"); + + +# Test 11.5 one host in URL, master +$conninfo=psql_conninfo(connstring2([$node_master])); +is($conninfo,get_host_port($node_master),"alt syntax old behavoir compat - master"); + + +# Test 11.6 one host in URL, slave +$conninfo=psql_conninfo(connstring2([$node_standby_1])); +is($conninfo,get_host_port($node_standby_1),"alt syntax old behavoir compat - slave"); + + + diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/pl/plpgsql/src/plpgsql.h b/src/pl/plpgsql/src/plpgsql.h index b416e50..709c2b4 100644 --- a/src/pl/plpgsql/src/plpgsql.h +++ b/src/pl/plpgsql/src/plpgsql.h @@ -351,6 +351,7 @@ typedef struct PLpgSQL_arrayelem typedef struct PLpgSQL_nsitem { int itemtype; + /* * For labels, itemno is a value of enum PLpgSQL_label_types. For other * itemtypes, itemno is the associated PLpgSQL_datum's dno. @@ -748,7 +749,7 @@ typedef struct PLpgSQL_stmt_execsql int lineno; PLpgSQL_expr *sqlstmt; bool mod_stmt; /* is the stmt INSERT/UPDATE/DELETE? Note: - mod_stmt is set when we plan the query */ + * mod_stmt is set when we plan the query */ bool into; /* INTO supplied? */ bool strict; /* INTO STRICT flag */ PLpgSQL_rec *rec; /* INTO target, if record */ diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index fede1e6..c4917dd 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -392,6 +392,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -424,7 +425,11 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp} ) { + print $conf "listen_addresses = '$test_localhost'\n"; + } else { + print $conf "listen_addresses = ''\n"; + } } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-08 14:44  Aleksander Alekseev <a.alekseev@postgrespro.ru>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Aleksander Alekseev @ 2016-09-08 14:44 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

Hello, Victor.

> I'm sending new version of patch.
> 
> I've replaced readonly option with target_server_type (with JDBC
> compatibility alias targetServerType), 
> 
> use logic of setting defaults based on number of hosts in the connect
> string instead of complicated condition in the state machine,
> 
> added checks for return values of memory allocation function.
> 
> Also, I've solved pg_usleep problem by linking pgsleep.c into libpq
> along with some other libpgport objects which are already linked there.
> 
> Thus client applications don't need to link with libpgport and libpq
> shared library is self-containted.

This patch doesn't apply to master branch:

```
$ git apply ~/temp/libpq-failover-8.patch
/home/eax/temp/libpq-failover-8.patch:184: trailing whitespace.
check: 
/home/eax/temp/libpq-failover-8.patch:252: trailing whitespace.
	/* 
/home/eax/temp/libpq-failover-8.patch:253: trailing whitespace.
	 *  Validate target_server_mode option 
/home/eax/temp/libpq-failover-8.patch:254: trailing whitespace.
	 */ 
/home/eax/temp/libpq-failover-8.patch:306: trailing whitespace.
			appendPQExpBuffer(&conn->errorMessage, 
error: src/interfaces/libpq/t/001-multihost.pl: already exists in
working directory

$ git diff
```

-- 
Best regards,
Aleksander Alekseev


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-08 14:48  Aleksander Alekseev <a.alekseev@postgrespro.ru>
  parent: Aleksander Alekseev <a.alekseev@postgrespro.ru>
  0 siblings, 0 replies; 165+ messages in thread

From: Aleksander Alekseev @ 2016-09-08 14:48 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org

> Hello, Victor.
> 
> > I'm sending new version of patch.
> > 
> > I've replaced readonly option with target_server_type (with JDBC
> > compatibility alias targetServerType), 
> > 
> > use logic of setting defaults based on number of hosts in the connect
> > string instead of complicated condition in the state machine,
> > 
> > added checks for return values of memory allocation function.
> > 
> > Also, I've solved pg_usleep problem by linking pgsleep.c into libpq
> > along with some other libpgport objects which are already linked there.
> > 
> > Thus client applications don't need to link with libpgport and libpq
> > shared library is self-containted.
> 
> This patch doesn't apply to master branch:
> 
> ```
> $ git apply ~/temp/libpq-failover-8.patch
> /home/eax/temp/libpq-failover-8.patch:184: trailing whitespace.
> check: 
> /home/eax/temp/libpq-failover-8.patch:252: trailing whitespace.
> 	/* 
> /home/eax/temp/libpq-failover-8.patch:253: trailing whitespace.
> 	 *  Validate target_server_mode option 
> /home/eax/temp/libpq-failover-8.patch:254: trailing whitespace.
> 	 */ 
> /home/eax/temp/libpq-failover-8.patch:306: trailing whitespace.
> 			appendPQExpBuffer(&conn->errorMessage, 
> error: src/interfaces/libpq/t/001-multihost.pl: already exists in
> working directory
> 
> $ git diff
> ```

Oops. Sorry, my mistake. I forgot to check for untracked files.
Everything is fine.

-- 
Best regards,
Aleksander Alekseev


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-09 05:50  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-09-09 05:50 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; Aleksander Alekseev <a.alekseev@postgrespro.ru>; +Cc: pgsql-hackers <pgsql-hackers@postgresql.org>

On Wed, Sep 7, 2016 at 7:26 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> No, algorithm here is more complicated. It must ensure that there would
> not be second attempt to connect to host, for which unsuccessful
> connection attempt was done. So, there is list rearrangement.
>Algorithm for pick random list element by single pass is quite trivial.

If concern is only about excluding address which was tried previously. Then
I think we can try this way, randomly permute given address list (for
example fisher-yates shuffle) before trying any of those address in it.
After that you can treat the new list exactly like we do for sequential
connections. I think this makes code less complex.
-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-09 08:49  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-09-09 08:49 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Fri, 9 Sep 2016 11:20:59 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> If concern is only about excluding address which was tried
> previously. Then I think we can try this way, randomly permute given
> address list (for example fisher-yates shuffle) before trying any of
> those address in it. After that you can treat the new list exactly
> like we do for sequential connections. I think this makes code less
> complex.

Random permutation is much more computationally complex than random
picking. 

Alexander suggests to use other random pick algorithm than I use.

I use algorithm which works with lists of unknown length and chooses
line of such list with equal probability. This algorithm requires one
random number for each element of the list, but we are using C library
rand function which uses quite cheap linear congruental pseudo random
numbers, so random number generation is infinitely cheap than network
connection attempt.

As this algorithm doesn't need beforehand knowledge of the list length,
it is easy to wrap this algorithm into loop, which modifies the list,
moving already tried elements out of scope of next picking.
(it is really quite alike fisher-yates algorithm).

Alexander suggests to store somewhere number of elements of the list,
than generate one random number and pick element with this number.

Unfortunately, it doesn't save much effort in the linked list.
At average we'll need to scan half of the list to find desired element.
So, it is O(N) anyway.

Now, the main point is that we have two different timeframes of
operation.

1. Attempt to connect. It is short period, and we can assume that state
of servers doesn't change. So if, server is down, we should ignore it
until the end of this attempt to connect.

2. Attempt to failover. If no good candidate was found, we might need
to retry connection until one of standbys would be promoted to master
(with targetServerType=master) or some host comes up. See documentation
of failover_timeout configuration parameter.

It means that we cannot just throw away those hosts from list which
didn't respond during this connect attempt.
 
So, using random permutation instead  of random pick wouln't help.
And keeping somewhere number of elements in the list wouldn't help
either unless we change linked list to completely different data
structure which allows random access.
-- 




-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-13 18:58  Robert Haas <robertmhaas@gmail.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-09-13 18:58 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Fri, Sep 9, 2016 at 4:49 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> Random permutation is much more computationally complex than random
> picking.

It really isn't.  The pseudocode given at
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle is all of 4
lines long, and one of those lines is a comment.  The C implementation
is longer, but not by much.

Mind you, I haven't read the patch, so I don't know whether using
something like this would make the code simpler or more complicated.
However, if the two modes of operation are (1) try all hosts in random
order and (2) try all hosts in the listed order, it's worth noting
that the code for the second thing can be used to implement the first
thing just by shuffling the list before you begin.

> So, using random permutation instead  of random pick wouln't help.
> And keeping somewhere number of elements in the list wouldn't help
> either unless we change linked list to completely different data
> structure which allows random access.

Is there a good reason not to use an array rather than a linked list?

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-25 12:01  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-09-25 12:01 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

I have some more comments on libpq-failover-8.patch

+ /* FIXME need to check that port is numeric */

Is this still applicable?.

1)

+ /*

+ * if there is more than one host in the connect string and

+ * target_server_type is not specified explicitely, set

+ * target_server_type to "master"

+ */

I think we need comments to know why we change default value based on
number of elements in connection string. why default in not “any" when node
count > 1.


2)

+ /* loop over all the host specs in the node variable */

+ for (node = nodes; node->host != NULL || node->port != NULL; node++)

  {

I think instead of loop if we can move these code into a separate function say
pg_add_to_addresslist(host, port, &addrs) this helps in removing temp
variables like "struct node info” and several heap calls around it.


3)

+static char *

+get_port_from_addrinfo(struct addrinfo * ai)

+{

+ char port[6];

+

+ sprintf(port, "%d", htons(((struct sockaddr_in *)
ai->ai_addr)->sin_port));

+ return strdup(port);

+}

Need some comments for this function.

We use strdup in many places no where we handle memory allocation failure.


4)

+ /*

+ * consult connection options and check if RO connection is OK RO

+ * connection is OK if readonly connection is explicitely

+ * requested or if replication option is set, or just one host is

+ * specified in the connect string.

+ */

+ if (conn->pghost == NULL || !conn->target_server_type ||

+ strcmp(conn->target_server_type, "any") == 0)

Comments not in sink with code.

On Wed, Sep 14, 2016 at 12:28 AM, Robert Haas <robertmhaas@gmail.com> wrote:

> On Fri, Sep 9, 2016 at 4:49 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> > Random permutation is much more computationally complex than random
> > picking.
>
> It really isn't.  The pseudocode given at
> https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle is all of 4
> lines long, and one of those lines is a comment.  The C implementation
> is longer, but not by much.
>
> Mind you, I haven't read the patch, so I don't know whether using
> something like this would make the code simpler or more complicated.
> However, if the two modes of operation are (1) try all hosts in random
> order and (2) try all hosts in the listed order, it's worth noting
> that the code for the second thing can be used to implement the first
> thing just by shuffling the list before you begin.
>
> > So, using random permutation instead  of random pick wouln't help.
> > And keeping somewhere number of elements in the list wouldn't help
> > either unless we change linked list to completely different data
> > structure which allows random access.
>
> Is there a good reason not to use an array rather than a linked list?
>
> --
> Robert Haas
> EnterpriseDB: http://www.enterprisedb.com
> The Enterprise PostgreSQL Company
>
>
> --
> Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-hackers
>



-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-27 09:19  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Victor Wagner @ 2016-09-27 09:19 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Sun, 25 Sep 2016 17:31:53 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> I have some more comments on libpq-failover-8.patch
> 
> + /* FIXME need to check that port is numeric */
> 
> Is this still applicable?.
> 

Unfortunately, it was. I've fixed this problem in 9-th version of patch
(attached)
> 
> I think we need comments to know why we change default value based on
> number of elements in connection string. why default in not “any"
> when node count > 1.

Fixed.

> 
> + /* loop over all the host specs in the node variable */
> 
> + for (node = nodes; node->host != NULL || node->port != NULL; node++)
> 
>   {
> 
> I think instead of loop if we can move these code into a separate
> function say pg_add_to_addresslist(host, port, &addrs) this helps in
> removing temp variables like "struct node info” and several heap
> calls around it.

For some reason DNS resolving was concentrated in one place before my
changes. So, I've tried to not change this decision.

 
> 3)
> 
> +static char *
> 
> +get_port_from_addrinfo(struct addrinfo * ai)
> 
> 
> Need some comments for this function.

Done.
 
> We use strdup in many places no where we handle memory allocation
> failure.

Added some more memory allocation error checks.
> 
> Comments not in sink with code.

Fixed.

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-9.patch (text/x-patch, 46.1K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..f0df877 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal> upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + <literaL>any</literal>, connection to standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in connect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7303,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..815a827 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..d9c18b7 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -888,7 +901,21 @@ connectOptions2(PGconn *conn) if (!conn->client_encoding_initial) goto oom_error; } - + /* + * Validate target_server_mode option + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in @@ -1173,6 +1200,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1419,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1471,162 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + + /* Host has explicitely specified port */ + char *nptr; + /* Check if port is numeric */ + for (nptr=r+1;nptr<q;nptr++) { + if (*nptr<'0' ||*nptr >'9') { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Port is not numeric")); + conn->options_valid = false; + goto connect_errReturn; + } + } + /* Allocate memory for port string */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].port, r + 1, q - r); + nodes[nodecount].port[q - r - 1] = 0; + + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitely, set + * target_server_type to "master", because default mode of + * operation is failover, and so, we need to connect to RW + * host, and keep other nodes of the cluster in the connect + * string just in case master would fail and one of standbys + * would be promoted to master. + * + * If we want to loadbalance readonly queries, set + * target_server_type = "any" explicitely + * + * But global default is "any" because if there is only one + * host in the connect string, we want backward-compatible + * behavoir. + */ + conn->target_server_type = strdup("master"); + if (conn->target_server_type == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1636,104 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + nodes->port = strdup(portstr); + if (nodes->port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1746,27 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1521,6 +1784,22 @@ connect_errReturn: return 0; } +/* + * This function is used to convert integer port number from the + * addrinfo structure back into string representation, because function + * PQport needs to return string representation of port. + */ + +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + /* allocation failure must be cheked by caller */ + return strdup(port); +} + /* * connectDBComplete @@ -1603,6 +1882,117 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char + *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator in case if nobody have done it + * before. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +2070,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +2109,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +2129,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2139,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2150,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2197,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2273,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2292,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2338,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +2989,21 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +3015,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +3047,133 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * Connection to readonly host is allowed if + * taget_server_type is set to 'any' or is not exlicitely + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now. but first make a copy + * of name of host we are connected to or it would be freed + * with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3464,17 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3490,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3522,27 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4529,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4650,33 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4808,87 +5396,126 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5645,22 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5875,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; @@ -5352,7 +6010,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +6032,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index be6c370..d268453 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +387,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index afbdb63..77f94ef 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -398,6 +398,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -431,7 +432,11 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp} ) { + print $conf "listen_addresses = '$test_localhost'\n"; + } else { + print $conf "listen_addresses = ''\n"; + } } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-29 18:15  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-09-29 18:15 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers <pgsql-hackers@postgresql.org>

This patch do not apply on latest code. it fails as follows
libpq-failover-9.patch:176: trailing whitespace.
thread.o pgsleep.o
libpq-failover-9.patch:184: trailing whitespace.
check:
libpq-failover-9.patch:185: trailing whitespace.
$(prove_check)
libpq-failover-9.patch:186: trailing whitespace.

libpq-failover-9.patch:194: trailing whitespace.
rm -rf tmp_check
error: patch failed: doc/src/sgml/libpq.sgml:792
error: doc/src/sgml/libpq.sgml: patch does not apply
error: patch failed: src/interfaces/libpq/Makefile:36
error: src/interfaces/libpq/Makefile: patch does not apply
error: patch failed: src/interfaces/libpq/fe-connect.c:299
error: src/interfaces/libpq/fe-connect.c: patch does not apply
error: patch failed: src/interfaces/libpq/libpq-fe.h:62
error: src/interfaces/libpq/libpq-fe.h: patch does not apply
error: patch failed: src/interfaces/libpq/libpq-int.h:334
error: src/interfaces/libpq/libpq-int.h: patch does not apply
error: patch failed: src/interfaces/libpq/test/expected.out:1
error: src/interfaces/libpq/test/expected.out: patch does not apply
error: patch failed: src/test/perl/PostgresNode.pm:398
error: src/test/perl/PostgresNode.pm: patch does not apply


On Tue, Sep 27, 2016 at 2:49 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:
1).
>* if there is more than one host in the connect string and
>* target_server_type is not specified explicitely, set
>* target_server_type to "master", because default mode of
>* operation is failover, and so, we need to connect to RW
>* host, and keep other nodes of the cluster in the connect
>* string just in case master would fail and one of standbys
>* would be promoted to master.

I am slightly confused. As per this target_server_type=master means user is
expecting failover. What if user pass target_server_type=any and request
sequential connection isn't this also a case for failover?.  I think by
default it should be "any" for any number of hosts. And parameter
"sequential and random will decide whether we want just failover or with
load-balance.

2).

>For some reason DNS resolving was concentrated in one place before my
>changes. So, I've tried to not change this decision.

My intention was not to have a replacement function for
"pg_getaddrinfo_all", I just suggested to

have a local function which call pg_getaddrinfo_all for every host, port
pair read earlier. By this way we need not to maintain nodes struct. This
also reduces complexity of connectDBStart.

FUNC (host, port, addrs)

{

    CALL pg_getaddrinfo_all(host, port, newaddrs);

   addrs-> ai_next = newaddrs;

}

3).

I think you should run a spellcheck once. And, there are some formatting
issue with respect to comments and curly braces of controlled blocks which
need to be fixed.
-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-09-30 08:44  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Victor Wagner @ 2016-09-30 08:44 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Thu, 29 Sep 2016 23:45:52 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> This patch do not apply on latest code. it fails as follows

It's strange. I have no problems applying it to commit
fd321a1dfd64d30

Ok, some trailing whitespace and mixing of tabs and spaces
which git apply doesn't like really present in the patch.

I'm attached hear version with these issues resolved.

 
> I am slightly confused. As per this target_server_type=master means
> user is expecting failover. What if user pass target_server_type=any
> and request sequential connection isn't this also a case for
> failover?.  I think by default it should be "any" for any number of
> hosts. And parameter "sequential and random will decide whether we
> want just failover or with load-balance.

I don't agree with this. In the first versions of the patch it refuses 
connect to readonly server even if it is only one, because I think that
read-write connection is what user typically expect.

When user tries to connect to cluster (specifying many hosts in the
connect string), it can be by default assumed that he wants master. 

But backward compatibility is more
important thing, so I now assume, that user tries to connect just one
node, and this node is read only, user knows what he is doing.

 

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-9.patch (text/x-patch, 46.0K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..f0df877 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -942,8 +963,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal> upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + <literaL>any</literal>, connection to standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in connect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7303,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..815a827 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..d9c18b7 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -888,7 +901,21 @@ connectOptions2(PGconn *conn) if (!conn->client_encoding_initial) goto oom_error; } - + /* + * Validate target_server_mode option + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in @@ -1173,6 +1200,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1419,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1471,162 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + while (*p) + { + q = p; + r = NULL; + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + + /* Host has explicitely specified port */ + char *nptr; + /* Check if port is numeric */ + for (nptr=r+1;nptr<q;nptr++) { + if (*nptr<'0' ||*nptr >'9') { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Port is not numeric")); + conn->options_valid = false; + goto connect_errReturn; + } + } + /* Allocate memory for port string */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].port, r + 1, q - r); + nodes[nodecount].port[q - r - 1] = 0; + + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + /* skip a comma */ + if (*q) + q++; + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + p = q; + } + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitely, set + * target_server_type to "master", because default mode of + * operation is failover, and so, we need to connect to RW + * host, and keep other nodes of the cluster in the connect + * string just in case master would fail and one of standbys + * would be promoted to master. + * + * If we want to loadbalance readonly queries, set + * target_server_type = "any" explicitely + * + * But global default is "any" because if there is only one + * host in the connect string, we want backward-compatible + * behavoir. + */ + conn->target_server_type = strdup("master"); + if (conn->target_server_type == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1636,104 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + nodes->port = strdup(portstr); + if (nodes->port == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + free(nodes); + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1746,27 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1521,6 +1784,22 @@ connect_errReturn: return 0; } +/* + * This function is used to convert integer port number from the + * addrinfo structure back into string representation, because function + * PQport needs to return string representation of port. + */ + +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + /* allocation failure must be cheked by caller */ + return strdup(port); +} + /* * connectDBComplete @@ -1603,6 +1882,117 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char + *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator in case if nobody have done it + * before. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } + +} + /* ---------------- * PQconnectPoll * @@ -1680,7 +2070,8 @@ PQconnectPoll(PGconn *conn) case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: break; - + case CONNECTION_CHECK_RW: + break; default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,9 +2109,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } appendPQExpBuffer(&conn->errorMessage, @@ -1739,7 +2129,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2139,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2150,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2197,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2273,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2292,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2338,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +2989,21 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +3015,9 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + } case CONNECTION_SETENV: @@ -2645,9 +3047,133 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * Connection to readonly host is allowed if + * taget_server_type is set to 'any' or is not exlicitely + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now. but first make a copy + * of name of host we are connected to or it would be freed + * with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + } + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3464,17 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3490,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3522,27 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4529,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4650,33 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4808,87 +5396,126 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, */ p = start; } - - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5645,22 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5875,22 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + + } option->val = value_copy; return option; @@ -5352,7 +6010,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +6032,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index be6c370..d268453 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +387,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index afbdb63..77f94ef 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -398,6 +398,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -431,7 +432,11 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp} ) { + print $conf "listen_addresses = '$test_localhost'\n"; + } else { + print $conf "listen_addresses = ''\n"; + } } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-03 00:50  Michael Paquier <michael.paquier@gmail.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 0 replies; 165+ messages in thread

From: Michael Paquier @ 2016-10-03 00:50 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL mailing lists <pgsql-hackers@postgresql.org>

On Fri, Sep 30, 2016 at 5:44 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> But backward compatibility is more
> important thing, so I now assume, that user tries to connect just one
> node, and this node is read only, user knows what he is doing.

Moved this patch to next CF.

(Note that I am in CF-vacuuming mode this morning, I'll try to close it asap.)
-- 
Michael


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-13 07:00  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-10-13 07:00 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers <pgsql-hackers@postgresql.org>

On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru> wrote:
>Ok, some trailing whitespace and mixing of tabs and spaces
>which git apply doesn't like really present in the patch.
>I'm attached hear version with these issues resolved.

There were some more trailing spaces and spaces used for tabs in patch 09.
I have fixed same along with formatting issues related to comments and { of
controlled blocks.

>But backward compatibility is more important thing, so I now assume, that
user tries to connect just onenode, and this node is read only, user knows
>what he is doing.
Okay but for me consistency is also important. Since we agree to disagree
on some of the comments and others have not expressed any problem I am
moving it to committer.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-10.patch (application/octet-stream, 46.4K) download commit 52270559f28ab673e14124b813b7cdfb772cd1bd Author: mithun <mithun@localhost.localdomain> Date: Thu Oct 13 12:07:15 2016 +0530 libpq10 diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..fd2fa88 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be serveral host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connect string. In this case these hosts would be considered + alternate entries into same database and if connect to first one + fails, library would try to connect second etc. This can be used + for high availability cluster or for load balancing. See + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + Network host name can be accompanied with port number, separated by + colon. If so, this port number is used only when connected to + this host. If there is no port number, port specified in the + <xref linkend="libpq-connect-port"> parameter would be used. + </para> </listitem> </varlistentry> @@ -943,7 +964,43 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose host from list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If value of this argument is <literal>sequential</literal> (the + default) library connects to the hosts in order they specified, + and tries to connect second one only if connection to the first + fails. + </para> + <para> + If value is <literal>random</literal> host to connect is randomly + picked from the list. It allows to balance load between several + cluster nodes. However, currently PostgreSQL doesn't support + multimaster clusters. So, without use of third-party products, + only read-only connections can take advantage from the + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal> upon successful connection + library checks if host is in recovery state, and if it is so, + tries next host in the connect string. If this parameter is + <literaL>any</literal>, connection to standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in connect string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of standby nodes to the new master. + So clients which notice that connect to the master fails, can + already give up attempt to reestablish a connection when new master + became available. + </para> + <para> + Setting this parameter to reasonable time makes library try to + reconnect all the host in cyclically until new master appears. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7303,18 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option present in the section of service file, it + is interpeted as alternate servers for failover or load-balancing. See + <xref linkend="libpq-connect-host"> option in the connect string. + </para> + <para> + For all other options first value takes precedence over later ones. + </para> + <para> + Options, specified in the connect string along with service option + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..4c14cc5 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..3bc58a1 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -890,6 +903,21 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1173,6 +1201,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1420,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1472,184 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records. + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + while (*p) + { + q = p; + r = NULL; + + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + char *nptr; + + /* Check if port is numeric */ + for (nptr=r+1;nptr<q;nptr++) + { + if (*nptr<'0' ||*nptr >'9') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Port is not numeric")); + conn->options_valid = false; + goto connect_errReturn; + } + } + + /* Allocate memory for port string */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].port, r + 1, q - r); + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + + /* skip a comma */ + if (*q) + q++; + + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + p = q; + } + + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitely, set + * target_server_type to "master", because default mode of + * operation is failover, and so, we need to connect to RW + * host, and keep other nodes of the cluster in the connect + * string just in case master would fail and one of standbys + * would be promoted to master. + * + * If we want to loadbalance readonly queries, set + * target_server_type = "any" explicitely + * + * But global default is "any" because if there is only one + * host in the connect string, we want backward-compatible + * behavoir. + */ + conn->target_server_type = strdup("master"); + if (conn->target_server_type == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1659,113 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + + nodes->port = strdup(portstr); + if (nodes->port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + + free(nodes); + + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1778,26 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1521,6 +1815,23 @@ connect_errReturn: return 0; } +/* + * This function is used to convert integer port number from the + * addrinfo structure back into string representation, because function + * PQport needs to return string representation of port. + */ + +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + + /* allocation failure must be checked by caller */ + return strdup(port); +} + /* * connectDBComplete @@ -1603,6 +1914,118 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator in case if nobody have done it + * before. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } +} + /* ---------------- * PQconnectPoll * @@ -1681,6 +2104,9 @@ PQconnectPoll(PGconn *conn) case CONNECTION_NEEDED: break; + case CONNECTION_CHECK_RW: + break; + default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,11 +2144,11 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not create socket: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -1739,7 +2165,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2175,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2186,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2233,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2309,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2328,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2374,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +3025,22 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +3052,8 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; } case CONNECTION_SETENV: @@ -2645,9 +3083,141 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * Connection to readonly host is allowed if + * taget_server_type is set to 'any' or is not exlicitely + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now. but first make a copy + * of name of host we are connected to or it would be freed + * with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + } + + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3508,16 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3533,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3565,29 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4574,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4695,38 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + + if (options[i].val) + { + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + } + + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4809,86 +5447,127 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, p = start; } - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5697,21 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5926,21 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + } option->val = value_copy; return option; @@ -5352,7 +6060,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +6082,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index be6c370..d268453 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +387,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index 535d6c0..5472818 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -398,6 +398,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -432,7 +433,10 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp}) + print $conf "listen_addresses = '$test_localhost'\n"; + else + print $conf "listen_addresses = ''\n"; } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-13 09:53  Victor Wagner <vitus@wagner.pp.ru>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Victor Wagner @ 2016-10-13 09:53 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Thu, 13 Oct 2016 12:30:59 +0530
Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
> wrote:

> Okay but for me consistency is also important. Since we agree to
> disagree on some of the comments and others have not expressed any
> problem I am moving it to committer.


Thank you for your efforts improving my patch



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-19 16:04  Robert Haas <robertmhaas@gmail.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-10-19 16:04 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Oct 13, 2016 at 5:53 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Thu, 13 Oct 2016 12:30:59 +0530
> Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
>> wrote:
>> Okay but for me consistency is also important. Since we agree to
>> disagree on some of the comments and others have not expressed any
>> problem I am moving it to committer.
>
> Thank you for your efforts improving my patch

I haven't deeply reviewed this patch, but on a quick read-through it
certainly seems to need a lot of cleanup work.

+      <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder">
+      <term><literal>hostorder</literal></term>
+      <listitem>

I don't think that putting everything at the same indentation level
matches the style of the surrounding documentation.

@@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       </para>
       </listitem>
      </varlistentry>
-
      <varlistentry id="libpq-connect-connect-timeout"
xreflabel="connect_timeout">
       <term><literal>connect_timeout</literal></term>
       <listitem>

Spurious hunk.

+                /* Host has explicitely specified port */

Spelling.  This same error is repeated elsewhere.

+                /* Check if port is numeric */
+                for (nptr=r+1;nptr<q;nptr++)
+                {
+                    if (*nptr<'0' ||*nptr >'9')

Formatting.  Consider using pgindent to get this into correct PostgreSQL style.

+             * behavoir.

Spelling.

+ * the beginning (and putting its addres into given pointer.

Spelling.

+ *    Returns 1 if address is choosen and 0 if there are no more addresses

Spelling.

+         * Initialize random number generator in case if nobody have done it
+         * before. Use value from rand along with time in case random number

Grammar ("in case nobody has done it already").  Also, is it really OK
for libpq to call srand() as a side effect?  I think that seems rather
unfriendly.

+             * taget_server_type is set to 'any' or is not exlicitely

Multiple spelling mistakes.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-19 17:44  Thom Brown <thom@linux.com>
  parent: Victor Wagner <vitus@wagner.pp.ru>
  1 sibling, 0 replies; 165+ messages in thread

From: Thom Brown @ 2016-10-19 17:44 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>

On 13 October 2016 at 10:53, Victor Wagner <vitus@wagner.pp.ru> wrote:
> On Thu, 13 Oct 2016 12:30:59 +0530
> Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>
>> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
>> wrote:
>
>> Okay but for me consistency is also important. Since we agree to
>> disagree on some of the comments and others have not expressed any
>> problem I am moving it to committer.
>
>
> Thank you for your efforts improving my patch

I've found various spelling and grammatical issues in the docs
section, which I've corrected.  I've attached a revised patch with
these changes.

One thing I'm wondering is whether we should be using the term
"master", as that's usually paired with "slave", whereas, nowadays,
there's a tendency to refer to them as "primary" and "standby".  I
know we use "master" in some other places in the documentation, but it
seems inconsistent to have "master" as a parameter value, but then
having "primary" used in some other configuration parameters.

I'd also avoid referring to "the library", and just describe what
happens without making reference to what's making it happen.

Regards

Thom

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments: download all (2 files, .tar.gz)

libpq-failover-10vs11.diff (text/plain, 5.8K) download 1,6d0 < commit 52270559f28ab673e14124b813b7cdfb772cd1bd < Author: mithun <mithun@localhost.localdomain> < Date: Thu Oct 13 12:07:15 2016 +0530 < < libpq10 < 8c2 < index 4e34f00..fd2fa88 100644 --- > index 4e34f00..adbad75 100644 44c38 < + There can be serveral host specifications, optionally accompanied --- > + There can be several host specifications, optionally accompanied 56,59c50,53 < + the connect string. In this case these hosts would be considered < + alternate entries into same database and if connect to first one < + fails, library would try to connect second etc. This can be used < + for high availability cluster or for load balancing. See --- > + the connection string. In this case these hosts would be considered > + alternate entries into same database and if connection to first one > + fails, the second would be attemped, and so on. This can be used > + for high availability clusters or for load balancing. See the 63,66c57,60 < + Network host name can be accompanied with port number, separated by < + colon. If so, this port number is used only when connected to < + this host. If there is no port number, port specified in the < + <xref linkend="libpq-connect-port"> parameter would be used. --- > + The network host name can be accompanied by a port number, separated by > + colon. This port number is used only when connected to > + this host. If there is no port number, the port specified in the > + <xref linkend="libpq-connect-port"> parameter would be used instead. 71c65 < @@ -943,7 +964,43 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname --- > @@ -943,7 +964,42 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname 79c73 < + Specifies how to choose host from list of alternate hosts, --- > + Specifies how to choose the host from the list of alternate hosts, 83,86c77,79 < + If value of this argument is <literal>sequential</literal> (the < + default) library connects to the hosts in order they specified, < + and tries to connect second one only if connection to the first < + fails. --- > + If the value of this argument is <literal>sequential</literal> (the > + default) connections to the hosts will be attempted in the order in > + which they are specified. 89,93c82,86 < + If value is <literal>random</literal> host to connect is randomly < + picked from the list. It allows to balance load between several < + cluster nodes. However, currently PostgreSQL doesn't support < + multimaster clusters. So, without use of third-party products, < + only read-only connections can take advantage from the --- > + If the value is <literal>random</literal>, the host to connect to > + will be randomly picked from the list. It allows load balacing between > + several cluster nodes. However, PostgreSQL doesn't currently support > + multimaster clusters. So, without the use of third-party products, > + only read-only connections can take advantage from 102,104c95,97 < + If this parameter is <literal>master</literal> upon successful connection < + library checks if host is in recovery state, and if it is so, < + tries next host in the connect string. If this parameter is --- > + If this parameter is <literal>master</literal>, upon successful connection > + the host is checked to determine whether it is in a recovery state. If it > + is, it then tries next host in the connection string. If this parameter is 115c108 < @@ -985,7 +1042,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname --- > @@ -985,7 +1041,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname 123c116 < @@ -996,7 +1052,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname --- > @@ -996,7 +1051,28 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname 132c125 < + Maximum time to cyclically retry all the hosts in connect string. --- > + Maximum time to cyclically retry all the hosts in the connection string. 138,141c131,134 < + take some time to promote one of standby nodes to the new master. < + So clients which notice that connect to the master fails, can < + already give up attempt to reestablish a connection when new master < + became available. --- > + take some time to promote one of the standby nodes to the new master. > + So clients which detect failure to connect to the master might > + abandon attempts to reestablish a connection before the new master > + becomes available. 144,145c137,139 < + Setting this parameter to reasonable time makes library try to < + reconnect all the host in cyclically until new master appears. --- > + Setting this parameter to a value that takes into account the amount of > + time needed for failover to complete will ensure attempts to connect > + to hosts continue to be made until the new master becomes available. 152c146 < @@ -7227,6 +7303,18 @@ user=admin --- > @@ -7227,6 +7303,19 @@ user=admin 157,159c151,154 < + If more than one <literal>host</literal> option present in the section of service file, it < + is interpeted as alternate servers for failover or load-balancing. See < + <xref linkend="libpq-connect-host"> option in the connect string. --- > + If more than one <literal>host</literal> option is present in the same > + section of the service file, it is interpeted as alternate servers for > + failover or load-balancing. See <xref linkend="libpq-connect-host"> > + option in the connection string. 162c157 < + For all other options first value takes precedence over later ones. --- > + For all other options, the first value takes precedence over later ones. 165c160 < + Options, specified in the connect string along with service option --- > + Options specified in the connection string, along with the service option,
libpq-failover-11.patch (application/x-patch, 46.4K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..adbad75 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be several host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connection string. In this case these hosts would be considered + alternate entries into same database and if connection to first one + fails, the second would be attemped, and so on. This can be used + for high availability clusters or for load balancing. See the + <xref linkend="libpq-connect-hostorder"> parameter. + </para> + <para> + The network host name can be accompanied by a port number, separated by + colon. This port number is used only when connected to + this host. If there is no port number, the port specified in the + <xref linkend="libpq-connect-port"> parameter would be used instead. + </para> </listitem> </varlistentry> @@ -943,7 +964,42 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose the host from the list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If the value of this argument is <literal>sequential</literal> (the + default) connections to the hosts will be attempted in the order in + which they are specified. + </para> + <para> + If the value is <literal>random</literal>, the host to connect to + will be randomly picked from the list. It allows load balacing between + several cluster nodes. However, PostgreSQL doesn't currently support + multimaster clusters. So, without the use of third-party products, + only read-only connections can take advantage from + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal>, upon successful connection + the host is checked to determine whether it is in a recovery state. If it + is, it then tries next host in the connection string. If this parameter is + <literaL>any</literal>, connection to standby nodes are considered + successful. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-port" xreflabel="port"> + <term><literal>port</literal></term> <listitem> <para> @@ -985,7 +1041,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1051,28 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in the connection string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of the standby nodes to the new master. + So clients which detect failure to connect to the master might + abandon attempts to reestablish a connection before the new master + becomes available. + </para> + <para> + Setting this parameter to a value that takes into account the amount of + time needed for failover to complete will ensure attempts to connect + to hosts continue to be made until the new master becomes available. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7303,19 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option is present in the same + section of the service file, it is interpeted as alternate servers for + failover or load-balancing. See <xref linkend="libpq-connect-host"> + option in the connection string. + </para> + <para> + For all other options, the first value takes precedence over later ones. + </para> + <para> + Options specified in the connection string, along with the service option, + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..4c14cc5 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..3bc58a1 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -890,6 +903,21 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1173,6 +1201,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1420,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1472,184 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records. + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + while (*p) + { + q = p; + r = NULL; + + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitely specified port */ + char *nptr; + + /* Check if port is numeric */ + for (nptr=r+1;nptr<q;nptr++) + { + if (*nptr<'0' ||*nptr >'9') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Port is not numeric")); + conn->options_valid = false; + goto connect_errReturn; + } + } + + /* Allocate memory for port string */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].port, r + 1, q - r); + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + + /* skip a comma */ + if (*q) + q++; + + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + p = q; + } + + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitely, set + * target_server_type to "master", because default mode of + * operation is failover, and so, we need to connect to RW + * host, and keep other nodes of the cluster in the connect + * string just in case master would fail and one of standbys + * would be promoted to master. + * + * If we want to loadbalance readonly queries, set + * target_server_type = "any" explicitely + * + * But global default is "any" because if there is only one + * host in the connect string, we want backward-compatible + * behavoir. + */ + conn->target_server_type = strdup("master"); + if (conn->target_server_type == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1659,113 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + + nodes->port = strdup(portstr); + if (nodes->port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + + free(nodes); + + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1778,26 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1521,6 +1815,23 @@ connect_errReturn: return 0; } +/* + * This function is used to convert integer port number from the + * addrinfo structure back into string representation, because function + * PQport needs to return string representation of port. + */ + +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + + /* allocation failure must be checked by caller */ + return strdup(port); +} + /* * connectDBComplete @@ -1603,6 +1914,118 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo sturctures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its addres into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is choosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator in case if nobody have done it + * before. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } +} + /* ---------------- * PQconnectPoll * @@ -1681,6 +2104,9 @@ PQconnectPoll(PGconn *conn) case CONNECTION_NEEDED: break; + case CONNECTION_CHECK_RW: + break; + default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,11 +2144,11 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not create socket: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -1739,7 +2165,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2175,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2186,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2233,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2309,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2328,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2374,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +3025,22 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +3052,8 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; } case CONNECTION_SETENV: @@ -2645,9 +3083,141 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * Connection to readonly host is allowed if + * taget_server_type is set to 'any' or is not exlicitely + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now. but first make a copy + * of name of host we are connected to or it would be freed + * with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + } + + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3508,16 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3533,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3565,29 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4574,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4695,38 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + + if (options[i].val) + { + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + } + + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4809,86 +5447,127 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, p = start; } - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5697,21 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5926,21 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + } option->val = value_copy; return option; @@ -5352,7 +6060,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +6082,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index be6c370..d268453 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -382,6 +387,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -467,6 +477,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index 535d6c0..5472818 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -398,6 +398,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -432,7 +433,10 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp}) + print $conf "listen_addresses = '$test_localhost'\n"; + else + print $conf "listen_addresses = ''\n"; } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-19 22:08  Robert Haas <robertmhaas@gmail.com>
  parent: Peter Eisentraut <peter_e@gmx.net>
  2 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-10-19 22:08 UTC (permalink / raw)
  To: Peter Eisentraut <peter_e@gmx.net>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Oct 26, 2015 at 4:25 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> On 10/14/15 6:41 AM, Victor Wagner wrote:
>> 1. It is allowed to specify several hosts in the connect string, either
>> in URL-style (separated by comma) or in param=value form (several host
>> parameters).
>
> I'm not fond of having URLs that are not valid URLs according to the
> applicable standards.  Because then they can't be parsed or composed by
> standard libraries.

I did a little bit more research on this topic and found out a few
things that are interesting, at least to me.  First, our documentation
reference RFC3986.  According to RFC3986:

URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

hier-part   = "//" authority path-abempty
                  / path-absolute
                  / path-rootless
                  / path-empty

authority   = [ userinfo "@" ] host [ ":" port ]

host        = IP-literal / IPv4address / reg-name

reg-name    = *( unreserved / pct-encoded / sub-delims )

sub-delims include comma but not colon, so I think that
postgresql://host1,host2,host3/ is a perfectly good URL, and so is
postgresql://host1,host2,host3:1111/ but
postgresql://host1:1234,host2:3456/ is not a valid URL because the :
after host1 terminates the "host" portion of the URL.  The port can't
contain anything but digits, so 1234 has to be the port, but then
there's nothing to do with the portion between the comma and the
following slash, so it is indeed an invalid URI as far as I can tell.

However, PostgreSQL's JDBC driver isn't alone in supporting something
like this.  The MySQL JDBC driver does the same thing:

http://lists.mysql.com/cluster/249
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html

MongoDB refers to their connection string as a URI, but it uses
exactly this syntax:

https://docs.mongodb.com/manual/reference/connection-string/

Couchbase's syntax is also quite similar, though it's not clear that
they allow port numbers:

http://developer.couchbase.com/documentation/server/4.1/developer-guide/connecting.html

Of course, since this is a very common need and it's not obvious how
to satisfy it within the confines of the URI specification, people
have developed a variety of other answers, such as (a) multiple URIs
separated by commas, which is a terrible idea because comma can occur
*within* URIs, (b) separating multiple host names with a double-dash,
(c) including a parameter in the "query" portion of the URI to specify
alternate host names, (d) defining a new failover: URI scheme that
acts as a container for multiple connection URIs of whatever form is
normally supported, and in the case of Oracle (e) creating some
frightening monstrosity of proprietary syntax that I don't (care to)
understand.

All in all, I'm still feeling pretty good about trying to support the
same syntax that our JDBC driver already does.  It's certainly not a
perfect solution, but it is at least compatible with MySQL's JDBC
driver and with MongoDB, and in a world where everybody has picked a
different approach that's not too bad.  Hey, maybe if we use the same
syntax as MongoDB they'll let us hang out with the cool kids...

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-19 23:26  Peter van Hardenberg <pvh@pvh.ca>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Peter van Hardenberg @ 2016-10-19 23:26 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Oct 19, 2016 at 3:08 PM, Robert Haas <robertmhaas@gmail.com> wrote:

> On Mon, Oct 26, 2015 at 4:25 PM, Peter Eisentraut <peter_e@gmx.net> wrote:
> > On 10/14/15 6:41 AM, Victor Wagner wrote:
> All in all, I'm still feeling pretty good about trying to support the
> same syntax that our JDBC driver already does.  It's certainly not a
> perfect solution, but it is at least compatible with MySQL's JDBC
> driver and with MongoDB, and in a world where everybody has picked a
> different approach that's not too bad.  Hey, maybe if we use the same
> syntax as MongoDB they'll let us hang out with the cool kids...
>
>
They will never let us hang out with the cool kids. Don't worry though, the
cool kids are too busy figuring out why their cluster is out of consensus
to pay attention to much else.

Supporting different ports on different servers would be a much appreciated
feature (I can't remember if it was Kafka or Cassandra that didn't do this
and it was very annoying.)

Remember, as the connection string gets more complicated, psql supports the
Postgres URL format as a single command-line argument and we may want to
begin encouraging people to use that syntax instead.

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-20 00:15  Robert Haas <robertmhaas@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-10-20 00:15 UTC (permalink / raw)
  To: Victor Wagner <vitus@wagner.pp.ru>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Oct 19, 2016 at 12:04 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> On Thu, Oct 13, 2016 at 5:53 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
>> On Thu, 13 Oct 2016 12:30:59 +0530
>> Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>>> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
>>> wrote:
>>> Okay but for me consistency is also important. Since we agree to
>>> disagree on some of the comments and others have not expressed any
>>> problem I am moving it to committer.
>>
>> Thank you for your efforts improving my patch
>
> I haven't deeply reviewed this patch, but on a quick read-through it
> certainly seems to need a lot of cleanup work.

Some more comments:

- I am pretty doubtful that the changes to connectOptions2() work as
intended.  I think that's only going to be called before actualhost
and actualport could possibly get set.  I don't think we keep
reinvoking this function for every new host we try.

- It's pretty clear that this isn't going to work if the host list
includes a mix of hostnames and UNIX socket addresses.  The code that
handles the UNIX socket address case is totally separate from the code
that handles the multiple-hostname case.

- This creates a sort of definitional problem for functions like
PQhost().  The documentation says of this and other related functions:
"These values are fixed for the life of the PGconn object."  But with
this patch, that would no longer be true.  So at least the
documentation needs an update.  Actually, though, I think the problem
is more fundamental than that.  If the user asks for PQhost(conn), do
they want the list of all hosts, or the one to which we're currently
connected?  It might be either, depending on what they intend to do
with the information.  If they mean to construct a new connection
string, they might well want them all; but something like psql's
\conninfo only shows the current one.  There's also the question of
what "the current one" means if we're not connected to any server at
all.  I'm not sure exactly how to solve these problems, but they need
some thought.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 10:36  Thom Brown <thom@linux.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 165+ messages in thread

From: Thom Brown @ 2016-10-24 10:36 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 20 October 2016 at 01:15, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Wed, Oct 19, 2016 at 12:04 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> > On Thu, Oct 13, 2016 at 5:53 AM, Victor Wagner <vitus@wagner.pp.ru> wrote:
> >> On Thu, 13 Oct 2016 12:30:59 +0530
> >> Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> >>> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
> >>> wrote:
> >>> Okay but for me consistency is also important. Since we agree to
> >>> disagree on some of the comments and others have not expressed any
> >>> problem I am moving it to committer.
> >>
> >> Thank you for your efforts improving my patch
> >
> > I haven't deeply reviewed this patch, but on a quick read-through it
> > certainly seems to need a lot of cleanup work.
>
> Some more comments:
>
> - I am pretty doubtful that the changes to connectOptions2() work as
> intended.  I think that's only going to be called before actualhost
> and actualport could possibly get set.  I don't think we keep
> reinvoking this function for every new host we try.
>
> - It's pretty clear that this isn't going to work if the host list
> includes a mix of hostnames and UNIX socket addresses.  The code that
> handles the UNIX socket address case is totally separate from the code
> that handles the multiple-hostname case.

So should it be the case that it disallows UNIX socket addresses
entirely?  I can't imagine a list of UNIX socket addresses being that
useful.

Thom


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 11:03  Victor Wagner <vitus@wagner.pp.ru>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-10-24 11:03 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, 24 Oct 2016 11:36:31 +0100
Thom Brown <thom@linux.com> wrote:


> > - It's pretty clear that this isn't going to work if the host list
> > includes a mix of hostnames and UNIX socket addresses.  The code
> > that handles the UNIX socket address case is totally separate from
> > the code that handles the multiple-hostname case.  
> 
> So should it be the case that it disallows UNIX socket addresses
> entirely?  I can't imagine a list of UNIX socket addresses being that
> useful.

Really, patch was implemented as TCP-only from the beginning.

I know only one case, where list of UNIX sockets is useful - test suite.
I have to include modifications to PostgresNode.pm in the patch to
allow testing with TCP sockets.

Also, I can imagine that people would want include one unix socket into
list of TCP ones, i.e. one of replicas running on the same host as
application server. But patch doesn't support it. May be it should be
clarified in the documentation, that this is not supported.



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 11:09  Victor Wagner <vitus@wagner.pp.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-10-24 11:09 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Wed, 19 Oct 2016 20:15:38 -0400
Robert Haas <robertmhaas@gmail.com> wrote:

> 
> Some more comments:
> 
> - I am pretty doubtful that the changes to connectOptions2() work as
> intended.  I think that's only going to be called before actualhost
> and actualport could possibly get set.  I don't think we keep
> reinvoking this function for every new host we try.

I would investigate this. Probably test cases for .pgpass file should
be added.

 
> - It's pretty clear that this isn't going to work if the host list
> includes a mix of hostnames and UNIX socket addresses.  The code that
> handles the UNIX socket address case is totally separate from the code
> that handles the multiple-hostname case.

Muitihost feature was never intended to work with unix-domain socket. 
May be it should be clarified in the docs, or even improved error
message emitted when unix socket occurs in the multiple host list.
 
> - This creates a sort of definitional problem for functions like
> PQhost().  The documentation says of this and other related functions:
> "These values are fixed for the life of the PGconn object."  But with
> this patch, that would no longer be true.  So at least the
> documentation needs an update.  Actually, though, I think the problem

I've missed this phrase, documentation should be updated.

> is more fundamental than that.  If the user asks for PQhost(conn), do
> they want the list of all hosts, or the one to which we're currently
> connected?  It might be either, depending on what they intend to do
> with the information.  If they mean to construct a new connection
> string, they might well want them all; but something like psql's
> \conninfo only shows the current one.  There's also the question of
> what "the current one" means if we're not connected to any server at
> all.  I'm not sure exactly how to solve these problems, but they need
> some thought.

I've thought that no one would need to reconstruct connect string from
conninfo object.  May be I've missed some use cases. 

Name PQhost suggest that it'll return just one host. So, I've decided
to interpret it as  'currently choosen host'. 

If we really need function which lists all the potentially connected
hosts, it should be new function. 

I hope this would introduce no backward incompatibility, because no
existing setup uses multihost connect strings.

Thanks for your critique.

			Victor.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 15:57  Robert Haas <robertmhaas@gmail.com>
  parent: Peter van Hardenberg <pvh@pvh.ca>
  0 siblings, 3 replies; 165+ messages in thread

From: Robert Haas @ 2016-10-24 15:57 UTC (permalink / raw)
  To: Peter van Hardenberg <pvh@pvh.ca>; +Cc: Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Oct 19, 2016 at 7:26 PM, Peter van Hardenberg <pvh@pvh.ca> wrote:
> Supporting different ports on different servers would be a much appreciated
> feature (I can't remember if it was Kafka or Cassandra that didn't do this
> and it was very annoying.)
>
> Remember, as the connection string gets more complicated, psql supports the
> Postgres URL format as a single command-line argument and we may want to
> begin encouraging people to use that syntax instead.

While I was experimenting with this today, I discovered a problem of
interpretation related to IPv6 addresses.  Internally, a postgresql://
URL and a connection string are converted into the same format, so
postgresql://a,b/ means just the same thing as host=a,b.  I thought
that could similarly decide that postgresql://a:123,b:456/ is going to
get translated to host=a:123,b:456 and then there can be further code
to parse that into a list of host-and-port pairs.  However, if you do
that, then something like host=1:2:3::4:5:6 is fundamentally
ambiguous.  That :6 is equally valid either as part of the IP address
or as a trailing port number specification, and there's no a priori
way to know which it is.  Today, since the host part can't include a
port specifier, it's regarded as part of the IP address, and I think
it would probably be a bad idea to change that, as I believe Victor's
patch would.  He seems to have it in mind that we could allow things
like host=[1:2:3::4:5:6] or host=[1:2:3::4:5]:6, which would might be
helpful for the future but doesn't avoid changing the meaning of
connection strings that work today.

So now I think that to make this work correctly, we're going to need
to change both the URL parser and also add parsing for the host and
port.  Let's say the user says this:

postgresql://[1::2]:3,[4::5],[6::7]::8/

What I think we need to do is translate that into this:

host=1::2,4::5,6::7 port=3,,8

Note the double-comma, indicating a blank port number for the second
URL component.  When we parse those host and port strings, we can
match up each host with the corresponding port number again.  Of
course, the user could also skip the URL format and directly specify a
connection string.  And then they might write one where the host and
port parts don't have the same number of components, like this:

host=a,b,c port=3,4
or
host=a,b port=3,4,5

It is obvious what is meant if multiple hosts are given but only a
single port number is specified; it is also obvious what is meant if
the number of ports is equal to the number of hosts.  It is not
obvious what it means if there are multiple ports but the number
doesn't equal the number of hosts.  I think we can either treat that
case as an error or else do the following: if there are extra port
specifiers, ignore them; if there are extra host specifiers, use the
last port in the list for all of the remaining hosts.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 19:38  Victor Wagner <vitus@wagner.pp.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Victor Wagner @ 2016-10-24 19:38 UTC (permalink / raw)
  To: pgsql-hackers@postgresql.org

On Wed, 19 Oct 2016 12:04:27 -0400
Robert Haas <robertmhaas@gmail.com> wrote:

> On Thu, Oct 13, 2016 at 5:53 AM, Victor Wagner <vitus@wagner.pp.ru>
> wrote:
> > On Thu, 13 Oct 2016 12:30:59 +0530
> > Mithun Cy <mithun.cy@enterprisedb.com> wrote:  
> >> On Fri, Sep 30, 2016 at 2:14 PM, Victor Wagner <vitus@wagner.pp.ru>
> >> wrote:
> >> Okay but for me consistency is also important. Since we agree to
> >> disagree on some of the comments and others have not expressed any
> >> problem I am moving it to committer.  
> >
> > Thank you for your efforts improving my patch  
> 
> I haven't deeply reviewed this patch, but on a quick read-through it
> certainly seems to need a lot of cleanup work.
> 

I've did some cleanup, i.e. running pgindent, spell-checking comments
and indenting sgml and attaching cleaned up version here.

I've also re-added test file t/001-multihost.pl which get lost from
previous post.

Thanks for your suggestions.



-- 
                                   Victor Wagner <vitus@wagner.pp.ru>

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-12.patch (text/x-patch, 60.5K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..b7c62d2 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -792,7 +792,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,netloc[:port]...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +809,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://node1,node2:5433,node3:4432,node4/mydb?hostorder=random&amp;target_server_type=any </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -831,7 +832,9 @@ postgresql:///mydb?host=localhost&amp;port=5433 <para> For improved compatibility with JDBC connection <acronym>URI</acronym>s, instances of parameter <literal>ssl=true</literal> are translated into - <literal>sslmode=require</literal>. + <literal>sslmode=require</literal> and + <literal>loadBalanceHosts=true</literal> into + <literal>hostorder=random</literal>. </para> <para> @@ -841,6 +844,10 @@ postgresql:///mydb?host=localhost&amp;port=5433 postgresql://[2001:db8::1234]/database </synopsis> </para> + <para> + There can be several host specifications, optionally accompanied + with port, separated by comma. + </para> <para> The host component is interpreted as described for the parameter <xref @@ -881,6 +888,21 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname when <productname>PostgreSQL</> was built). On machines without Unix-domain sockets, the default is to connect to <literal>localhost</>. </para> + <para> + There can be more than one <literal>host</literal> parameter in + the connection string. In this case these hosts would be considered + alternate entries into same database and if connection to first one + fails, the second would be attemped, and so on. This can be used + for high availability clusters or for load balancing. See the + <xref linkend="libpq-connect-hostorder"> parameter. This feature + works for TCP/IP host names only. + </para> + <para> + The network host name can be accompanied by a port number, separated by + colon. This port number is used only when connected to + this host. If there is no port number, the port specified in the + <xref linkend="libpq-connect-port"> parameter would be used instead. + </para> </listitem> </varlistentry> @@ -933,7 +955,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname is used to identify the connection in <filename>~/.pgpass</> (see <xref linkend="libpq-pgpass">). </para> - <para> Without either a host name or host address, <application>libpq</application> will connect using a @@ -943,6 +964,43 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-hostorder" xreflabel="hostorder"> + <term><literal>hostorder</literal></term> + <listitem> + <para> + Specifies how to choose the host from the list of alternate hosts, + specified in the <xref linkend="libpq-connect-host"> parameter. + </para> + <para> + If the value of this argument is <literal>sequential</literal> (the + default) connections to the hosts will be attempted in the order in + which they are specified. + </para> + <para> + If the value is <literal>random</literal>, the host to connect to + will be randomly picked from the list. It allows load balacing between + several cluster nodes. However, PostgreSQL doesn't currently support + multimaster clusters. So, without the use of third-party products, + only read-only connections can take advantage from + load-balancing. See <xref linkend="libpq-connect-target-server-type"> + </para> + </listitem> + </varlistentry> + + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + If this parameter is <literal>master</literal>, upon + successful connection the host is checked to determine whether + it is in a recovery state. If it is, it then tries next host + in the connection string. If this parameter is + <literaL>any</literal>, connection to standby nodes are + considered successful. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-port" xreflabel="port"> <term><literal>port</literal></term> <listitem> @@ -985,7 +1043,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout"> <term><literal>connect_timeout</literal></term> <listitem> @@ -996,7 +1053,28 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - + <varlistentry id="libpq-connect-falover-timeout" xreflabel="failover_timeout"> + <term><literal>failover_timeout</literal></term> + <listitem> + <para> + Maximum time to cyclically retry all the hosts in the connection string. + (as decimal integer number of seconds). If not specified, then + hosts are tried just once. + </para> + <para> + If we have replicating cluster, and master node fails, it might + take some time to promote one of the standby nodes to the new master. + So clients which detect failure to connect to the master might + abandon attempts to reestablish a connection before the new master + becomes available. + </para> + <para> + Setting this parameter to a value that takes into account the amount of + time needed for failover to complete will ensure attempts to connect + to hosts continue to be made until the new master becomes available. + </para> + </listitem> + </varlistentry> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding"> <term><literal>client_encoding</literal></term> <listitem> @@ -7227,6 +7305,19 @@ user=admin An example file is provided at <filename>share/pg_service.conf.sample</filename>. </para> + <para> + If more than one <literal>host</literal> option is present in the same + section of the service file, it is interpeted as alternate servers for + failover or load-balancing. See <xref linkend="libpq-connect-host"> + option in the connection string. + </para> + <para> + For all other options, the first value takes precedence over later ones. + </para> + <para> + Options specified in the connection string, along with the service option, + have precedence over values from the service file. + </para> </sect1> diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile index b1789eb..4c14cc5 100644 --- a/src/interfaces/libpq/Makefile +++ b/src/interfaces/libpq/Makefile @@ -36,7 +36,7 @@ OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ libpq-events.o # libpgport C files we always use OBJS += chklocale.o inet_net_ntop.o noblock.o pgstrcasecmp.o pqsignal.o \ - thread.o + thread.o pgsleep.o # libpgport C files that are needed if identified by configure OBJS += $(filter crypt.o getaddrinfo.o getpeereid.o inet_aton.o open.o system.o snprintf.o strerror.o strlcpy.o win32error.o win32setlocale.o, $(LIBOBJS)) # src/backend/utils/mb @@ -129,6 +129,9 @@ install: all installdirs install-lib installcheck: $(MAKE) -C test $@ +check: + $(prove_check) + installdirs: installdirs-lib $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' '$(DESTDIR)$(datadir)' @@ -142,6 +145,7 @@ uninstall: uninstall-lib clean distclean: clean-lib $(MAKE) -C test $@ rm -f $(OBJS) pthread.h libpq.rc + rm -rf tmp_check # Might be left over from a Win32 client-only build rm -f pg_config_paths.h rm -f inet_net_ntop.c noblock.c pgstrcasecmp.c pqsignal.c thread.c diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..67080c5 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -299,7 +299,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { {"replication", NULL, NULL, NULL, "Replication", "D", 5, offsetof(struct pg_conn, replication)}, - + /* Parameters added by failover patch */ + {"hostorder", NULL, "sequential", NULL, + "Host order", "", 10, + offsetof(struct pg_conn, hostorder)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + {"failover_timeout", NULL, NULL, NULL, + "Failover Timeout", "", 10, + offsetof(struct pg_conn, failover_timeout)}, /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +345,7 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void pqTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -380,6 +390,7 @@ static bool getPgPassFilename(char *pgpassfile); static void dot_pg_pass_warning(PGconn *conn); static void default_threadlock(int acquire); +static int try_next_address(PGconn *conn); /* global variable because fe-auth.c needs to access it */ pgthreadlock_t pg_g_threadlock = default_threadlock; @@ -806,7 +817,9 @@ connectOptions2(PGconn *conn) { if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, + conn->pgpass = PasswordFromFile( + conn->actualhost ? conn->actualhost : conn->pghost, + conn->actualport ? conn->actualport : conn->pgport, conn->dbName, conn->pguser); if (conn->pgpass == NULL) { @@ -890,6 +903,22 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value: \"%s\" should be \"any\" or \"master\"\n"), + conn->target_server_type); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1173,6 +1202,8 @@ connectFailureMessage(PGconn *conn, int errorno) if (conn->pghostaddr && conn->pghostaddr[0] != '\0') displayed_host = conn->pghostaddr; + else if (conn->actualhost && conn->actualhost[0] != '\0') + displayed_host = conn->actualhost; else if (conn->pghost && conn->pghost[0] != '\0') displayed_host = conn->pghost; else @@ -1390,11 +1421,17 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { + struct nodeinfo + { + char *host; + char *port; + }; int portnum; char portstr[MAXPGPATH]; struct addrinfo *addrs = NULL; struct addrinfo hint; - const char *node; + struct nodeinfo *nodes, + *node; int ret; if (!conn) @@ -1436,21 +1473,183 @@ connectDBStart(PGconn *conn) if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') { /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; + + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + nodes->host = strdup(conn->pghostaddr); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; } else if (conn->pghost != NULL && conn->pghost[0] != '\0') { /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; + char *p = conn->pghost, + *q, + *r; + int nodecount = 0, + nodesallocated = 4; + + /* + * Parse comma-separated list of host-port pairs into function-local + * array of records. + */ + nodes = malloc(sizeof(struct nodeinfo) * 4); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + while (*p) + { + q = p; + r = NULL; + + /* Scan for the comma or end of string */ + while (*q != ',' && *q != 0) + { + if (*q == ':') + r = q; + if (*q == ']') + r = NULL; /* if there is IPv6, colons before close + * bracket are part of address */ + q++; + } + if (r) + { + /* Host has explicitly specified port */ + char *nptr; + + /* Check if port is numeric */ + for (nptr = r + 1; nptr < q; nptr++) + { + if (*nptr < '0' || *nptr > '9') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Port is not numeric")); + conn->options_valid = false; + goto connect_errReturn; + } + } + + /* Allocate memory for port string */ + nodes[nodecount].port = malloc(q - r); + if (nodes[nodecount].port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].port, r + 1, q - r); + nodes[nodecount].port[q - r - 1] = 0; + } + else + { + r = q; + nodes[nodecount].port = NULL; + } + + if ((*p) == '[' && *(r - 1) == ']') + { + /* IPv6 address found. Strip brackets */ + p++; + r--; + } + + /* Fill node record */ + nodes[nodecount].host = malloc(r - p + 1); + if (nodes[nodecount].host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + strncpy(nodes[nodecount].host, p, r - p); + nodes[nodecount].host[r - p] = 0; + + /* skip a comma */ + if (*q) + q++; + + nodecount++; + if (nodecount == nodesallocated) + nodes = realloc(nodes, sizeof(struct nodeinfo) * (nodesallocated += 4)); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + + p = q; + } + + /* Fill end-of-host list marker */ + nodes[nodecount].host = NULL; + nodes[nodecount].port = NULL; hint.ai_family = AF_UNSPEC; + if (nodecount > 1 && conn->target_server_type == NULL) + { + /* + * if there is more than one host in the connect string and + * target_server_type is not specified explicitly, set + * target_server_type to "master", because default mode of + * operation is failover, and so, we need to connect to RW host, + * and keep other nodes of the cluster in the connect string just + * in case master would fail and one of standbys would be promoted + * to master. + * + * If we want to loadbalance readonly queries, set + * target_server_type = "any" explicitly + * + * But global default is "any" because if there is only one host + * in the connect string, we want backward-compatible behavior. + */ + conn->target_server_type = strdup("master"); + if (conn->target_server_type == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + } } else { #ifdef HAVE_UNIX_SOCKETS /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNIX; UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) @@ -1460,33 +1659,113 @@ connectDBStart(PGconn *conn) portstr, (int) (UNIXSOCK_PATH_BUFLEN - 1)); conn->options_valid = false; + free(nodes); + goto connect_errReturn; + } + + nodes->port = strdup(portstr); + if (nodes->port == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; goto connect_errReturn; } #else /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; + nodes = calloc(sizeof(struct nodeinfo), 2); + if (nodes == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } + hint.ai_family = AF_UNSPEC; + nodes->host = strdup(DefaultHost); + if (nodes->host == NULL) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory\n")); + conn->options_valid = false; + goto connect_errReturn; + } #endif /* HAVE_UNIX_SOCKETS */ } /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) + /* loop over all the host specs in the node variable */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); + struct addrinfo *this_node_addrs; + + /* Resolve each hostname into list of addrinfo structures */ + ret = pg_getaddrinfo_all(node->host, (node->port ? node->port : portstr), + &hint, &this_node_addrs); + if (ret || !this_node_addrs) + { + if (node->host) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node->host, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + node->port, gai_strerror(ret)); + if (this_node_addrs) + pg_freeaddrinfo_all(hint.ai_family, this_node_addrs); + + /* + * We shouldn't fail here unless there is no valid addrinfos left + */ + continue; + } + + if (node->host) + { + struct addrinfo *n; + + for (n = this_node_addrs; n != NULL; n = n->ai_next) + { + n->ai_canonname = strdup(node->host); + } + } + + /* add this host addrs to addrs field of PGconn structure */ + if (!addrs) + { + addrs = this_node_addrs; + } else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); + { + struct addrinfo *p; + + /* This loop finds pointer to the last element of the list */ + for (p = addrs; p->ai_next != NULL; p = p->ai_next) + { + } + p->ai_next = this_node_addrs; + } + } + + /* Free nodes array */ + for (node = nodes; node->host != NULL || node->port != NULL; node++) + { + if (node->host) + free(node->host); + if (node->port) + free(node->port); + } + + free(nodes); + + /* Check if we've found at least one usable address */ + if (!addrs) + { conn->options_valid = false; goto connect_errReturn; } - #ifdef USE_SSL /* setup values based on SSL mode */ if (conn->sslmode[0] == 'd') /* "disable" */ @@ -1499,11 +1778,26 @@ connectDBStart(PGconn *conn) * Set up to try to connect, with protocol 3.0 as the first attempt. */ conn->addrlist = addrs; - conn->addr_cur = addrs; + + /* + * We cannot just assign first addrs record to addr_cur, because host + * order may be random. So, use try_next_address + */ + conn->addr_cur = NULL; + try_next_address(conn); conn->addrlist_family = hint.ai_family; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; + if (conn->failover_timeout) + { + conn->failover_finish_time = time(NULL) + atoi(conn->failover_timeout); + } + else + { + conn->failover_finish_time = (time_t) 0; /* it is in past, so its + * ok */ + } /* * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(), @@ -1521,6 +1815,23 @@ connect_errReturn: return 0; } +/* + * This function is used to convert integer port number from the + * addrinfo structure back into string representation, because function + * PQport needs to return string representation of port. + */ + +static char * +get_port_from_addrinfo(struct addrinfo * ai) +{ + char port[6]; + + sprintf(port, "%d", htons(((struct sockaddr_in *) ai->ai_addr)->sin_port)); + + /* allocation failure must be checked by caller */ + return strdup(port); +} + /* * connectDBComplete @@ -1603,6 +1914,118 @@ connectDBComplete(PGconn *conn) } } +/* + * Gets address of pointer to the list of addrinfo structures. + * If order is random, rearranges the list by moving random element to + * the beginning (and putting its address into given pointer. + * Returns address of first list element + */ +static struct addrinfo * +get_next_element(struct addrinfo ** list, char *order) +{ + struct addrinfo *choice = NULL, + *prev, + *current, + *prechoice = NULL; + int count = 0; + + if (*list == NULL) + return NULL; + if (strcmp(order, "random") == 0) + { + /* Peek random element from the list. */ + for (current = *list, prev = NULL; current != NULL; + prev = current, current = current->ai_next) + { + count++; + if ((rand() & 0xffff) < 0x10000 / count) + { + choice = current; + prechoice = prev; + } + } + + /* + * If prechoice is not NULL, selected element is not first in the + * list. We have to move it to he head + */ + if (prechoice != NULL) + { + prechoice->ai_next = choice->ai_next; + choice->ai_next = *list; + *list = choice; + } + } + + /* We always return first element of the list */ + return *list; +} + +/* ------------- + * try_next_address + * Attempts to set next address from the list of known ones. + * Returns 1 if address is chosen and 0 if there are no more addresses + * to try + * Takes into account hostorder parameter + * ------------ + */ + +static int +try_next_address(PGconn *conn) +{ + if (strcmp(conn->hostorder, "random") == 0) + { + /* + * Initialize random number generator for it to be initialized for + * certain. Use value from rand along with time in case random number + * have been initialized by application. Use address of conn structure + * to load-balance different connections in the same app + */ + srand((unsigned int) ((long int) conn ^ (long int) time(NULL) ^ + (long int) rand())); + } + + if (conn->addr_cur == NULL) + { + + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + conn->addr_cur = get_next_element(&(conn->addr_cur->ai_next), + conn->hostorder); + } + + if (conn->addr_cur == NULL && time(NULL) < conn->failover_finish_time) + { + /* + * If failover timeout is set, retry list of hosts from the beginning + */ + pg_usleep(1000000); + conn->addr_cur = get_next_element(&(conn->addrlist), + conn->hostorder); + } + + if (conn->addr_cur != NULL) + { + /* + * Clean up error message buffer. + */ + resetPQExpBuffer(&conn->errorMessage); + conn->actualhost = conn->addr_cur->ai_canonname; + + return 1; + } + else + { + return 0; + } +} + /* ---------------- * PQconnectPoll * @@ -1681,6 +2104,9 @@ PQconnectPoll(PGconn *conn) case CONNECTION_NEEDED: break; + case CONNECTION_CHECK_RW: + break; + default: appendPQExpBufferStr(&conn->errorMessage, libpq_gettext( @@ -1718,11 +2144,11 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = addr_cur->ai_next; continue; } + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not create socket: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -1739,7 +2165,7 @@ keep_going: /* We will come back to here until there is if (!connectNoDelay(conn)) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1749,7 +2175,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to nonblocking mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } @@ -1760,7 +2186,7 @@ keep_going: /* We will come back to here until there is libpq_gettext("could not set socket to close-on-exec mode: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } #endif /* F_SETFD */ @@ -1807,7 +2233,7 @@ keep_going: /* We will come back to here until there is if (err) { pqDropConnection(conn, true); - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); continue; } } @@ -1883,6 +2309,10 @@ keep_going: /* We will come back to here until there is * go do the next stuff. */ conn->status = CONNECTION_STARTED; + + /* + * Save the name of the current host + */ goto keep_going; } @@ -1898,7 +2328,7 @@ keep_going: /* We will come back to here until there is /* * Try the next address, if any. */ - conn->addr_cur = addr_cur->ai_next; + try_next_address(conn); } /* loop over addresses */ /* @@ -1944,9 +2374,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (try_next_address(conn)) { - conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; goto keep_going; } @@ -2596,13 +3025,22 @@ keep_going: /* We will come back to here until there is conn->errorMessage.data[conn->errorMessage.len - 1] != '\n') appendPQExpBufferChar(&conn->errorMessage, '\n'); PQclear(res); + + /* + * If we have more than one host in the connect string, + * fatal message from one of them is not really fatal + */ + if (try_next_address(conn)) + { + /* Must drop the old connection */ + pqDropConnection(conn, true); + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; - conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) @@ -2614,8 +3052,8 @@ keep_going: /* We will come back to here until there is } /* Otherwise, we are open for business! */ - conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + conn->status = CONNECTION_CHECK_RO; + goto keep_going; } case CONNECTION_SETENV: @@ -2645,9 +3083,141 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We are open for business! */ + /* + * check if connection is readonly if we need readwrite one + */ + conn->status = CONNECTION_CHECK_RO; + goto keep_going; + + case CONNECTION_CHECK_RO: + + /* + * Connection to readonly host is allowed if taget_server_type is + * set to 'any' or is not exlicitely + */ + if (conn->pghost == NULL || !conn->target_server_type || + strcmp(conn->target_server_type, "any") == 0) + + { + /* + * We can release the address list now but first make a copy + * of the name of host we are connected to or it would be + * freed with list + */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* Otherwise request result pg_is_in_recovery() */ + /* pretend that status is OK for time of sending query */ conn->status = CONNECTION_OK; - return PGRES_POLLING_OK; + PQsendQuery(conn, "SELECT pg_catalog.pg_is_in_recovery()"); + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + + case CONNECTION_CHECK_RW: + { + char *value; + PGresult *res; + + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + + if (PQisBusy(conn)) + { + /* Result is not ready yet */ + conn->status = CONNECTION_CHECK_RW; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + + /* + * Call PQgetResult second time to clear connection state. + * Should return NULL, so result is ignored + */ + PQgetResult(conn); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK || + PQntuples(res) != 1) + { + /* + * Something wrong happened with this host. Skip to next + * one + */ + conn->status = CONNECTION_NEEDED; + } + else + { + value = PQgetvalue(res, 0, 0); + if (value[0] == 't') + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("cannot make RW connection to hot " + "standby node %s"), conn->actualhost); + conn->status = CONNECTION_NEEDED; + } + } + + if (res) + PQclear(res); + if (conn->status != CONNECTION_OK) + { + ConnStatusType save_status = conn->status; + + conn->status = CONNECTION_OK; + pqTerminateConn(conn); + pqDropConnection(conn, true); + conn->sock = PGINVALID_SOCKET; + if (try_next_address(conn)) + { + conn->status = save_status; + goto keep_going; + } + else + { + conn->status = CONNECTION_BAD; + return PGRES_POLLING_FAILED; + } + } + + /* We can release the address list now. */ + if (conn->actualhost) + { + conn->actualhost = strdup(conn->actualhost); + conn->actualport = get_port_from_addrinfo(conn->addr_cur); + if (!conn->actualhost || !conn->actualport) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Out of memory")); + goto error_return; + } + } + + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); + conn->addrlist = NULL; + conn->addr_cur = NULL; + return PGRES_POLLING_OK; + } default: appendPQExpBuffer(&conn->errorMessage, @@ -2938,19 +3508,16 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend + * pqTerminateConn + * + * - send terminate message to the backend, but do not free any + * transient state of PGconn object, which can be needed to reconnect * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). */ + static void -closePGconn(PGconn *conn) +pqTerminateConn(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; - /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -2966,6 +3533,26 @@ closePGconn(PGconn *conn) (void) pqFlush(conn); } + +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + /* Send terminate request to backend */ + pqTerminateConn(conn); + /* * Must reset the blocking status so a possible reconnect will work. * @@ -2978,11 +3565,29 @@ closePGconn(PGconn *conn) * Close the connection, reset all transient state, flush I/O buffers. */ pqDropConnection(conn, true); + conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just * absent */ conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); + + /* + * If addrlist is not freed, actualhost points in there. Otherwice it is + * allocated and should be freed + */ + if (conn->addrlist == NULL && conn->actualhost != NULL) + { + free(conn->actualhost); + conn->actualhost = NULL; + } + + if (conn->actualport) + { + free(conn->actualport); + conn->actualport = NULL; + } + pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); conn->addrlist = NULL; conn->addr_cur = NULL; @@ -3969,6 +4574,8 @@ parseServiceFile(const char *serviceFile, { int linenr = 0, i; + bool hostflag = false; /* true if we already have seen 'host' + * parameter in the service file, and */ FILE *f; char buf[MAXBUFSIZE], *line; @@ -4088,7 +4695,38 @@ parseServiceFile(const char *serviceFile, if (strcmp(options[i].keyword, key) == 0) { if (options[i].val == NULL) + { options[i].val = strdup(val); + + /* + * Set flag that we get value of host option from + * this service file, so subsequent host lines + * should be appended to it, not ignored + */ + if (strcmp(key, "host") == 0) + hostflag = true; + } + else if (strcmp(key, "host") == 0 && hostflag) + { + /* + * Old host value is from same service file, so + * append new one to it + */ + char *old = options[i].val; + int oldlen = strlen(old); + + options[i].val = malloc(oldlen + 1 + strlen(val) + 1); + + if (options[i].val) + { + strncpy(options[i].val, old, oldlen); + options[i].val[oldlen] = ','; + strcpy(options[i].val + oldlen + 1, val); + } + + free(old); + } + if (!options[i].val) { printfPQExpBuffer(errorMessage, @@ -4809,86 +5447,127 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, p = start; } - /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. - */ - if (*p == '[') + host = p; + if (*p == ':') { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) + int portnum; + char *portstr; + + *(p++) = '\0'; + portstr = p; + portnum = 0; + while (*p >= '0' && *p <= '9') { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; + portnum = portnum * 10 + (*(p++) - '0'); } - if (p == host) + if (portnum > 65535 || portnum < 1) { printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); goto cleanup; } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - - /* - * The address may be followed by a port specifier or a slash or a - * query. - */ - if (*p && *p != ':' && *p != '/' && *p != '?') + prevchar = *p; + *p = '\0'; + if (*portstr && + !conninfo_storeval(options, "port", portstr, + errorMessage, false, true)) { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); goto cleanup; } } else { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + do + { + if (*p == ',') + p++; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * "p" has been incremented past optional URI credential + * information at this point and now points at the "netloc" part + * of the URI. + * + * Look for IPv6 address. + */ + if (*p == '[') + { + char *ipv6start = ++p; - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == ipv6start) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + p++; + /* + * The address may be followed by a port specifier, a comma or + * a slash or a query. + */ + if (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + } + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ - while (*p && *p != '/' && *p != '?') - ++p; + /* + * Look for port specifier (colon) or end of host specifier + * (slash), or query (question mark). + */ + while (*p && *p != ',' && *p != ':' && *p != '/' && *p != '?') + ++p; + } + /* Skip port specifier */ + if (*p == ':') + { + int portnum; + + p++; + portnum = 0; + while (*p >= '0' && *p <= '9') + { + portnum = portnum * 10 + (*(p++) - '0'); + } + if (portnum > 65535 || portnum < 1) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("invalid port number: \"%d\"\n"), + portnum); + goto cleanup; + } + } + } while (*p == ','); + /* Save the hostname terminator before we null it */ prevchar = *p; *p = '\0'; - if (*port && - !conninfo_storeval(options, "port", port, + if (*host && + !conninfo_storeval(options, "host", host, errorMessage, false, true)) goto cleanup; - } + } if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -5018,6 +5697,21 @@ conninfo_uri_parse_params(char *params, keyword = "sslmode"; value = "require"; } + if ((strcmp(keyword, "loadBalanceHosts") == 0 || + strcmp(keyword, "load_balance_hosts") == 0) && + strcmp(value, "true") == 0) + { + free(keyword); + free(value); + malloced = false; + keyword = "hostorder"; + value = "random"; + } + if (strcmp(keyword, "targetServerType") == 0) + { + free(keyword); + keyword = strdup("target_server_type"); + } /* * Store the value if the corresponding option exists; ignore @@ -5232,7 +5926,21 @@ conninfo_storeval(PQconninfoOption *connOptions, } if (option->val) + { + if (strcmp(option->keyword, "host") == 0) + { + /* Accumulate multiple hosts in the single string */ + int val_len = strlen(option->val), + new_len = strlen(value); + + free(value_copy); + value_copy = malloc(val_len + 1 + new_len + 1); + strncpy(value_copy, option->val, val_len + 1); + value_copy[val_len] = ','; + strncpy(value_copy + val_len + 1, value, new_len + 1); + } free(option->val); + } option->val = value_copy; return option; @@ -5352,7 +6060,9 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->actualhost != NULL && conn->actualhost[0] != '\0') + return conn->actualhost; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { @@ -5372,6 +6082,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->actualport) + return conn->actualport; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..23560f4 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,11 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_RO, /* Internal state: need to check is RO + * connection acceptable */ + CONNECTION_CHECK_RW, /* Internal state: waiting that server replies + * if it is in recovery */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 7007692..3b0fb64 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -334,7 +334,12 @@ struct pg_conn #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) char *krbsrvname; /* Kerberos service name */ #endif - + char *hostorder; /* How to handle multiple hosts */ + char *target_server_type; /* If "any" could work with readonly + * standby server. Otherwise should be + * "master" */ + char *failover_timeout; /* If no usable server found, how long + * to wait before retry */ /* Optional file to write trace info to */ FILE *Pfdebug; @@ -381,6 +386,11 @@ struct pg_conn struct addrinfo *addrlist; /* list of possible backend addresses */ struct addrinfo *addr_cur; /* the one currently being tried */ int addrlist_family; /* needed to know how to free addrlist */ + time_t failover_finish_time; /* how long to retry host list waiting + * for new master to appear */ + char *actualhost; /* Name of host we are actually connected to + * (if there is list in the pghost) */ + char *actualport; /* Port number we are actually connected to */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */ @@ -466,6 +476,7 @@ struct pg_conn /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ + }; /* PGcancel stores all data necessary to cancel a connection. A copy of this diff --git a/src/interfaces/libpq/t/001-multihost.pl b/src/interfaces/libpq/t/001-multihost.pl new file mode 100644 index 0000000..7748aea --- /dev/null +++ b/src/interfaces/libpq/t/001-multihost.pl @@ -0,0 +1,529 @@ +# Minimal test testing streaming replication +use strict; +use warnings; +use PostgresNode; +use TestLib; +use Test::More tests => 28; + +# Initialize master node + +my $node_master = get_new_node('master'); +$node_master->init(allows_streaming => 1, use_tcp => 1); +$node_master->start; +my $backup_name = 'my_backup'; + +# Take backup +$node_master->backup($backup_name); + +# Create streaming standby linking to master +my $node_standby_1 = get_new_node('standby_1'); + +$node_standby_1->init_from_backup( + $node_master, $backup_name, + has_streaming => 1, + use_tcp => 1); +$node_standby_1->start; + +# Take backup of standby 1 (not mandatory, but useful to check if +# pg_basebackup works on a standby). +$node_standby_1->backup($backup_name); + +# Create second standby node linking to standby 1 +my $node_standby_2 = get_new_node('standby_2'); +$node_standby_2->init_from_backup( + $node_standby_1, $backup_name, + has_streaming => 1, + use_tcp => 1); +$node_standby_2->start; + + +sub get_host_port +{ + my $node = shift; + return "$PostgresNode::test_localhost:" . $node->port; +} + +sub multiconnstring +{ + my $nodes = shift; + my $database = shift || "postgres"; + my $params = shift; + my $extra = ""; + if ($params) + { + my @cs; + while (my ($key, $val) = each %$params) + { + push @cs, $key . "=" . $val; + } + $extra = "?" . join("&", @cs); + } + my $str = + "postgresql://" + . join(",", map({ get_host_port($_) } @$nodes)) + . "/$database$extra"; + return $str; + +} + +sub connstring2 +{ + my $nodes = shift; + my $database = shift; + my $params = shift; + my @args = (); + for my $n (@$nodes) + { + push @args, "host=" . get_host_port($n); + } + push @args, "dbname=$database" if defined($database); + while (my ($key, $val) = each %$params) + { + push @args, "$key=$val"; + } + return join(" ", @args); +} + +# +# Copied from PosgresNode.pm passing explicit connect-string instead of +# constructed from object +# + +sub psql +{ + # We expect dbname to be part of connstr + my ($connstr, $sql, %params) = @_; + + my $stdout = $params{stdout}; + my $stderr = $params{stderr}; + my $timeout = undef; + my $timeout_exception = 'psql timed out'; + my @psql_params = ('psql', '-XAtq', '-d', $connstr, '-f', '-'); + + # If the caller wants an array and hasn't passed stdout/stderr + # references, allocate temporary ones to capture them so we + # can return them. Otherwise we won't redirect them at all. + if (wantarray) + { + if (!defined($stdout)) + { + my $temp_stdout = ""; + $stdout = \$temp_stdout; + } + if (!defined($stderr)) + { + my $temp_stderr = ""; + $stderr = \$temp_stderr; + } + } + + $params{on_error_stop} = 1 unless defined $params{on_error_stop}; + $params{on_error_die} = 0 unless defined $params{on_error_die}; + + push @psql_params, '-v', 'ON_ERROR_STOP=1' if $params{on_error_stop}; + push @psql_params, @{ $params{extra_params} } + if defined $params{extra_params}; + + $timeout = + IPC::Run::timeout($params{timeout}, exception => $timeout_exception) + if (defined($params{timeout})); + + ${ $params{timed_out} } = 0 if defined $params{timed_out}; + + # IPC::Run would otherwise append to existing contents: + $$stdout = "" if ref($stdout); + $$stderr = "" if ref($stderr); + + my $ret; + + # Run psql and capture any possible exceptions. If the exception is + # because of a timeout and the caller requested to handle that, just return + # and set the flag. Otherwise, and for any other exception, rethrow. + # + # For background, see + # http://search.cpan.org/~ether/Try-Tiny-0.24/lib/Try/Tiny.pm + do + { + local $@; + eval { + my @ipcrun_opts = (\@psql_params, '<', \$sql); + push @ipcrun_opts, '>', $stdout if defined $stdout; + push @ipcrun_opts, '2>', $stderr if defined $stderr; + push @ipcrun_opts, $timeout if defined $timeout; + + IPC::Run::run @ipcrun_opts; + $ret = $?; + }; + my $exc_save = $@; + if ($exc_save) + { + + # IPC::Run::run threw an exception. re-throw unless it's a + # timeout, which we'll handle by testing is_expired + die $exc_save + if (blessed($exc_save) || $exc_save ne $timeout_exception); + + $ret = undef; + + die "Got timeout exception '$exc_save' but timer not expired?!" + unless $timeout->is_expired; + + if (defined($params{timed_out})) + { + ${ $params{timed_out} } = 1; + } + else + { + die "psql timed out: stderr: '$$stderr'\n" + . "while running '@psql_params'"; + } + } + }; + + if (defined $$stdout) + { + chomp $$stdout; + $$stdout =~ s/\r//g if $TestLib::windows_os; + } + + if (defined $$stderr) + { + chomp $$stderr; + $$stderr =~ s/\r//g if $TestLib::windows_os; + } + + # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR + # We don't use IPC::Run::Simple to limit dependencies. + # + # We always die on signal. + my $core = $ret & 128 ? " (core dumped)" : ""; + die "psql exited with signal " + . ($ret & 127) + . "$core: '$$stderr' while running '@psql_params'" + if $ret & 127; + $ret = $ret >> 8; + + if ($ret && $params{on_error_die}) + { + die "psql error: stderr: '$$stderr'\nwhile running '@psql_params'" + if $ret == 1; + die "connection error: '$$stderr'\nwhile running '@psql_params'" + if $ret == 2; + die "error running SQL: '$$stderr'\nwhile running '@psql_params'" + if $ret == 3; + die "psql returns $ret: '$$stderr'\nwhile running '@psql_params'"; + } + + if (wantarray) + { + return ($ret, $$stdout, $$stderr); + } + else + { + return $ret; + } +} + +sub psql_conninfo +{ + my ($connstr) = shift; + my ($timed_out); + my ($retcode, $stdout, $stderr) = + psql($connstr, '\conninfo', timed_out => \$timed_out); + if ($retcode == 0 && $stdout =~ /on host "([^"]*)" at port "([^"]*)"/s) + { + return "$1:$2"; + } + else + { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} + +sub psql_server_addr +{ + my ($connstr) = shift; + my ($timed_out); + my $sql = + "select abbrev(inet_server_addr()) ||':'||inet_server_port();\n"; + my ($retcode, $stdout, $stderr) = + psql($connstr, $sql, timed_out => \$timed_out); + if ($retcode == 0) + { + return $stdout; + } + else + { + return "STDOUT:$stdout\nSTDERR:$stderr"; + } +} +my $conninfo; + +# Test 1.1 - all hosts available, master first, readwrite requested +$conninfo = + psql_conninfo( + multiconnstring([ $node_master, $node_standby_1, $node_standby_2 ])); +is($conninfo, get_host_port($node_master), "master first, rw, conninfo"); + +# Test 1.2 +$conninfo = + psql_server_addr( + multiconnstring([ $node_master, $node_standby_1, $node_standby_2 ])); +is($conninfo, get_host_port($node_master), "master first, rw, server funcs"); + +# Test 2.1 - use symbolic name for master and IP for slave +$conninfo = + psql_conninfo("postgresql://localhost:" + . $node_master->port + . ",127.0.0.1:" + . $node_standby_1->port + . "/postgres"); + +is( $conninfo, + "localhost:" . $node_master->port, + "master symbolic, rw, conninfo"); + +# Test 2.2 - check server-side connect info (would return numeric IP) +$conninfo = + psql_server_addr("postgresql://localhost:" + . $node_master->port + . ",127.0.0.1:" + . $node_standby_1->port + . "/postgres"); +is( $conninfo, + "127.0.0.1:" . $node_master->port, + 'master symbolic, rw server funcs'); + +# Test 3.1 - all nodes available, master second, readwrite requested +$conninfo = + psql_conninfo( + multiconnstring([ $node_standby_1, $node_master, $node_standby_2 ])); + +is($conninfo, get_host_port($node_master), "master second,rw, conninfo"); + +# Test 3.2 Check server-side connection info +$conninfo = + psql_server_addr( + multiconnstring([ $node_standby_1, $node_master, $node_standby_2 ])); + +is($conninfo, get_host_port($node_master), "master second, rw, server funcs"); + +# Test 4.1 - use symbolic name for slave and IP for smaster +$conninfo = + psql_conninfo("postgresql://localhost:" + . $node_standby_1->port + . ",127.0.0.1:" + . $node_master->port + . "/postgres"); +is( $conninfo, + "127.0.0.1:" . $node_master->port, + "slave symbolic, rw,conninfo"); + +# Test 4.2 - check server-side connect info +$conninfo = + psql_server_addr("postgresql://localhost:" + . $node_standby_1->port + . ",127.0.0.1:" + . $node_master->port + . "/postgres"); +is( $conninfo, + "127.0.0.1:" . $node_master->port, + "slave symbolic rw, server funcs"); + +# Test 5 - all nodes available, master first, readonly requested + +$conninfo = psql_conninfo( + multiconnstring( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, { target_server_type => 'any' })); + +is($conninfo, get_host_port($node_master), "master first, ro, conninfo"); + +# Test 6 - all nodes available, master second, readonly requested +$conninfo = psql_conninfo( + multiconnstring( + [ $node_standby_1, $node_master, $node_standby_2 ], + undef, { target_server_type => 'any' })); + +is($conninfo, get_host_port($node_standby_1), "master second, ro conninfo"); + +# Test 7.1 - all nodes available, random order, readonly. +# Expect that during six attempts any of three nodes would be collected +# at least once + +my %conncount = (); +for (my $i = 0; $i < 9; $i++) +{ + my $conn = psql_conninfo( + multiconnstring( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, + { target_server_type => 'any', hostorder => 'random' })); + $conncount{$conn}++; +} +is(scalar(keys(%conncount)), 3, 'random order, readonly connect'); + +# Test 7.2 - alternate (jdbc compatible) syntax for randomized hosts + +for (my $i = 0; $i < 6; $i++) +{ + my $conn = psql_conninfo( + multiconnstring( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, + { targetServerType => 'any', loadBalanceHosts => "true" })); + $conncount{$conn}++; +} + +#diag(join(",",keys %conncount)); +is(scalar(keys %conncount), + 3, "alternate JDBC-compatible syntax for random order"); + +# Test 8 - all nodes available, random order, readwrite +# Expect all six connections go to the master + +%conncount = (); +for (my $i = 0; $i < 6; $i++) +{ + my $conn = psql_conninfo( + multiconnstring( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, { hostorder => 'random' })); + $conncount{$conn}++; +} + +is(length(keys %conncount), 1, 'random order, rw connect only one node'); +ok(exists $conncount{ get_host_port($node_master) }, + 'random order, rw connects master'); + +# Test 8.1 one host in URL, master +$conninfo = psql_conninfo(multiconnstring([$node_master])); +is($conninfo, get_host_port($node_master), "old behavoir compat - master"); + + +# Test 8.2 one host in URL, slave +$conninfo = psql_conninfo(multiconnstring([$node_standby_1])); +is($conninfo, get_host_port($node_standby_1), "old behavoir compat - slave"); + +# Test 9 - try to connect only slaves in rw mode + +$conninfo = + psql_conninfo(multiconnstring([ $node_standby_1, $node_standby_2 ])); +is( $conninfo, +"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1", + "cannot connect just slaves in RW mode"); + + + +# Test 10 - one of slaves is not available +$node_standby_1->stop(); + +# Test 10.1 + +$conninfo = + psql_conninfo( + multiconnstring([ $node_standby_1, $node_master, $node_standby_2 ])); + +is($conninfo, get_host_port($node_master), "first node is unavailable"); + +# Test 10.2 + +$conninfo = + psql_conninfo( + multiconnstring([ $node_standby_2, $node_standby_1, $node_master ])); + +is( $conninfo, + get_host_port($node_master), + "first node standby, second unavailable"); + +# Test 10.3 + +$conninfo = psql_conninfo( + multiconnstring( + [ $node_standby_1, $node_standby_2, $node_master ], + undef, { target_server_type => 'any' })); +is( $conninfo, + get_host_port($node_standby_2), + "first node unavailable, second standmby, readonly mode"); + +$node_standby_1->start(); + +$node_master->stop(); + +$conninfo = + psql_conninfo( + multiconnstring([ $node_standby_1, $node_master, $node_standby_2 ])); + +is( $conninfo, +"STDOUT:\nSTDERR:psql: cannot make RW connection to hot standby node 127.0.0.1", + "master unavialble, cannot connect just slaves in RW mode"); + +$conninfo = psql_conninfo( + multiconnstring( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, { target_server_type => 'any' })); + +is( $conninfo, + get_host_port($node_standby_1), + "Master unavailable, read only "); + +$node_master->start(); + +# Test 11 Alternate syntax + +$conninfo = + psql_conninfo( + connstring2([ $node_standby_1, $node_standby_2, $node_master ])); + +is( $conninfo, + get_host_port($node_master), + "Alternate syntax, master third, rw"); + + + +$conninfo = + psql_conninfo( + connstring2([ $node_master, $node_standby_1, $node_standby_2 ])); + +is( $conninfo, + get_host_port($node_master), + "Alternate syntax, master first, rw"); + + + +$conninfo = psql_conninfo( + connstring2( + [ $node_standby_1, $node_standby_2, $node_master ], + undef, { target_server_type => 'any' })); + +is( $conninfo, + get_host_port($node_standby_1), + "Alternate syntax, master third, ro"); + + + +$conninfo = psql_conninfo( + connstring2( + [ $node_master, $node_standby_1, $node_standby_2 ], + undef, { target_server_type => 'any' })); + +is( $conninfo, + get_host_port($node_master), + "Alternate syntax, master first, ro"); + + +# Test 11.5 one host in URL, master +$conninfo = psql_conninfo(connstring2([$node_master])); +is( $conninfo, + get_host_port($node_master), + "alt syntax old behavoir compat - master"); + + +# Test 11.6 one host in URL, slave +$conninfo = psql_conninfo(connstring2([$node_standby_1])); +is( $conninfo, + get_host_port($node_standby_1), + "alt syntax old behavoir compat - slave"); + + + diff --git a/src/interfaces/libpq/test/expected.out b/src/interfaces/libpq/test/expected.out index d375e82..4832bdd 100644 --- a/src/interfaces/libpq/test/expected.out +++ b/src/interfaces/libpq/test/expected.out @@ -1,20 +1,20 @@ trying postgresql://uri-user:secret@host:12345/db -user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet) +user='uri-user' password='secret' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host:12345/db -user='uri-user' dbname='db' host='host' port='12345' (inet) +user='uri-user' dbname='db' host='host:12345' (inet) trying postgresql://uri-user@host/db user='uri-user' dbname='db' host='host' (inet) trying postgresql://host:12345/db -dbname='db' host='host' port='12345' (inet) +dbname='db' host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) trying postgresql://uri-user@host:12345/ -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://uri-user@host/ user='uri-user' host='host' (inet) @@ -23,10 +23,10 @@ trying postgresql://uri-user@ user='uri-user' (local) trying postgresql://host:12345/ -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host:12345 -host='host' port='12345' (inet) +host='host:12345' (inet) trying postgresql://host/db dbname='db' host='host' (inet) @@ -62,7 +62,7 @@ trying postgresql://host/db?u%7aer=someotheruser&port=12345 uri-regress: invalid URI query parameter: "uzer" trying postgresql://host:12345?user=uri-user -user='uri-user' host='host' port='12345' (inet) +user='uri-user' host='host:12345' (inet) trying postgresql://host?user=uri-user user='uri-user' host='host' (inet) @@ -71,19 +71,19 @@ trying postgresql://host? host='host' (inet) trying postgresql://[::1]:12345/db -dbname='db' host='::1' port='12345' (inet) +dbname='db' host='[::1]:12345' (inet) trying postgresql://[::1]/db -dbname='db' host='::1' (inet) +dbname='db' host='[::1]' (inet) trying postgresql://[2001:db8::1234]/ -host='2001:db8::1234' (inet) +host='[2001:db8::1234]' (inet) trying postgresql://[200z:db8::1234]/ -host='200z:db8::1234' (inet) +host='[200z:db8::1234]' (inet) trying postgresql://[::1] -host='::1' (inet) +host='[::1]' (inet) trying postgres:// (local) @@ -143,7 +143,7 @@ trying postgres://@host host='host' (inet) trying postgres://host:/ -host='host' (inet) +uri-regress: invalid port number: "0" trying postgres://:12345/ port='12345' (local) diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm index c1b16ca..43d079d 100644 --- a/src/test/perl/PostgresNode.pm +++ b/src/test/perl/PostgresNode.pm @@ -398,6 +398,7 @@ sub init unless defined $params{hba_permit_replication}; $params{allows_streaming} = 0 unless defined $params{allows_streaming}; $params{has_archiving} = 0 unless defined $params{has_archiving}; + $params{use_tcp} = 0 unless defined $params{use_tcp}; mkdir $self->backup_dir; mkdir $self->archive_dir; @@ -432,7 +433,14 @@ sub init else { print $conf "unix_socket_directories = '$host'\n"; - print $conf "listen_addresses = ''\n"; + if ($params{use_tcp}) + { + print $conf "listen_addresses = '$test_localhost'\n"; + } + else + { + print $conf "listen_addresses = ''\n"; + } } close $conf;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 20:10  Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
  parent: Thom Brown <thom@linux.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Peter Eisentraut @ 2016-10-24 20:10 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Victor Wagner <vitus@wagner.pp.ru>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 10/24/16 6:36 AM, Thom Brown wrote:
> So should it be the case that it disallows UNIX socket addresses
> entirely?  I can't imagine a list of UNIX socket addresses being that
> useful.

But maybe a mixed list of Unix-domain sockets and TCP connections?

The nice thing is that is it currently transparent and you don't have to
wonder.

-- 
Peter Eisentraut              http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 20:15  Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Peter Eisentraut @ 2016-10-24 20:15 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; +Cc: pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 10/24/16 11:57 AM, Robert Haas wrote:
> Today, since the host part can't include a
> port specifier, it's regarded as part of the IP address, and I think
> it would probably be a bad idea to change that, as I believe Victor's
> patch would.  He seems to have it in mind that we could allow things
> like host=[1:2:3::4:5:6] or host=[1:2:3::4:5]:6, which would might be
> helpful for the future but doesn't avoid changing the meaning of
> connection strings that work today.

Let's keep in mind here that the decision to allow database names to
contain a connection parameter substructure has caused some security
issues.  Let's not create more levels of ambiguity and the need to pass
around override flags.

-- 
Peter Eisentraut              http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-24 20:40  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 2 replies; 165+ messages in thread

From: Alvaro Herrera @ 2016-10-24 20:40 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

Robert Haas wrote:

> While I was experimenting with this today, I discovered a problem of
> interpretation related to IPv6 addresses.  Internally, a postgresql://
> URL and a connection string are converted into the same format, so
> postgresql://a,b/ means just the same thing as host=a,b.  I thought
> that could similarly decide that postgresql://a:123,b:456/ is going to
> get translated to host=a:123,b:456 and then there can be further code
> to parse that into a list of host-and-port pairs.  However, if you do
> that, then something like host=1:2:3::4:5:6 is fundamentally
> ambiguous.  That :6 is equally valid either as part of the IP address
> or as a trailing port number specification, and there's no a priori
> way to know which it is.  Today, since the host part can't include a
> port specifier, it's regarded as part of the IP address, and I think
> it would probably be a bad idea to change that, as I believe Victor's
> patch would.  He seems to have it in mind that we could allow things
> like host=[1:2:3::4:5:6] or host=[1:2:3::4:5]:6, which would might be
> helpful for the future but doesn't avoid changing the meaning of
> connection strings that work today.

Umm, my recollection regarding IPv6 parsing in the URI syntax is that
those must appear inside square brackets -- it's not valid to have the
IPv6 address outside brackets, and the port number is necessarily
outside the brackets.  So there's no ambiguity.  If the current patch is
allowing IPv6 address to appear outside of brackets, that seems like a
bug to me.

The string conninfo spec should not accept port numbers in the "host"
part.  (Does it?)

> So now I think that to make this work correctly, we're going to need
> to change both the URL parser and also add parsing for the host and
> port.  Let's say the user says this:
> 
> postgresql://[1::2]:3,[4::5],[6::7]::8/

(There's a double colon before 8, I suppose that's just a typo.)

> What I think we need to do is translate that into this:
> 
> host=1::2,4::5,6::7 port=3,,8
> 
> Note the double-comma, indicating a blank port number for the second
> URL component.

Sounds reasonable.

> And then they might write one where the host and
> port parts don't have the same number of components, like this:
> 
> host=a,b,c port=3,4
> or
> host=a,b port=3,4,5
> 
> It is obvious what is meant if multiple hosts are given but only a
> single port number is specified; it is also obvious what is meant if
> the number of ports is equal to the number of hosts.

Agreed -- seems like we can accept both those cases.

> It is not obvious what it means if there are multiple ports but the
> number doesn't equal the number of hosts.

I think we should reject the case of differing number of elements and
neither host nor port is a singleton, as an error.  The suggestion to
ignore some parts seems too error-prone.

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-25 08:15  Amit Kapila <amit.kapila16@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Amit Kapila @ 2016-10-25 08:15 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Oct 25, 2016 at 2:10 AM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Robert Haas wrote:
>
>
>> It is not obvious what it means if there are multiple ports but the
>> number doesn't equal the number of hosts.
>
> I think we should reject the case of differing number of elements and
> neither host nor port is a singleton, as an error.  The suggestion to
> ignore some parts seems too error-prone.
>

+1. I also think returning error is better option in above case.


-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-25 17:23  Robert Haas <robertmhaas@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-10-25 17:23 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Oct 24, 2016 at 4:40 PM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Umm, my recollection regarding IPv6 parsing in the URI syntax is that
> those must appear inside square brackets -- it's not valid to have the
> IPv6 address outside brackets, and the port number is necessarily
> outside the brackets.  So there's no ambiguity.  If the current patch is
> allowing IPv6 address to appear outside of brackets, that seems like a
> bug to me.

I agree.

> The string conninfo spec should not accept port numbers in the "host"
> part.  (Does it?)

Not currently, but the proposed patch would cause it to do so.

>> So now I think that to make this work correctly, we're going to need
>> to change both the URL parser and also add parsing for the host and
>> port.  Let's say the user says this:
>>
>> postgresql://[1::2]:3,[4::5],[6::7]::8/
>
> (There's a double colon before 8, I suppose that's just a typo.)

Oh, yeah.  Right.

>> It is not obvious what it means if there are multiple ports but the
>> number doesn't equal the number of hosts.
>
> I think we should reject the case of differing number of elements and
> neither host nor port is a singleton, as an error.  The suggestion to
> ignore some parts seems too error-prone.

OK, can do.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-25 17:26  Robert Haas <robertmhaas@gmail.com>
  parent: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-10-25 17:26 UTC (permalink / raw)
  To: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Oct 24, 2016 at 4:15 PM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:
> On 10/24/16 11:57 AM, Robert Haas wrote:
>> Today, since the host part can't include a
>> port specifier, it's regarded as part of the IP address, and I think
>> it would probably be a bad idea to change that, as I believe Victor's
>> patch would.  He seems to have it in mind that we could allow things
>> like host=[1:2:3::4:5:6] or host=[1:2:3::4:5]:6, which would might be
>> helpful for the future but doesn't avoid changing the meaning of
>> connection strings that work today.
>
> Let's keep in mind here that the decision to allow database names to
> contain a connection parameter substructure has caused some security
> issues.  Let's not create more levels of ambiguity and the need to pass
> around override flags.

I agree.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-26 15:19  Robert Haas <robertmhaas@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-10-26 15:19 UTC (permalink / raw)
  To: Peter van Hardenberg <pvh@pvh.ca>; +Cc: Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Oct 24, 2016 at 11:57 AM, Robert Haas <robertmhaas@gmail.com> wrote:
> So now I think that to make this work correctly, we're going to need
> to change both the URL parser and also add parsing for the host and
> port.  Let's say the user says this:
>
> postgresql://[1::2]:3,[4::5],[6::7]::8/
>
> What I think we need to do is translate that into this:
>
> host=1::2,4::5,6::7 port=3,,8

So here's a patch implementing that.  This seems to work, but I
haven't tested it in incredible detail at this point, so testing from
others would be greatly appreciated (the handling of .pgpass files, in
particular, I have not tested).  This is loosely inspired by Victor's
patch but rewritten from scratch to fix the various design issues
which I've commented on in previous emails on this thread.

Some notes on decisions that I made while implementing this:

- Only the host= and port= parameter support multiple, comma-separated
values.  In particular, you can only specify a single password.
However, you can still end up with different passwords for connections
to different servers if the passwords are read from .pgpass.

- The PQhost(), PQport(), and PQpass() now functions return the
information for the host to which we actually connected or to the
first one in the list if we haven't tried to connect yet.  Looking
through where these functions are actually used in our source code,
this behavior seems more useful than any other I could imagine.  On
the other hand, PQreset() will retry the connection starting with the
first host in the original list.

- The hostorder, target_server_type, and failover_timeout parameters
from Victor's patch are not present in this version.  I think we can
add those things in future patches once the basic functionality is
committed.  Or maybe we'll decide that we don't want those things or
that we want something different instead, which is fine, too.  The
point is, they don't need to be there in the first patch.

- As requested, it's an error if you specify N hosts and K port
numbers where N != K.  However, K = 1 is always allowed; that is, if
only a single port number is specified, it applies to all hosts.

- I have made an attempt to update the documentation appropriately but
there might be other sections which also need to be adjusted.

Let me know your thoughts.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

multihost-v1.patch (application/x-download, 31.5K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..d04dba7 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -756,8 +756,10 @@ PGPing PQping(const char *conninfo); Several <application>libpq</> functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain <literal>keyword = value</literal> strings - and <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC - 3986</ulink> URIs. + and URIs. URIs generally follow + <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC + 3986</ulink>, except that multi-host connection strings are allowed + as further described below. </para> <sect3> @@ -792,7 +794,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://host1:123,host2:456/somedb </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -856,6 +859,15 @@ postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </programlisting> </para> + + <para> + It is possible to specify multiple host components, each with an optional + port component, in a single URI. A URI of the form + <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal> + is equivalent to a connection string of the form + <literal>host=host1,host2,host3 port=port1,port2,port3</literal>. Each + host will be tried in turn until a connection is successfully established. + </para> </sect3> </sect2> @@ -870,12 +882,13 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <term><literal>host</literal></term> <listitem> <para> - Name of host to connect to.<indexterm><primary>host name</></> - If this begins with a slash, it specifies Unix-domain + Comma-separated list of host names.<indexterm><primary>host name</></> + If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the - name of the directory in which the socket file is stored. The - default behavior when <literal>host</literal> is not specified - is to connect to a Unix-domain + name of the directory in which the socket file is stored. If + multiple host names are specified, each will be tried in turn in + the order given. The default behavior when <literal>host</literal> is + not specified is to connect to a Unix-domain socket<indexterm><primary>Unix domain socket</></> in <filename>/tmp</filename> (or whatever socket directory was specified when <productname>PostgreSQL</> was built). On machines without @@ -950,6 +963,9 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname Port number to connect to at the server host, or socket file name extension for Unix-domain connections.<indexterm><primary>port</></> + If the <literal>host</> parameter included multiple, comma-separated + hosts, this parameter may specify a list of ports of equal length, + or it may specify a single port number to be used for all hosts. </para> </listitem> </varlistentry> @@ -1394,7 +1410,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The following functions return parameter values established at connection. - These values are fixed for the life of the <structname>PGconn</> object. + These values are fixed for the life of the connection. If a multi-host + connection string is used, the values of <function>PQhost</>, + <function>PQport</>, and <function>PQpass</> can change if a new connection + is established using the same <structname>PGconn</> object. Other values + are fixed for the lifetime of the <structname>PGconn</> object. <variablelist> <varlistentry id="libpq-pqdb"> diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 404bc93..19171fb 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -683,20 +683,26 @@ pg_fe_sendauth(AuthRequest areq, PGconn *conn) case AUTH_REQ_MD5: case AUTH_REQ_PASSWORD: - conn->password_needed = true; - if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { - printfPQExpBuffer(&conn->errorMessage, - PQnoPasswordSupplied); - return STATUS_ERROR; - } - if (pg_password_sendauth(conn, conn->pgpass, areq) != STATUS_OK) - { - printfPQExpBuffer(&conn->errorMessage, + char *password = conn->connhost[conn->whichhost].password; + + if (password == NULL) + password = conn->pgpass; + conn->password_needed = true; + if (password == NULL || password[0] == '\0') + { + printfPQExpBuffer(&conn->errorMessage, + PQnoPasswordSupplied); + return STATUS_ERROR; + } + if (pg_password_sendauth(conn, password, areq) != STATUS_OK) + { + printfPQExpBuffer(&conn->errorMessage, "fe_sendauth: error sending password authentication\n"); - return STATUS_ERROR; + return STATUS_ERROR; + } + break; } - break; case AUTH_REQ_SCM_CREDS: if (pg_local_sendauth(conn) != STATUS_OK) diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..255e20a 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -771,6 +771,147 @@ static bool connectOptions2(PGconn *conn) { /* + * Allocate memory for details about each host to which we might possibly + * try to connect. If pghostaddr is set, we're only going to try to + * connect to that one particular address. If it's not, we'll use pghost, + * which may contain multiple, comma-separated names. + */ + conn->nconnhost = 1; + conn->whichhost = 0; + if ((conn->pghostaddr == NULL || conn->pghostaddr[0] == '\0') + && conn->pghost != NULL) + { + char *s; + + for (s = conn->pghost; *s != '\0'; ++s) + if (*s == ',') + conn->nconnhost++; + } + conn->connhost = (pg_conn_host *) + calloc(conn->nconnhost, sizeof(pg_conn_host)); + if (conn->connhost == NULL) + goto oom_error; + + /* + * We now have one pg_conn_host structure per possible host. Fill in + * the host details for each one. + */ + if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') + { + conn->connhost[0].host = strdup(conn->pghostaddr); + if (conn->connhost[0].host == NULL) + goto oom_error; + conn->connhost[0].type = CHT_HOST_ADDRESS; + } + else if (conn->pghost != NULL && conn->pghost[0] != '\0') + { + int i = 0; + char *s = conn->pghost; + + while (1) + { + char *e = s; + + /* + * Search for the end of the current hostname; a comma or + * end-of-string acts as a terminator. + */ + while (*e != '\0' && *e != ',') + ++e; + + /* Copy the hostname whose bounds we just identified. */ + conn->connhost[i].host = (char *) malloc(sizeof(char) * (e - s)); + if (conn->connhost[i].host == NULL) + goto oom_error; + memcpy(conn->connhost[i].host, s, e - s); + conn->connhost[i].host[e - s] = '\0'; + + /* Identify the type of host. */ + conn->connhost[i].type = CHT_HOST_NAME; +#ifdef HAVE_UNIX_SOCKETS + if (is_absolute_path(conn->connhost[i].host)) + conn->connhost[i].type = CHT_UNIX_SOCKET; +#endif + + /* Prepare to find the next host (if any). */ + if (*e == '\0') + break; + s = e + 1; + i++; + } + } + else + { +#ifdef HAVE_UNIX_SOCKETS + conn->connhost[0].host = strdup(DEFAULT_PGSOCKET_DIR); + conn->connhost[0].type = CHT_UNIX_SOCKET; +#else + conn->connhost[0].host = strdup(DefaultHost); + conn->connhost[0].type = CHT_HOST_NAME; +#endif + if (conn->connhost[0].host == NULL) + goto oom_error; + } + + /* + * Next, work out the port number corresponding to each host name. + */ + if (conn->pgport != NULL && conn->pgport[0] != '\0') + { + int i = 0; + char *s = conn->pgport; + int nports = 1; + + for (i = 0; i < conn->nconnhost; ++i) + { + char *e = s; + + /* Search for the end of the current port number. */ + while (*e != '\0' && *e != ',') + ++e; + + /* + * If we found a port number of non-zero length, copy it. + * Otherwise, insert the default port number. + */ + if (e > s) + { + conn->connhost[i].port = + (char *) malloc(sizeof(char) * (e - s)); + if (conn->connhost[i].port == NULL) + goto oom_error; + memcpy(conn->connhost[i].port, s, e - s); + conn->connhost[i].port[e - s] = '\0'; + } + + /* + * Move on to the next port number, unless there are no more. + * (If only one part number is specified, we reuse it for every + * host.) + */ + if (*e != '\0') + { + s = e + 1; + ++nports; + } + } + + /* + * If multiple ports were specified, there must be exactly as many + * ports as there were hosts. Otherwise, we do not know how to match + * them up. + */ + if (nports != 1 && nports != conn->nconnhost) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not match %d port numbers to %d hosts\n"), + nports, conn->nconnhost); + return false; + } + } + + /* * If user name was not given, fetch it. (Most likely, the fetch will * fail, since the only way we get here is if pg_fe_getauthname() failed * during conninfo_add_defaults(). But now we want an error message.) @@ -800,33 +941,27 @@ connectOptions2(PGconn *conn) } /* - * Supply default password if none given + * Supply default password if none given. Note that the password might + * be different for each host/port pair. */ if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { + int i; + if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, - conn->dbName, conn->pguser); - if (conn->pgpass == NULL) + conn->pgpass = strdup(DefaultPassword); + if (!conn->pgpass) + goto oom_error; + for (i = 0; i < conn->nconnhost; ++i) { - conn->pgpass = strdup(DefaultPassword); - if (!conn->pgpass) - goto oom_error; + conn->connhost[i].password = + PasswordFromFile(conn->connhost[i].host, + conn->connhost[i].port, + conn->dbName, conn->pguser); + if (conn->connhost[i].password != NULL) + conn->dot_pgpass_used = true; } - else - conn->dot_pgpass_used = true; - } - - /* - * Allow unix socket specification in the host name - */ - if (conn->pghost && is_absolute_path(conn->pghost)) - { - if (conn->pgunixsocket) - free(conn->pgunixsocket); - conn->pgunixsocket = conn->pghost; - conn->pghost = NULL; } /* @@ -1142,6 +1277,7 @@ connectFailureMessage(PGconn *conn, int errorno) { char host_addr[NI_MAXHOST]; const char *displayed_host; + const char *displayed_port; struct sockaddr_storage *addr = &conn->raddr.addr; /* @@ -1171,12 +1307,11 @@ connectFailureMessage(PGconn *conn, int errorno) else strcpy(host_addr, "???"); - if (conn->pghostaddr && conn->pghostaddr[0] != '\0') - displayed_host = conn->pghostaddr; - else if (conn->pghost && conn->pghost[0] != '\0') - displayed_host = conn->pghost; - else - displayed_host = DefaultHost; + /* To which host and port were we actually connecting? */ + displayed_host = conn->connhost[conn->whichhost].host; + displayed_port = conn->connhost[conn->whichhost].port; + if (displayed_port == NULL || displayed_port[0] == '\0') + displayed_port = DEF_PGPORT_STR; /* * If the user did not supply an IP address using 'hostaddr', and @@ -1192,7 +1327,7 @@ connectFailureMessage(PGconn *conn, int errorno) SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, host_addr, - conn->pgport); + displayed_port); else appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not connect to server: %s\n" @@ -1200,7 +1335,7 @@ connectFailureMessage(PGconn *conn, int errorno) "\tTCP/IP connections on port %s?\n"), SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, - conn->pgport); + displayed_port); } } @@ -1390,12 +1525,9 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { - int portnum; char portstr[MAXPGPATH]; - struct addrinfo *addrs = NULL; - struct addrinfo hint; - const char *node; int ret; + int i; if (!conn) return 0; @@ -1408,83 +1540,86 @@ connectDBStart(PGconn *conn) conn->outCount = 0; /* - * Determine the parameters to pass to pg_getaddrinfo_all. + * Look up socket addresses for each possible host using + * pg_getaddrinfo_all. */ + for (i = 0; i < conn->nconnhost; ++i) + { + pg_conn_host *ch = &conn->connhost[i]; + char *node = ch->host; + struct addrinfo hint; + int thisport; - /* Initialize hint structure */ - MemSet(&hint, 0, sizeof(hint)); - hint.ai_socktype = SOCK_STREAM; - hint.ai_family = AF_UNSPEC; + /* Initialize hint structure */ + MemSet(&hint, 0, sizeof(hint)); + hint.ai_socktype = SOCK_STREAM; + hint.ai_family = AF_UNSPEC; - /* Set up port number as a string */ - if (conn->pgport != NULL && conn->pgport[0] != '\0') - { - portnum = atoi(conn->pgport); - if (portnum < 1 || portnum > 65535) + /* Figure out the port number we're going to use. */ + if (ch->port == NULL) + thisport = DEF_PGPORT; + else { - appendPQExpBuffer(&conn->errorMessage, + thisport = atoi(ch->port); + if (thisport < 1 || thisport > 65535) + { + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid port number: \"%s\"\n"), - conn->pgport); - conn->options_valid = false; - goto connect_errReturn; + ch->port); + conn->options_valid = false; + goto connect_errReturn; + } } - } - else - portnum = DEF_PGPORT; - snprintf(portstr, sizeof(portstr), "%d", portnum); + snprintf(portstr, sizeof(portstr), "%d", thisport); - if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') - { - /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; - hint.ai_family = AF_UNSPEC; - hint.ai_flags = AI_NUMERICHOST; - } - else if (conn->pghost != NULL && conn->pghost[0] != '\0') - { - /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; - hint.ai_family = AF_UNSPEC; - } - else - { + /* Set up for name resolution. */ + switch (ch->type) + { + case CHT_HOST_NAME: + break; + case CHT_HOST_ADDRESS: + hint.ai_flags = AI_NUMERICHOST; + break; + case CHT_UNIX_SOCKET: #ifdef HAVE_UNIX_SOCKETS - /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; - hint.ai_family = AF_UNIX; - UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); - if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + node = NULL; + hint.ai_family = AF_UNIX; + UNIXSOCK_PATH(portstr, thisport, ch->host); + if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), + portstr, + (int) (UNIXSOCK_PATH_BUFLEN - 1)); + conn->options_valid = false; + goto connect_errReturn; + } +#else + Assert(false); +#endif + break; + } + + /* Use pg_getaddrinfo_all() to resolve the address */ + ret = pg_getaddrinfo_all(node, portstr, &hint, &ch->addrlist); + if (ret || !ch->addrlist) { - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), - portstr, - (int) (UNIXSOCK_PATH_BUFLEN - 1)); + if (node) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + portstr, gai_strerror(ret)); + if (ch->addrlist) + { + pg_freeaddrinfo_all(hint.ai_family, ch->addrlist); + ch->addrlist = NULL; + } conn->options_valid = false; goto connect_errReturn; } -#else - /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; - hint.ai_family = AF_UNSPEC; -#endif /* HAVE_UNIX_SOCKETS */ - } - - /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); - else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); - conn->options_valid = false; - goto connect_errReturn; } #ifdef USE_SSL @@ -1498,9 +1633,8 @@ connectDBStart(PGconn *conn) /* * Set up to try to connect, with protocol 3.0 as the first attempt. */ - conn->addrlist = addrs; - conn->addr_cur = addrs; - conn->addrlist_family = hint.ai_family; + conn->whichhost = 0; + conn->addr_cur = conn->connhost[0].addrlist; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; @@ -1702,11 +1836,27 @@ keep_going: /* We will come back to here until there is * returned by pg_getaddrinfo_all(). conn->addr_cur is the * next one to try. We fail when we run out of addresses. */ - while (conn->addr_cur != NULL) + for (;;) { - struct addrinfo *addr_cur = conn->addr_cur; + struct addrinfo *addr_cur; + + /* + * Advance to next possible host, if we've tried all of + * the addresses for the current host. + */ + if (conn->addr_cur == NULL) + { + if (++conn->whichhost >= conn->nconnhost) + { + conn->whichhost = 0; + break; + } + conn->addr_cur = + conn->connhost[conn->whichhost].addrlist; + } /* Remember current address for possible error msg */ + addr_cur = conn->addr_cur; memcpy(&conn->raddr.addr, addr_cur->ai_addr, addr_cur->ai_addrlen); conn->raddr.salen = addr_cur->ai_addrlen; @@ -1718,7 +1868,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = addr_cur->ai_next; continue; @@ -1944,7 +2095,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; @@ -2599,9 +2751,25 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + /* We can release the address lists now. */ + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ @@ -2858,6 +3026,21 @@ freePGconn(PGconn *conn) free(conn->events[i].name); } + /* clean up pg_conn_host structures */ + if (conn->connhost != NULL) + { + for (i = 0; i < conn->nconnhost; ++i) + { + if (conn->connhost[i].host != NULL) + free(conn->connhost[i].host); + if (conn->connhost[i].port != NULL) + free(conn->connhost[i].port); + if (conn->connhost[i].password != NULL) + free(conn->connhost[i].password); + } + free(conn->connhost); + } + if (conn->client_encoding_initial) free(conn->client_encoding_initial); if (conn->events) @@ -2868,8 +3051,6 @@ freePGconn(PGconn *conn) free(conn->pghostaddr); if (conn->pgport) free(conn->pgport); - if (conn->pgunixsocket) - free(conn->pgunixsocket); if (conn->pgtty) free(conn->pgtty); if (conn->connect_timeout) @@ -2983,8 +3164,24 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) @@ -4720,7 +4917,10 @@ conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...] * * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded - * by literal square brackets. + * by literal square brackets. As an extension, we also allow multiple + * netloc[:port] specifications, separated by commas: + * + * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...] * * Any of the URI parts might use percent-encoding (%xy). */ @@ -4736,6 +4936,17 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, char *user = NULL; char *host = NULL; bool retval = false; + PQExpBufferData hostbuf; + PQExpBufferData portbuf; + + initPQExpBuffer(&hostbuf); + initPQExpBuffer(&portbuf); + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("out of memory\n")); + return false; + } /* need a modifiable copy of the input URI */ buf = strdup(uri); @@ -4810,85 +5021,104 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, } /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. + * There may be multiple netloc[:port] pairs, each separated from the next + * by a comma. When we initially enter this loop, "p" has been + * incremented past optional URI credential information at this point and + * now points at the "netloc" part of the URI. On subsequent loop + * iterations, "p" has been incremented past the comma separator and now + * points at the start of the next "netloc". */ - if (*p == '[') + for (;;) { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; - } - if (p == host) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); - goto cleanup; - } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - /* - * The address may be followed by a port specifier or a slash or a - * query. + * Look for IPv6 address. */ - if (*p && *p != ':' && *p != '/' && *p != '?') + if (*p == '[') { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; + host = ++p; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == host) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + + /* Cut off the bracket and advance */ + *(p++) = '\0'; + + /* + * The address may be followed by a port specifier or a slash or a + * query or a separator comma. + */ + if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ + host = p; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * Look for port specifier (colon) or end of host specifier (slash) + * or query (question mark) or host separator (comma). + */ + while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + ++p; + } - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* Save the hostname terminator before we null it */ + prevchar = *p; + *p = '\0'; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + appendPQExpBufferStr(&hostbuf, host); + if (prevchar == ':') + { + const char *port = ++p; /* advance past host terminator */ - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + while (*p && *p != '/' && *p != '?' && *p != ',') + ++p; - while (*p && *p != '/' && *p != '?') - ++p; + prevchar = *p; + *p = '\0'; - prevchar = *p; - *p = '\0'; + appendPQExpBufferStr(&portbuf, port); + } - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) - goto cleanup; + if (prevchar != ',') + break; + ++p; /* advance past comma separator */ + appendPQExpBufferStr(&hostbuf, ","); + appendPQExpBufferStr(&portbuf, ","); } + /* Save final values for host and port. */ + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + goto cleanup; + if (hostbuf.data[0] && + !conninfo_storeval(options, "host", hostbuf.data, + errorMessage, false, true)) + goto cleanup; + if (portbuf.data[0] && + !conninfo_storeval(options, "port", portbuf.data, + errorMessage, false, true)) + goto cleanup; + if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -4923,6 +5153,8 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, retval = true; cleanup: + termPQExpBuffer(&hostbuf); + termPQExpBuffer(&portbuf); free(buf); return retval; } @@ -5344,6 +5576,8 @@ PQpass(const PGconn *conn) { if (!conn) return NULL; + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].password; return conn->pgpass; } @@ -5352,15 +5586,14 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].host; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { #ifdef HAVE_UNIX_SOCKETS - if (conn->pgunixsocket != NULL && conn->pgunixsocket[0] != '\0') - return conn->pgunixsocket; - else - return DEFAULT_PGSOCKET_DIR; + return DEFAULT_PGSOCKET_DIR; #else return DefaultHost; #endif @@ -5372,6 +5605,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].port; return conn->pgport; } diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 7007692..854ec89 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -292,6 +292,30 @@ typedef struct pgDataValue const char *value; /* data value, without zero-termination */ } PGdataValue; +typedef enum pg_conn_host_type +{ + CHT_HOST_NAME, + CHT_HOST_ADDRESS, + CHT_UNIX_SOCKET +} pg_conn_host_type; + +/* + * pg_conn_host stores all information about one of possibly several hosts + * mentioned in the connection string. Derived by splitting the pghost + * on the comma character and then parsing each segment. + */ +typedef struct pg_conn_host +{ + char *host; /* host name or address, or socket path */ + pg_conn_host_type type; /* type of host */ + char *port; /* port number for this host; if not NULL, + * overrrides the PGConn's pgport */ + char *password; /* password for this host, read from the + * password file. only set if the PGconn's + * pgpass field is NULL. */ + struct addrinfo *addrlist; /* list of possible backend addresses */ +} pg_conn_host; + /* * PGconn stores all the state data associated with a single connection * to a backend. @@ -299,13 +323,15 @@ typedef struct pgDataValue struct pg_conn { /* Saved values of connection options */ - char *pghost; /* the machine on which the server is running */ + char *pghost; /* the machine on which the server is running, + * or a path to a UNIX-domain socket, or a + * comma-separated list of machines and/or + * paths, optionally with port suffixes; if + * NULL, use DEFAULT_PGSOCKET_DIR */ char *pghostaddr; /* the numeric IP address of the machine on * which the server is running. Takes * precedence over above. */ char *pgport; /* the server's communication port number */ - char *pgunixsocket; /* the directory of the server's Unix-domain - * socket; if NULL, use DEFAULT_PGSOCKET_DIR */ char *pgtty; /* tty on which the backend messages is * displayed (OBSOLETE, NOT USED) */ char *connect_timeout; /* connection timeout (numeric string) */ @@ -363,6 +389,11 @@ struct pg_conn PGnotify *notifyHead; /* oldest unreported Notify msg */ PGnotify *notifyTail; /* newest unreported Notify msg */ + /* Support for multiple hosts in connection string */ + int nconnhost; /* # of possible hosts */ + int whichhost; /* host we're currently considering */ + pg_conn_host *connhost; /* details about each possible host */ + /* Connection data */ pgsocket sock; /* FD for socket, PGINVALID_SOCKET if * unconnected */ @@ -378,9 +409,7 @@ struct pg_conn bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */ /* Transient state needed while establishing connection */ - struct addrinfo *addrlist; /* list of possible backend addresses */ - struct addrinfo *addr_cur; /* the one currently being tried */ - int addrlist_family; /* needed to know how to free addrlist */ + struct addrinfo *addr_cur; /* backend address currently being tried */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-27 13:46  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-10-27 13:46 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Oct 26, 2016 at 8:49 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Let me know your thoughts.

One small issue. I tried to run make installcheck after applying patch
there seems to be a invalid write access in code (resulting in crash).

==118997== Invalid write of size 1
==118997==    at 0x4E3DDF1: connectOptions2 (fe-connect.c:884)
==118997==    by 0x4E3D6FF: PQconnectStartParams (fe-connect.c:608)
==118997==    by 0x4E3D553: PQconnectdbParams (fe-connect.c:465)
==118997==    by 0x413067: main (startup.c:245)
==118997==  Address 0x5dc4014 is 0 bytes after a block of size 4 alloc'd
==118997==    at 0x4C29BFD: malloc (in
/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==118997==    by 0x4E3DD3C: connectOptions2 (fe-connect.c:880)
==118997==    by 0x4E3D6FF: PQconnectStartParams (fe-connect.c:608)
==118997==    by 0x4E3D553: PQconnectdbParams (fe-connect.c:465)
==118997==    by 0x413067: main (startup.c:245)

After locally fixing this by allocating an extra space for string terminal
character. make installcheck  tests pass.
-(char *) malloc(sizeof(char) * (e - s));
+ (char *) malloc(sizeof(char) * (e - s + 1));

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-10-27 17:45  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-10-27 17:45 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Oct 27, 2016 at 9:46 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Wed, Oct 26, 2016 at 8:49 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Let me know your thoughts.
>
> One small issue. I tried to run make installcheck after applying patch there
> seems to be a invalid write access in code (resulting in crash).
>
> ==118997== Invalid write of size 1
> ==118997==    at 0x4E3DDF1: connectOptions2 (fe-connect.c:884)
> ==118997==    by 0x4E3D6FF: PQconnectStartParams (fe-connect.c:608)
> ==118997==    by 0x4E3D553: PQconnectdbParams (fe-connect.c:465)
> ==118997==    by 0x413067: main (startup.c:245)
> ==118997==  Address 0x5dc4014 is 0 bytes after a block of size 4 alloc'd
> ==118997==    at 0x4C29BFD: malloc (in
> /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
> ==118997==    by 0x4E3DD3C: connectOptions2 (fe-connect.c:880)
> ==118997==    by 0x4E3D6FF: PQconnectStartParams (fe-connect.c:608)
> ==118997==    by 0x4E3D553: PQconnectdbParams (fe-connect.c:465)
> ==118997==    by 0x413067: main (startup.c:245)
>
> After locally fixing this by allocating an extra space for string terminal
> character. make installcheck  tests pass.
> -(char *) malloc(sizeof(char) * (e - s));
> + (char *) malloc(sizeof(char) * (e - s + 1));

Thanks.  Here's a new version with a fix for that issue and also a fix
for PQconnectionNeedsPassword(), which was busted in v1.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

multihost-v2.patch (application/x-download, 32.0K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..d04dba7 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -756,8 +756,10 @@ PGPing PQping(const char *conninfo); Several <application>libpq</> functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain <literal>keyword = value</literal> strings - and <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC - 3986</ulink> URIs. + and URIs. URIs generally follow + <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC + 3986</ulink>, except that multi-host connection strings are allowed + as further described below. </para> <sect3> @@ -792,7 +794,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://host1:123,host2:456/somedb </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -856,6 +859,15 @@ postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </programlisting> </para> + + <para> + It is possible to specify multiple host components, each with an optional + port component, in a single URI. A URI of the form + <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal> + is equivalent to a connection string of the form + <literal>host=host1,host2,host3 port=port1,port2,port3</literal>. Each + host will be tried in turn until a connection is successfully established. + </para> </sect3> </sect2> @@ -870,12 +882,13 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <term><literal>host</literal></term> <listitem> <para> - Name of host to connect to.<indexterm><primary>host name</></> - If this begins with a slash, it specifies Unix-domain + Comma-separated list of host names.<indexterm><primary>host name</></> + If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the - name of the directory in which the socket file is stored. The - default behavior when <literal>host</literal> is not specified - is to connect to a Unix-domain + name of the directory in which the socket file is stored. If + multiple host names are specified, each will be tried in turn in + the order given. The default behavior when <literal>host</literal> is + not specified is to connect to a Unix-domain socket<indexterm><primary>Unix domain socket</></> in <filename>/tmp</filename> (or whatever socket directory was specified when <productname>PostgreSQL</> was built). On machines without @@ -950,6 +963,9 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname Port number to connect to at the server host, or socket file name extension for Unix-domain connections.<indexterm><primary>port</></> + If the <literal>host</> parameter included multiple, comma-separated + hosts, this parameter may specify a list of ports of equal length, + or it may specify a single port number to be used for all hosts. </para> </listitem> </varlistentry> @@ -1394,7 +1410,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The following functions return parameter values established at connection. - These values are fixed for the life of the <structname>PGconn</> object. + These values are fixed for the life of the connection. If a multi-host + connection string is used, the values of <function>PQhost</>, + <function>PQport</>, and <function>PQpass</> can change if a new connection + is established using the same <structname>PGconn</> object. Other values + are fixed for the lifetime of the <structname>PGconn</> object. <variablelist> <varlistentry id="libpq-pqdb"> diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 404bc93..19171fb 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -683,20 +683,26 @@ pg_fe_sendauth(AuthRequest areq, PGconn *conn) case AUTH_REQ_MD5: case AUTH_REQ_PASSWORD: - conn->password_needed = true; - if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { - printfPQExpBuffer(&conn->errorMessage, - PQnoPasswordSupplied); - return STATUS_ERROR; - } - if (pg_password_sendauth(conn, conn->pgpass, areq) != STATUS_OK) - { - printfPQExpBuffer(&conn->errorMessage, + char *password = conn->connhost[conn->whichhost].password; + + if (password == NULL) + password = conn->pgpass; + conn->password_needed = true; + if (password == NULL || password[0] == '\0') + { + printfPQExpBuffer(&conn->errorMessage, + PQnoPasswordSupplied); + return STATUS_ERROR; + } + if (pg_password_sendauth(conn, password, areq) != STATUS_OK) + { + printfPQExpBuffer(&conn->errorMessage, "fe_sendauth: error sending password authentication\n"); - return STATUS_ERROR; + return STATUS_ERROR; + } + break; } - break; case AUTH_REQ_SCM_CREDS: if (pg_local_sendauth(conn) != STATUS_OK) diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..b5e12cc 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -771,6 +771,148 @@ static bool connectOptions2(PGconn *conn) { /* + * Allocate memory for details about each host to which we might possibly + * try to connect. If pghostaddr is set, we're only going to try to + * connect to that one particular address. If it's not, we'll use pghost, + * which may contain multiple, comma-separated names. + */ + conn->nconnhost = 1; + conn->whichhost = 0; + if ((conn->pghostaddr == NULL || conn->pghostaddr[0] == '\0') + && conn->pghost != NULL) + { + char *s; + + for (s = conn->pghost; *s != '\0'; ++s) + if (*s == ',') + conn->nconnhost++; + } + conn->connhost = (pg_conn_host *) + calloc(conn->nconnhost, sizeof(pg_conn_host)); + if (conn->connhost == NULL) + goto oom_error; + + /* + * We now have one pg_conn_host structure per possible host. Fill in + * the host details for each one. + */ + if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') + { + conn->connhost[0].host = strdup(conn->pghostaddr); + if (conn->connhost[0].host == NULL) + goto oom_error; + conn->connhost[0].type = CHT_HOST_ADDRESS; + } + else if (conn->pghost != NULL && conn->pghost[0] != '\0') + { + int i = 0; + char *s = conn->pghost; + + while (1) + { + char *e = s; + + /* + * Search for the end of the current hostname; a comma or + * end-of-string acts as a terminator. + */ + while (*e != '\0' && *e != ',') + ++e; + + /* Copy the hostname whose bounds we just identified. */ + conn->connhost[i].host = + (char *) malloc(sizeof(char) * (e - s + 1)); + if (conn->connhost[i].host == NULL) + goto oom_error; + memcpy(conn->connhost[i].host, s, e - s); + conn->connhost[i].host[e - s] = '\0'; + + /* Identify the type of host. */ + conn->connhost[i].type = CHT_HOST_NAME; +#ifdef HAVE_UNIX_SOCKETS + if (is_absolute_path(conn->connhost[i].host)) + conn->connhost[i].type = CHT_UNIX_SOCKET; +#endif + + /* Prepare to find the next host (if any). */ + if (*e == '\0') + break; + s = e + 1; + i++; + } + } + else + { +#ifdef HAVE_UNIX_SOCKETS + conn->connhost[0].host = strdup(DEFAULT_PGSOCKET_DIR); + conn->connhost[0].type = CHT_UNIX_SOCKET; +#else + conn->connhost[0].host = strdup(DefaultHost); + conn->connhost[0].type = CHT_HOST_NAME; +#endif + if (conn->connhost[0].host == NULL) + goto oom_error; + } + + /* + * Next, work out the port number corresponding to each host name. + */ + if (conn->pgport != NULL && conn->pgport[0] != '\0') + { + int i = 0; + char *s = conn->pgport; + int nports = 1; + + for (i = 0; i < conn->nconnhost; ++i) + { + char *e = s; + + /* Search for the end of the current port number. */ + while (*e != '\0' && *e != ',') + ++e; + + /* + * If we found a port number of non-zero length, copy it. + * Otherwise, insert the default port number. + */ + if (e > s) + { + conn->connhost[i].port = + (char *) malloc(sizeof(char) * (e - s + 1)); + if (conn->connhost[i].port == NULL) + goto oom_error; + memcpy(conn->connhost[i].port, s, e - s); + conn->connhost[i].port[e - s] = '\0'; + } + + /* + * Move on to the next port number, unless there are no more. + * (If only one part number is specified, we reuse it for every + * host.) + */ + if (*e != '\0') + { + s = e + 1; + ++nports; + } + } + + /* + * If multiple ports were specified, there must be exactly as many + * ports as there were hosts. Otherwise, we do not know how to match + * them up. + */ + if (nports != 1 && nports != conn->nconnhost) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not match %d port numbers to %d hosts\n"), + nports, conn->nconnhost); + return false; + } + } + + /* * If user name was not given, fetch it. (Most likely, the fetch will * fail, since the only way we get here is if pg_fe_getauthname() failed * during conninfo_add_defaults(). But now we want an error message.) @@ -800,33 +942,27 @@ connectOptions2(PGconn *conn) } /* - * Supply default password if none given + * Supply default password if none given. Note that the password might + * be different for each host/port pair. */ if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { + int i; + if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, - conn->dbName, conn->pguser); - if (conn->pgpass == NULL) + conn->pgpass = strdup(DefaultPassword); + if (!conn->pgpass) + goto oom_error; + for (i = 0; i < conn->nconnhost; ++i) { - conn->pgpass = strdup(DefaultPassword); - if (!conn->pgpass) - goto oom_error; + conn->connhost[i].password = + PasswordFromFile(conn->connhost[i].host, + conn->connhost[i].port, + conn->dbName, conn->pguser); + if (conn->connhost[i].password != NULL) + conn->dot_pgpass_used = true; } - else - conn->dot_pgpass_used = true; - } - - /* - * Allow unix socket specification in the host name - */ - if (conn->pghost && is_absolute_path(conn->pghost)) - { - if (conn->pgunixsocket) - free(conn->pgunixsocket); - conn->pgunixsocket = conn->pghost; - conn->pghost = NULL; } /* @@ -1142,6 +1278,7 @@ connectFailureMessage(PGconn *conn, int errorno) { char host_addr[NI_MAXHOST]; const char *displayed_host; + const char *displayed_port; struct sockaddr_storage *addr = &conn->raddr.addr; /* @@ -1171,12 +1308,11 @@ connectFailureMessage(PGconn *conn, int errorno) else strcpy(host_addr, "???"); - if (conn->pghostaddr && conn->pghostaddr[0] != '\0') - displayed_host = conn->pghostaddr; - else if (conn->pghost && conn->pghost[0] != '\0') - displayed_host = conn->pghost; - else - displayed_host = DefaultHost; + /* To which host and port were we actually connecting? */ + displayed_host = conn->connhost[conn->whichhost].host; + displayed_port = conn->connhost[conn->whichhost].port; + if (displayed_port == NULL || displayed_port[0] == '\0') + displayed_port = DEF_PGPORT_STR; /* * If the user did not supply an IP address using 'hostaddr', and @@ -1192,7 +1328,7 @@ connectFailureMessage(PGconn *conn, int errorno) SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, host_addr, - conn->pgport); + displayed_port); else appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not connect to server: %s\n" @@ -1200,7 +1336,7 @@ connectFailureMessage(PGconn *conn, int errorno) "\tTCP/IP connections on port %s?\n"), SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, - conn->pgport); + displayed_port); } } @@ -1390,12 +1526,9 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { - int portnum; char portstr[MAXPGPATH]; - struct addrinfo *addrs = NULL; - struct addrinfo hint; - const char *node; int ret; + int i; if (!conn) return 0; @@ -1408,83 +1541,86 @@ connectDBStart(PGconn *conn) conn->outCount = 0; /* - * Determine the parameters to pass to pg_getaddrinfo_all. + * Look up socket addresses for each possible host using + * pg_getaddrinfo_all. */ + for (i = 0; i < conn->nconnhost; ++i) + { + pg_conn_host *ch = &conn->connhost[i]; + char *node = ch->host; + struct addrinfo hint; + int thisport; - /* Initialize hint structure */ - MemSet(&hint, 0, sizeof(hint)); - hint.ai_socktype = SOCK_STREAM; - hint.ai_family = AF_UNSPEC; + /* Initialize hint structure */ + MemSet(&hint, 0, sizeof(hint)); + hint.ai_socktype = SOCK_STREAM; + hint.ai_family = AF_UNSPEC; - /* Set up port number as a string */ - if (conn->pgport != NULL && conn->pgport[0] != '\0') - { - portnum = atoi(conn->pgport); - if (portnum < 1 || portnum > 65535) + /* Figure out the port number we're going to use. */ + if (ch->port == NULL) + thisport = DEF_PGPORT; + else { - appendPQExpBuffer(&conn->errorMessage, + thisport = atoi(ch->port); + if (thisport < 1 || thisport > 65535) + { + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid port number: \"%s\"\n"), - conn->pgport); - conn->options_valid = false; - goto connect_errReturn; + ch->port); + conn->options_valid = false; + goto connect_errReturn; + } } - } - else - portnum = DEF_PGPORT; - snprintf(portstr, sizeof(portstr), "%d", portnum); + snprintf(portstr, sizeof(portstr), "%d", thisport); - if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') - { - /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; - hint.ai_family = AF_UNSPEC; - hint.ai_flags = AI_NUMERICHOST; - } - else if (conn->pghost != NULL && conn->pghost[0] != '\0') - { - /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; - hint.ai_family = AF_UNSPEC; - } - else - { + /* Set up for name resolution. */ + switch (ch->type) + { + case CHT_HOST_NAME: + break; + case CHT_HOST_ADDRESS: + hint.ai_flags = AI_NUMERICHOST; + break; + case CHT_UNIX_SOCKET: #ifdef HAVE_UNIX_SOCKETS - /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; - hint.ai_family = AF_UNIX; - UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); - if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + node = NULL; + hint.ai_family = AF_UNIX; + UNIXSOCK_PATH(portstr, thisport, ch->host); + if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), + portstr, + (int) (UNIXSOCK_PATH_BUFLEN - 1)); + conn->options_valid = false; + goto connect_errReturn; + } +#else + Assert(false); +#endif + break; + } + + /* Use pg_getaddrinfo_all() to resolve the address */ + ret = pg_getaddrinfo_all(node, portstr, &hint, &ch->addrlist); + if (ret || !ch->addrlist) { - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), - portstr, - (int) (UNIXSOCK_PATH_BUFLEN - 1)); + if (node) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + portstr, gai_strerror(ret)); + if (ch->addrlist) + { + pg_freeaddrinfo_all(hint.ai_family, ch->addrlist); + ch->addrlist = NULL; + } conn->options_valid = false; goto connect_errReturn; } -#else - /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; - hint.ai_family = AF_UNSPEC; -#endif /* HAVE_UNIX_SOCKETS */ - } - - /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); - else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); - conn->options_valid = false; - goto connect_errReturn; } #ifdef USE_SSL @@ -1498,9 +1634,8 @@ connectDBStart(PGconn *conn) /* * Set up to try to connect, with protocol 3.0 as the first attempt. */ - conn->addrlist = addrs; - conn->addr_cur = addrs; - conn->addrlist_family = hint.ai_family; + conn->whichhost = 0; + conn->addr_cur = conn->connhost[0].addrlist; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; @@ -1702,11 +1837,27 @@ keep_going: /* We will come back to here until there is * returned by pg_getaddrinfo_all(). conn->addr_cur is the * next one to try. We fail when we run out of addresses. */ - while (conn->addr_cur != NULL) + for (;;) { - struct addrinfo *addr_cur = conn->addr_cur; + struct addrinfo *addr_cur; + + /* + * Advance to next possible host, if we've tried all of + * the addresses for the current host. + */ + if (conn->addr_cur == NULL) + { + if (++conn->whichhost >= conn->nconnhost) + { + conn->whichhost = 0; + break; + } + conn->addr_cur = + conn->connhost[conn->whichhost].addrlist; + } /* Remember current address for possible error msg */ + addr_cur = conn->addr_cur; memcpy(&conn->raddr.addr, addr_cur->ai_addr, addr_cur->ai_addrlen); conn->raddr.salen = addr_cur->ai_addrlen; @@ -1718,7 +1869,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = addr_cur->ai_next; continue; @@ -1944,7 +2096,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; @@ -2599,9 +2752,25 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + /* We can release the address lists now. */ + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ @@ -2858,6 +3027,21 @@ freePGconn(PGconn *conn) free(conn->events[i].name); } + /* clean up pg_conn_host structures */ + if (conn->connhost != NULL) + { + for (i = 0; i < conn->nconnhost; ++i) + { + if (conn->connhost[i].host != NULL) + free(conn->connhost[i].host); + if (conn->connhost[i].port != NULL) + free(conn->connhost[i].port); + if (conn->connhost[i].password != NULL) + free(conn->connhost[i].password); + } + free(conn->connhost); + } + if (conn->client_encoding_initial) free(conn->client_encoding_initial); if (conn->events) @@ -2868,8 +3052,6 @@ freePGconn(PGconn *conn) free(conn->pghostaddr); if (conn->pgport) free(conn->pgport); - if (conn->pgunixsocket) - free(conn->pgunixsocket); if (conn->pgtty) free(conn->pgtty); if (conn->connect_timeout) @@ -2983,8 +3165,24 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) @@ -4720,7 +4918,10 @@ conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...] * * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded - * by literal square brackets. + * by literal square brackets. As an extension, we also allow multiple + * netloc[:port] specifications, separated by commas: + * + * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...] * * Any of the URI parts might use percent-encoding (%xy). */ @@ -4736,6 +4937,17 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, char *user = NULL; char *host = NULL; bool retval = false; + PQExpBufferData hostbuf; + PQExpBufferData portbuf; + + initPQExpBuffer(&hostbuf); + initPQExpBuffer(&portbuf); + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("out of memory\n")); + return false; + } /* need a modifiable copy of the input URI */ buf = strdup(uri); @@ -4810,85 +5022,104 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, } /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. + * There may be multiple netloc[:port] pairs, each separated from the next + * by a comma. When we initially enter this loop, "p" has been + * incremented past optional URI credential information at this point and + * now points at the "netloc" part of the URI. On subsequent loop + * iterations, "p" has been incremented past the comma separator and now + * points at the start of the next "netloc". */ - if (*p == '[') + for (;;) { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; - } - if (p == host) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); - goto cleanup; - } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - /* - * The address may be followed by a port specifier or a slash or a - * query. + * Look for IPv6 address. */ - if (*p && *p != ':' && *p != '/' && *p != '?') + if (*p == '[') { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; + host = ++p; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == host) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + + /* Cut off the bracket and advance */ + *(p++) = '\0'; + + /* + * The address may be followed by a port specifier or a slash or a + * query or a separator comma. + */ + if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ + host = p; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * Look for port specifier (colon) or end of host specifier (slash) + * or query (question mark) or host separator (comma). + */ + while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + ++p; + } - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* Save the hostname terminator before we null it */ + prevchar = *p; + *p = '\0'; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + appendPQExpBufferStr(&hostbuf, host); + if (prevchar == ':') + { + const char *port = ++p; /* advance past host terminator */ - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + while (*p && *p != '/' && *p != '?' && *p != ',') + ++p; - while (*p && *p != '/' && *p != '?') - ++p; + prevchar = *p; + *p = '\0'; - prevchar = *p; - *p = '\0'; + appendPQExpBufferStr(&portbuf, port); + } - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) - goto cleanup; + if (prevchar != ',') + break; + ++p; /* advance past comma separator */ + appendPQExpBufferStr(&hostbuf, ","); + appendPQExpBufferStr(&portbuf, ","); } + /* Save final values for host and port. */ + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + goto cleanup; + if (hostbuf.data[0] && + !conninfo_storeval(options, "host", hostbuf.data, + errorMessage, false, true)) + goto cleanup; + if (portbuf.data[0] && + !conninfo_storeval(options, "port", portbuf.data, + errorMessage, false, true)) + goto cleanup; + if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -4923,6 +5154,8 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, retval = true; cleanup: + termPQExpBuffer(&hostbuf); + termPQExpBuffer(&portbuf); free(buf); return retval; } @@ -5342,9 +5575,14 @@ PQuser(const PGconn *conn) char * PQpass(const PGconn *conn) { + char *password; + if (!conn) return NULL; - return conn->pgpass; + password = conn->connhost[conn->whichhost].password; + if (password == NULL) + password = conn->pgpass; + return password; } char * @@ -5352,15 +5590,14 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].host; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { #ifdef HAVE_UNIX_SOCKETS - if (conn->pgunixsocket != NULL && conn->pgunixsocket[0] != '\0') - return conn->pgunixsocket; - else - return DEFAULT_PGSOCKET_DIR; + return DEFAULT_PGSOCKET_DIR; #else return DefaultHost; #endif @@ -5372,6 +5609,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].port; return conn->pgport; } @@ -5481,10 +5720,13 @@ PQbackendPID(const PGconn *conn) int PQconnectionNeedsPassword(const PGconn *conn) { + char *password; + if (!conn) return false; + password = PQpass(conn); if (conn->password_needed && - (conn->pgpass == NULL || conn->pgpass[0] == '\0')) + (password == NULL || password[0] == '\0')) return true; else return false; diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 7007692..854ec89 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -292,6 +292,30 @@ typedef struct pgDataValue const char *value; /* data value, without zero-termination */ } PGdataValue; +typedef enum pg_conn_host_type +{ + CHT_HOST_NAME, + CHT_HOST_ADDRESS, + CHT_UNIX_SOCKET +} pg_conn_host_type; + +/* + * pg_conn_host stores all information about one of possibly several hosts + * mentioned in the connection string. Derived by splitting the pghost + * on the comma character and then parsing each segment. + */ +typedef struct pg_conn_host +{ + char *host; /* host name or address, or socket path */ + pg_conn_host_type type; /* type of host */ + char *port; /* port number for this host; if not NULL, + * overrrides the PGConn's pgport */ + char *password; /* password for this host, read from the + * password file. only set if the PGconn's + * pgpass field is NULL. */ + struct addrinfo *addrlist; /* list of possible backend addresses */ +} pg_conn_host; + /* * PGconn stores all the state data associated with a single connection * to a backend. @@ -299,13 +323,15 @@ typedef struct pgDataValue struct pg_conn { /* Saved values of connection options */ - char *pghost; /* the machine on which the server is running */ + char *pghost; /* the machine on which the server is running, + * or a path to a UNIX-domain socket, or a + * comma-separated list of machines and/or + * paths, optionally with port suffixes; if + * NULL, use DEFAULT_PGSOCKET_DIR */ char *pghostaddr; /* the numeric IP address of the machine on * which the server is running. Takes * precedence over above. */ char *pgport; /* the server's communication port number */ - char *pgunixsocket; /* the directory of the server's Unix-domain - * socket; if NULL, use DEFAULT_PGSOCKET_DIR */ char *pgtty; /* tty on which the backend messages is * displayed (OBSOLETE, NOT USED) */ char *connect_timeout; /* connection timeout (numeric string) */ @@ -363,6 +389,11 @@ struct pg_conn PGnotify *notifyHead; /* oldest unreported Notify msg */ PGnotify *notifyTail; /* newest unreported Notify msg */ + /* Support for multiple hosts in connection string */ + int nconnhost; /* # of possible hosts */ + int whichhost; /* host we're currently considering */ + pg_conn_host *connhost; /* details about each possible host */ + /* Connection data */ pgsocket sock; /* FD for socket, PGINVALID_SOCKET if * unconnected */ @@ -378,9 +409,7 @@ struct pg_conn bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */ /* Transient state needed while establishing connection */ - struct addrinfo *addrlist; /* list of possible backend addresses */ - struct addrinfo *addr_cur; /* the one currently being tried */ - int addrlist_family; /* needed to know how to free addrlist */ + struct addrinfo *addr_cur; /* backend address currently being tried */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 06:03  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-01 06:03 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Oct 27, 2016 at 11:15 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Thanks.  Here's a new version with a fix for that issue and also a fix
> for PQconnectionNeedsPassword(), which was busted in v1.
I did some more testing of the patch for both URI and (host, port)
parameter pairs. I did test for ipv4, ipv6, UDS type of sockets, Also
tested different password using .pgpass. I did not see any major issue
with. All seems to work as defined. Tested the behaviors of API PQport,
PQhost, PQpass, PQreset all works as defined.

I also have following observation which can be considered if it is valid.

1. URI do not support UDS, where as (host,port) pair support same.
But there is one problem with this, instead of reporting it, we discard the
URI input (@conninfo_uri_parse_options) and try to connect to default unix
socket

[mithun@localhost bin]$ ./psql postgres:///home/mithun:5555,
127.0.0.1:5555/postgres -U mithun
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
server is running on both the sockets.

2. If we fail to connect we get an error message for each of the addrinfo
we tried to connect, wondering if we could simplify same. Just a suggestion.
[mithun@localhost bin]$ ./psql postgres://,,,,,,,/postgres
psql: could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 13:24  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-01 13:24 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 2:03 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Thu, Oct 27, 2016 at 11:15 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Thanks.  Here's a new version with a fix for that issue and also a fix
>> for PQconnectionNeedsPassword(), which was busted in v1.
> I did some more testing of the patch for both URI and (host, port) parameter
> pairs. I did test for ipv4, ipv6, UDS type of sockets, Also tested different
> password using .pgpass. I did not see any major issue with. All seems to
> work as defined. Tested the behaviors of API PQport, PQhost, PQpass, PQreset
> all works as defined.
>
> I also have following observation which can be considered if it is valid.
>
> 1. URI do not support UDS, where as (host,port) pair support same.
> But there is one problem with this, instead of reporting it, we discard the
> URI input (@conninfo_uri_parse_options) and try to connect to default unix
> socket
>
> [mithun@localhost bin]$ ./psql
> postgres:///home/mithun:5555,127.0.0.1:5555/postgres -U mithun
> psql: could not connect to server: No such file or directory
> Is the server running locally and accepting
> connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
> server is running on both the sockets.

That's the wrong syntax.  If you look in
https://www.postgresql.org/docs/devel/static/libpq-connect.html under
"32.1.1.2. Connection URIs", it gives an example of how to include a
slash in a pathname.  You have to use %2F, or else the URL parser will
think you're starting a new section of the URI.

I believe this works fine if you use the correct syntax.

> 2. If we fail to connect we get an error message for each of the addrinfo we
> tried to connect, wondering if we could simplify same. Just a suggestion.
> [mithun@localhost bin]$ ./psql postgres://,,,,,,,/postgres
> psql: could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (::1) and accepting
> TCP/IP connections on port 5432?
> could not connect to server: Connection refused
> Is the server running on host "" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?

That output seems fine to me.  In a real connection string, you're not
likely to have so many duplicated addresses, and it's good for the
error message to make clear which addresses were tried and what
happened for each one.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 13:43  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-01 13:43 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 6:54 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>That's the wrong syntax.  If you look in
> https://www.postgresql.org/docs/devel/static/libpq-connect.html under
> "32.1.1.2. Connection URIs", it gives an example of how to include a
> slash in a pathname.  You have to use %2F, or else the URL parser will
> think you're starting a new section of the URI.
>I believe this works fine if you use the correct syntax.

Sorry that was a mistake from me. Now it appears fine.

>
> Starting program: /home/mithun/libpqbin/bin/./psql
> postgres://%2fhome%2fmithun:5555/postgres -U mithun1
> [Thread debugging using libthread_db enabled]
> Using host libthread_db library "/lib64/libthread_db.so.1".
> psql: could not connect to server: No such file or directory
> Is the server running locally and accepting
> *connections on Unix domain socket "/home/mithun/.s.PGSQL.5555"*?



Accidentally when testing further on this line I found a crash when invalid
encoding "%2" (not recognised as hexa) was used.
Test:

> Starting program: /home/mithun/libpqbin/bin/*./psql
> postgres://%2home%2mithun:5555/postgres -U mithun1*

[Thread debugging using libthread_db enabled]

Using host libthread_db library "/lib64/libthread_db.so.1".


> Program received signal SIGSEGV, Segmentation fault.

0x00007ffff7bb8d4f in PQpass (conn=0x68aaa0) at fe-connect.c:5582

5582 password = conn->connhost[conn->whichhost].password;

Missing separate debuginfos, use: debuginfo-install
> glibc-2.17-106.el7_2.6.x86_64 ncurses-libs-5.9-13.20130511.el7.x86_64
> readline-6.2-9.el7.x86_64


There can be PGconn which have no connhost.
exposed API's PQpass, PQreset->connectDBStart access conn->connhost without
checking whether it is set.

>That output seems fine to me.  In a real connection string, you're not
>likely to have so many duplicated addresses, and it's good for the
>error message to make clear which addresses were tried and what
>happened for each one.

Agree, Thanks.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 14:14  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-01 14:14 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 9:43 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>> Starting program: /home/mithun/libpqbin/bin/./psql
>> postgres://%2fhome%2fmithun:5555/postgres -U mithun1
>> [Thread debugging using libthread_db enabled]
>> Using host libthread_db library "/lib64/libthread_db.so.1".
>> psql: could not connect to server: No such file or directory
>> Is the server running locally and accepting
>> connections on Unix domain socket "/home/mithun/.s.PGSQL.5555"?
>
> Accidentally when testing further on this line I found a crash when invalid
> encoding "%2" (not recognised as hexa) was used.
> Test:
>>
>> Starting program: /home/mithun/libpqbin/bin/./psql
>> postgres://%2home%2mithun:5555/postgres -U mithun1

You seem to be confused about how to escape characters in URLs.  The
format is a % followed by exactly two hex digits.  In this case, that
would give you %2h and %2m, and h and m are not hex characters, so the
error message is right.  Your input is not valid.

> There can be PGconn which have no connhost.
> exposed API's PQpass, PQreset->connectDBStart access conn->connhost without
> checking whether it is set.

Can you provide a concrete test scenario or some test code that fails?
 connhost is supposed to be getting set in connectOptions2(), which is
run (AIUI) when the PGconn is first created.  So I think that it will
be set in all scenarios of the type you mention, but I might be
missing something.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 15:21  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-01 15:21 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 7:44 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Starting program: /home/mithun/libpqbin/bin/./psql
>> postgres://%2home%2mithun:5555/postgres -U mithun1
>Can you provide a concrete test scenario or some test code that fails?
>connhost is supposed to be getting set in connectOptions2(), which is
>run (AIUI) when the PGconn is first created.  So I think that it will
>be set in all scenarios of the type you mention, but I might be
>missing something.

Sorry if my sentence is confusing
If I give a proper hexadecimal encoding % followed by 2 hexadigit (i.e. for
e.g %2f, %2a) every thing is fine. When I pass a invalid hexadigit encoding
eg:  *%2h, %2m *among the host string e.g
"postgres://*%2h*ome*%2m*ithun:5555/postgres".
then "PQconnectdbParams()" fails before calling connectOptions2(). In that
case failed PQconnectdbParams() also return a PGconn where connhost is not
set. If we call PQpass(), PQReset() on such a PGconn we get a crash.

A simple test case which crash is:
./psql  'postgres://%2hxxx:5555/postgres'

Call stack:
--------------
#0  0x00007ffff7bb8d4f in PQpass (conn=0x68aa10) at fe-connect.c:5582
#1  0x00007ffff7bb907a in PQconnectionNeedsPassword (conn=0x68aa10) at
fe-connect.c:5727
#2  0x00000000004130aa in main (argc=2, argv=0x7fffffffdff8) at
startup.c:250

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-01 16:12  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-01 16:12 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 11:21 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Tue, Nov 1, 2016 at 7:44 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>>> Starting program: /home/mithun/libpqbin/bin/./psql
>>> postgres://%2home%2mithun:5555/postgres -U mithun1
>>Can you provide a concrete test scenario or some test code that fails?
>>connhost is supposed to be getting set in connectOptions2(), which is
>>run (AIUI) when the PGconn is first created.  So I think that it will
>>be set in all scenarios of the type you mention, but I might be
>>missing something.
>
> Sorry if my sentence is confusing
> If I give a proper hexadecimal encoding % followed by 2 hexadigit (i.e. for
> e.g %2f, %2a) every thing is fine. When I pass a invalid hexadigit encoding
> eg:  %2h, %2m among the host string e.g
> "postgres://%2home%2mithun:5555/postgres". then "PQconnectdbParams()" fails
> before calling connectOptions2(). In that case failed PQconnectdbParams()
> also return a PGconn where connhost is not set. If we call PQpass(),
> PQReset() on such a PGconn we get a crash.
>
> A simple test case which crash is:
> ./psql  'postgres://%2hxxx:5555/postgres'
>
> Call stack:
> --------------
> #0  0x00007ffff7bb8d4f in PQpass (conn=0x68aa10) at fe-connect.c:5582
> #1  0x00007ffff7bb907a in PQconnectionNeedsPassword (conn=0x68aa10) at
> fe-connect.c:5727
> #2  0x00000000004130aa in main (argc=2, argv=0x7fffffffdff8) at
> startup.c:250

Ah, nuts.  Thanks, good catch.  Should be fixed in the attached version.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

multihost-v3.patch (application/x-download, 32.0K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 4e34f00..d04dba7 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -756,8 +756,10 @@ PGPing PQping(const char *conninfo); Several <application>libpq</> functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain <literal>keyword = value</literal> strings - and <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC - 3986</ulink> URIs. + and URIs. URIs generally follow + <ulink url="http://www.ietf.org/rfc/rfc3986.txt">RFC + 3986</ulink>, except that multi-host connection strings are allowed + as further described below. </para> <sect3> @@ -792,7 +794,7 @@ host=localhost port=5432 dbname=mydb connect_timeout=10 <para> The general form for a connection <acronym>URI</acronym> is: <synopsis> -postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&amp;...] +postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&amp;...] </synopsis> </para> @@ -809,6 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp +postgresql://host1:123,host2:456/somedb </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -856,6 +859,15 @@ postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </programlisting> </para> + + <para> + It is possible to specify multiple host components, each with an optional + port component, in a single URI. A URI of the form + <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal> + is equivalent to a connection string of the form + <literal>host=host1,host2,host3 port=port1,port2,port3</literal>. Each + host will be tried in turn until a connection is successfully established. + </para> </sect3> </sect2> @@ -870,12 +882,13 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <term><literal>host</literal></term> <listitem> <para> - Name of host to connect to.<indexterm><primary>host name</></> - If this begins with a slash, it specifies Unix-domain + Comma-separated list of host names.<indexterm><primary>host name</></> + If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the - name of the directory in which the socket file is stored. The - default behavior when <literal>host</literal> is not specified - is to connect to a Unix-domain + name of the directory in which the socket file is stored. If + multiple host names are specified, each will be tried in turn in + the order given. The default behavior when <literal>host</literal> is + not specified is to connect to a Unix-domain socket<indexterm><primary>Unix domain socket</></> in <filename>/tmp</filename> (or whatever socket directory was specified when <productname>PostgreSQL</> was built). On machines without @@ -950,6 +963,9 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname Port number to connect to at the server host, or socket file name extension for Unix-domain connections.<indexterm><primary>port</></> + If the <literal>host</> parameter included multiple, comma-separated + hosts, this parameter may specify a list of ports of equal length, + or it may specify a single port number to be used for all hosts. </para> </listitem> </varlistentry> @@ -1394,7 +1410,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The following functions return parameter values established at connection. - These values are fixed for the life of the <structname>PGconn</> object. + These values are fixed for the life of the connection. If a multi-host + connection string is used, the values of <function>PQhost</>, + <function>PQport</>, and <function>PQpass</> can change if a new connection + is established using the same <structname>PGconn</> object. Other values + are fixed for the lifetime of the <structname>PGconn</> object. <variablelist> <varlistentry id="libpq-pqdb"> diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 404bc93..19171fb 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -683,20 +683,26 @@ pg_fe_sendauth(AuthRequest areq, PGconn *conn) case AUTH_REQ_MD5: case AUTH_REQ_PASSWORD: - conn->password_needed = true; - if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { - printfPQExpBuffer(&conn->errorMessage, - PQnoPasswordSupplied); - return STATUS_ERROR; - } - if (pg_password_sendauth(conn, conn->pgpass, areq) != STATUS_OK) - { - printfPQExpBuffer(&conn->errorMessage, + char *password = conn->connhost[conn->whichhost].password; + + if (password == NULL) + password = conn->pgpass; + conn->password_needed = true; + if (password == NULL || password[0] == '\0') + { + printfPQExpBuffer(&conn->errorMessage, + PQnoPasswordSupplied); + return STATUS_ERROR; + } + if (pg_password_sendauth(conn, password, areq) != STATUS_OK) + { + printfPQExpBuffer(&conn->errorMessage, "fe_sendauth: error sending password authentication\n"); - return STATUS_ERROR; + return STATUS_ERROR; + } + break; } - break; case AUTH_REQ_SCM_CREDS: if (pg_local_sendauth(conn) != STATUS_OK) diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index f3a9e5a..b4f9ad7 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -771,6 +771,148 @@ static bool connectOptions2(PGconn *conn) { /* + * Allocate memory for details about each host to which we might possibly + * try to connect. If pghostaddr is set, we're only going to try to + * connect to that one particular address. If it's not, we'll use pghost, + * which may contain multiple, comma-separated names. + */ + conn->nconnhost = 1; + conn->whichhost = 0; + if ((conn->pghostaddr == NULL || conn->pghostaddr[0] == '\0') + && conn->pghost != NULL) + { + char *s; + + for (s = conn->pghost; *s != '\0'; ++s) + if (*s == ',') + conn->nconnhost++; + } + conn->connhost = (pg_conn_host *) + calloc(conn->nconnhost, sizeof(pg_conn_host)); + if (conn->connhost == NULL) + goto oom_error; + + /* + * We now have one pg_conn_host structure per possible host. Fill in + * the host details for each one. + */ + if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') + { + conn->connhost[0].host = strdup(conn->pghostaddr); + if (conn->connhost[0].host == NULL) + goto oom_error; + conn->connhost[0].type = CHT_HOST_ADDRESS; + } + else if (conn->pghost != NULL && conn->pghost[0] != '\0') + { + int i = 0; + char *s = conn->pghost; + + while (1) + { + char *e = s; + + /* + * Search for the end of the current hostname; a comma or + * end-of-string acts as a terminator. + */ + while (*e != '\0' && *e != ',') + ++e; + + /* Copy the hostname whose bounds we just identified. */ + conn->connhost[i].host = + (char *) malloc(sizeof(char) * (e - s + 1)); + if (conn->connhost[i].host == NULL) + goto oom_error; + memcpy(conn->connhost[i].host, s, e - s); + conn->connhost[i].host[e - s] = '\0'; + + /* Identify the type of host. */ + conn->connhost[i].type = CHT_HOST_NAME; +#ifdef HAVE_UNIX_SOCKETS + if (is_absolute_path(conn->connhost[i].host)) + conn->connhost[i].type = CHT_UNIX_SOCKET; +#endif + + /* Prepare to find the next host (if any). */ + if (*e == '\0') + break; + s = e + 1; + i++; + } + } + else + { +#ifdef HAVE_UNIX_SOCKETS + conn->connhost[0].host = strdup(DEFAULT_PGSOCKET_DIR); + conn->connhost[0].type = CHT_UNIX_SOCKET; +#else + conn->connhost[0].host = strdup(DefaultHost); + conn->connhost[0].type = CHT_HOST_NAME; +#endif + if (conn->connhost[0].host == NULL) + goto oom_error; + } + + /* + * Next, work out the port number corresponding to each host name. + */ + if (conn->pgport != NULL && conn->pgport[0] != '\0') + { + int i = 0; + char *s = conn->pgport; + int nports = 1; + + for (i = 0; i < conn->nconnhost; ++i) + { + char *e = s; + + /* Search for the end of the current port number. */ + while (*e != '\0' && *e != ',') + ++e; + + /* + * If we found a port number of non-zero length, copy it. + * Otherwise, insert the default port number. + */ + if (e > s) + { + conn->connhost[i].port = + (char *) malloc(sizeof(char) * (e - s + 1)); + if (conn->connhost[i].port == NULL) + goto oom_error; + memcpy(conn->connhost[i].port, s, e - s); + conn->connhost[i].port[e - s] = '\0'; + } + + /* + * Move on to the next port number, unless there are no more. + * (If only one part number is specified, we reuse it for every + * host.) + */ + if (*e != '\0') + { + s = e + 1; + ++nports; + } + } + + /* + * If multiple ports were specified, there must be exactly as many + * ports as there were hosts. Otherwise, we do not know how to match + * them up. + */ + if (nports != 1 && nports != conn->nconnhost) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not match %d port numbers to %d hosts\n"), + nports, conn->nconnhost); + return false; + } + } + + /* * If user name was not given, fetch it. (Most likely, the fetch will * fail, since the only way we get here is if pg_fe_getauthname() failed * during conninfo_add_defaults(). But now we want an error message.) @@ -800,33 +942,27 @@ connectOptions2(PGconn *conn) } /* - * Supply default password if none given + * Supply default password if none given. Note that the password might + * be different for each host/port pair. */ if (conn->pgpass == NULL || conn->pgpass[0] == '\0') { + int i; + if (conn->pgpass) free(conn->pgpass); - conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport, - conn->dbName, conn->pguser); - if (conn->pgpass == NULL) + conn->pgpass = strdup(DefaultPassword); + if (!conn->pgpass) + goto oom_error; + for (i = 0; i < conn->nconnhost; ++i) { - conn->pgpass = strdup(DefaultPassword); - if (!conn->pgpass) - goto oom_error; + conn->connhost[i].password = + PasswordFromFile(conn->connhost[i].host, + conn->connhost[i].port, + conn->dbName, conn->pguser); + if (conn->connhost[i].password != NULL) + conn->dot_pgpass_used = true; } - else - conn->dot_pgpass_used = true; - } - - /* - * Allow unix socket specification in the host name - */ - if (conn->pghost && is_absolute_path(conn->pghost)) - { - if (conn->pgunixsocket) - free(conn->pgunixsocket); - conn->pgunixsocket = conn->pghost; - conn->pghost = NULL; } /* @@ -1142,6 +1278,7 @@ connectFailureMessage(PGconn *conn, int errorno) { char host_addr[NI_MAXHOST]; const char *displayed_host; + const char *displayed_port; struct sockaddr_storage *addr = &conn->raddr.addr; /* @@ -1171,12 +1308,11 @@ connectFailureMessage(PGconn *conn, int errorno) else strcpy(host_addr, "???"); - if (conn->pghostaddr && conn->pghostaddr[0] != '\0') - displayed_host = conn->pghostaddr; - else if (conn->pghost && conn->pghost[0] != '\0') - displayed_host = conn->pghost; - else - displayed_host = DefaultHost; + /* To which host and port were we actually connecting? */ + displayed_host = conn->connhost[conn->whichhost].host; + displayed_port = conn->connhost[conn->whichhost].port; + if (displayed_port == NULL || displayed_port[0] == '\0') + displayed_port = DEF_PGPORT_STR; /* * If the user did not supply an IP address using 'hostaddr', and @@ -1192,7 +1328,7 @@ connectFailureMessage(PGconn *conn, int errorno) SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, host_addr, - conn->pgport); + displayed_port); else appendPQExpBuffer(&conn->errorMessage, libpq_gettext("could not connect to server: %s\n" @@ -1200,7 +1336,7 @@ connectFailureMessage(PGconn *conn, int errorno) "\tTCP/IP connections on port %s?\n"), SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)), displayed_host, - conn->pgport); + displayed_port); } } @@ -1390,12 +1526,9 @@ setKeepalivesWin32(PGconn *conn) static int connectDBStart(PGconn *conn) { - int portnum; char portstr[MAXPGPATH]; - struct addrinfo *addrs = NULL; - struct addrinfo hint; - const char *node; int ret; + int i; if (!conn) return 0; @@ -1408,83 +1541,86 @@ connectDBStart(PGconn *conn) conn->outCount = 0; /* - * Determine the parameters to pass to pg_getaddrinfo_all. + * Look up socket addresses for each possible host using + * pg_getaddrinfo_all. */ + for (i = 0; i < conn->nconnhost; ++i) + { + pg_conn_host *ch = &conn->connhost[i]; + char *node = ch->host; + struct addrinfo hint; + int thisport; - /* Initialize hint structure */ - MemSet(&hint, 0, sizeof(hint)); - hint.ai_socktype = SOCK_STREAM; - hint.ai_family = AF_UNSPEC; + /* Initialize hint structure */ + MemSet(&hint, 0, sizeof(hint)); + hint.ai_socktype = SOCK_STREAM; + hint.ai_family = AF_UNSPEC; - /* Set up port number as a string */ - if (conn->pgport != NULL && conn->pgport[0] != '\0') - { - portnum = atoi(conn->pgport); - if (portnum < 1 || portnum > 65535) + /* Figure out the port number we're going to use. */ + if (ch->port == NULL) + thisport = DEF_PGPORT; + else { - appendPQExpBuffer(&conn->errorMessage, + thisport = atoi(ch->port); + if (thisport < 1 || thisport > 65535) + { + appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid port number: \"%s\"\n"), - conn->pgport); - conn->options_valid = false; - goto connect_errReturn; + ch->port); + conn->options_valid = false; + goto connect_errReturn; + } } - } - else - portnum = DEF_PGPORT; - snprintf(portstr, sizeof(portstr), "%d", portnum); + snprintf(portstr, sizeof(portstr), "%d", thisport); - if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0') - { - /* Using pghostaddr avoids a hostname lookup */ - node = conn->pghostaddr; - hint.ai_family = AF_UNSPEC; - hint.ai_flags = AI_NUMERICHOST; - } - else if (conn->pghost != NULL && conn->pghost[0] != '\0') - { - /* Using pghost, so we have to look-up the hostname */ - node = conn->pghost; - hint.ai_family = AF_UNSPEC; - } - else - { + /* Set up for name resolution. */ + switch (ch->type) + { + case CHT_HOST_NAME: + break; + case CHT_HOST_ADDRESS: + hint.ai_flags = AI_NUMERICHOST; + break; + case CHT_UNIX_SOCKET: #ifdef HAVE_UNIX_SOCKETS - /* pghostaddr and pghost are NULL, so use Unix domain socket */ - node = NULL; - hint.ai_family = AF_UNIX; - UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket); - if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + node = NULL; + hint.ai_family = AF_UNIX; + UNIXSOCK_PATH(portstr, thisport, ch->host); + if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN) + { + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), + portstr, + (int) (UNIXSOCK_PATH_BUFLEN - 1)); + conn->options_valid = false; + goto connect_errReturn; + } +#else + Assert(false); +#endif + break; + } + + /* Use pg_getaddrinfo_all() to resolve the address */ + ret = pg_getaddrinfo_all(node, portstr, &hint, &ch->addrlist); + if (ret || !ch->addrlist) { - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"), - portstr, - (int) (UNIXSOCK_PATH_BUFLEN - 1)); + if (node) + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate host name \"%s\" to address: %s\n"), + node, gai_strerror(ret)); + else + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), + portstr, gai_strerror(ret)); + if (ch->addrlist) + { + pg_freeaddrinfo_all(hint.ai_family, ch->addrlist); + ch->addrlist = NULL; + } conn->options_valid = false; goto connect_errReturn; } -#else - /* Without Unix sockets, default to localhost instead */ - node = DefaultHost; - hint.ai_family = AF_UNSPEC; -#endif /* HAVE_UNIX_SOCKETS */ - } - - /* Use pg_getaddrinfo_all() to resolve the address */ - ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs); - if (ret || !addrs) - { - if (node) - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate host name \"%s\" to address: %s\n"), - node, gai_strerror(ret)); - else - appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"), - portstr, gai_strerror(ret)); - if (addrs) - pg_freeaddrinfo_all(hint.ai_family, addrs); - conn->options_valid = false; - goto connect_errReturn; } #ifdef USE_SSL @@ -1498,9 +1634,8 @@ connectDBStart(PGconn *conn) /* * Set up to try to connect, with protocol 3.0 as the first attempt. */ - conn->addrlist = addrs; - conn->addr_cur = addrs; - conn->addrlist_family = hint.ai_family; + conn->whichhost = 0; + conn->addr_cur = conn->connhost[0].addrlist; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; conn->status = CONNECTION_NEEDED; @@ -1702,11 +1837,27 @@ keep_going: /* We will come back to here until there is * returned by pg_getaddrinfo_all(). conn->addr_cur is the * next one to try. We fail when we run out of addresses. */ - while (conn->addr_cur != NULL) + for (;;) { - struct addrinfo *addr_cur = conn->addr_cur; + struct addrinfo *addr_cur; + + /* + * Advance to next possible host, if we've tried all of + * the addresses for the current host. + */ + if (conn->addr_cur == NULL) + { + if (++conn->whichhost >= conn->nconnhost) + { + conn->whichhost = 0; + break; + } + conn->addr_cur = + conn->connhost[conn->whichhost].addrlist; + } /* Remember current address for possible error msg */ + addr_cur = conn->addr_cur; memcpy(&conn->raddr.addr, addr_cur->ai_addr, addr_cur->ai_addrlen); conn->raddr.salen = addr_cur->ai_addrlen; @@ -1718,7 +1869,8 @@ keep_going: /* We will come back to here until there is * ignore socket() failure if we have more addresses * to try */ - if (addr_cur->ai_next != NULL) + if (addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = addr_cur->ai_next; continue; @@ -1944,7 +2096,8 @@ keep_going: /* We will come back to here until there is * If more addresses remain, keep trying, just as in the * case where connect() returned failure immediately. */ - if (conn->addr_cur->ai_next != NULL) + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) { conn->addr_cur = conn->addr_cur->ai_next; conn->status = CONNECTION_NEEDED; @@ -2599,9 +2752,25 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address list now. */ - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + /* We can release the address lists now. */ + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; /* Fire up post-connection housekeeping if needed */ @@ -2858,6 +3027,21 @@ freePGconn(PGconn *conn) free(conn->events[i].name); } + /* clean up pg_conn_host structures */ + if (conn->connhost != NULL) + { + for (i = 0; i < conn->nconnhost; ++i) + { + if (conn->connhost[i].host != NULL) + free(conn->connhost[i].host); + if (conn->connhost[i].port != NULL) + free(conn->connhost[i].port); + if (conn->connhost[i].password != NULL) + free(conn->connhost[i].password); + } + free(conn->connhost); + } + if (conn->client_encoding_initial) free(conn->client_encoding_initial); if (conn->events) @@ -2868,8 +3052,6 @@ freePGconn(PGconn *conn) free(conn->pghostaddr); if (conn->pgport) free(conn->pgport); - if (conn->pgunixsocket) - free(conn->pgunixsocket); if (conn->pgtty) free(conn->pgtty); if (conn->connect_timeout) @@ -2983,8 +3165,24 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist); - conn->addrlist = NULL; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) @@ -4720,7 +4918,10 @@ conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...] * * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded - * by literal square brackets. + * by literal square brackets. As an extension, we also allow multiple + * netloc[:port] specifications, separated by commas: + * + * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...] * * Any of the URI parts might use percent-encoding (%xy). */ @@ -4736,6 +4937,17 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, char *user = NULL; char *host = NULL; bool retval = false; + PQExpBufferData hostbuf; + PQExpBufferData portbuf; + + initPQExpBuffer(&hostbuf); + initPQExpBuffer(&portbuf); + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("out of memory\n")); + return false; + } /* need a modifiable copy of the input URI */ buf = strdup(uri); @@ -4810,85 +5022,104 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, } /* - * "p" has been incremented past optional URI credential information at - * this point and now points at the "netloc" part of the URI. - * - * Look for IPv6 address. + * There may be multiple netloc[:port] pairs, each separated from the next + * by a comma. When we initially enter this loop, "p" has been + * incremented past optional URI credential information at this point and + * now points at the "netloc" part of the URI. On subsequent loop + * iterations, "p" has been incremented past the comma separator and now + * points at the start of the next "netloc". */ - if (*p == '[') + for (;;) { - host = ++p; - while (*p && *p != ']') - ++p; - if (!*p) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), - uri); - goto cleanup; - } - if (p == host) - { - printfPQExpBuffer(errorMessage, - libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), - uri); - goto cleanup; - } - - /* Cut off the bracket and advance */ - *(p++) = '\0'; - /* - * The address may be followed by a port specifier or a slash or a - * query. + * Look for IPv6 address. */ - if (*p && *p != ':' && *p != '/' && *p != '?') + if (*p == '[') { - printfPQExpBuffer(errorMessage, - libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), - *p, (int) (p - buf + 1), uri); - goto cleanup; + host = ++p; + while (*p && *p != ']') + ++p; + if (!*p) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"), + uri); + goto cleanup; + } + if (p == host) + { + printfPQExpBuffer(errorMessage, + libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"), + uri); + goto cleanup; + } + + /* Cut off the bracket and advance */ + *(p++) = '\0'; + + /* + * The address may be followed by a port specifier or a slash or a + * query or a separator comma. + */ + if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + { + printfPQExpBuffer(errorMessage, + libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"), + *p, (int) (p - buf + 1), uri); + goto cleanup; + } } - } - else - { - /* not an IPv6 address: DNS-named or IPv4 netloc */ - host = p; + else + { + /* not an IPv6 address: DNS-named or IPv4 netloc */ + host = p; - /* - * Look for port specifier (colon) or end of host specifier (slash), - * or query (question mark). - */ - while (*p && *p != ':' && *p != '/' && *p != '?') - ++p; - } + /* + * Look for port specifier (colon) or end of host specifier (slash) + * or query (question mark) or host separator (comma). + */ + while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',') + ++p; + } - /* Save the hostname terminator before we null it */ - prevchar = *p; - *p = '\0'; + /* Save the hostname terminator before we null it */ + prevchar = *p; + *p = '\0'; - if (*host && - !conninfo_storeval(options, "host", host, - errorMessage, false, true)) - goto cleanup; + appendPQExpBufferStr(&hostbuf, host); + if (prevchar == ':') + { + const char *port = ++p; /* advance past host terminator */ - if (prevchar == ':') - { - const char *port = ++p; /* advance past host terminator */ + while (*p && *p != '/' && *p != '?' && *p != ',') + ++p; - while (*p && *p != '/' && *p != '?') - ++p; + prevchar = *p; + *p = '\0'; - prevchar = *p; - *p = '\0'; + appendPQExpBufferStr(&portbuf, port); + } - if (*port && - !conninfo_storeval(options, "port", port, - errorMessage, false, true)) - goto cleanup; + if (prevchar != ',') + break; + ++p; /* advance past comma separator */ + appendPQExpBufferStr(&hostbuf, ","); + appendPQExpBufferStr(&portbuf, ","); } + /* Save final values for host and port. */ + if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf)) + goto cleanup; + if (hostbuf.data[0] && + !conninfo_storeval(options, "host", hostbuf.data, + errorMessage, false, true)) + goto cleanup; + if (portbuf.data[0] && + !conninfo_storeval(options, "port", portbuf.data, + errorMessage, false, true)) + goto cleanup; + if (prevchar && prevchar != '?') { const char *dbname = ++p; /* advance past host terminator */ @@ -4923,6 +5154,8 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, retval = true; cleanup: + termPQExpBuffer(&hostbuf); + termPQExpBuffer(&portbuf); free(buf); return retval; } @@ -5342,9 +5575,15 @@ PQuser(const PGconn *conn) char * PQpass(const PGconn *conn) { + char *password = NULL; + if (!conn) return NULL; - return conn->pgpass; + if (conn->connhost != NULL) + password = conn->connhost[conn->whichhost].password; + if (password == NULL) + password = conn->pgpass; + return password; } char * @@ -5352,15 +5591,14 @@ PQhost(const PGconn *conn) { if (!conn) return NULL; - if (conn->pghost != NULL && conn->pghost[0] != '\0') + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].host; + else if (conn->pghost != NULL && conn->pghost[0] != '\0') return conn->pghost; else { #ifdef HAVE_UNIX_SOCKETS - if (conn->pgunixsocket != NULL && conn->pgunixsocket[0] != '\0') - return conn->pgunixsocket; - else - return DEFAULT_PGSOCKET_DIR; + return DEFAULT_PGSOCKET_DIR; #else return DefaultHost; #endif @@ -5372,6 +5610,8 @@ PQport(const PGconn *conn) { if (!conn) return NULL; + if (conn->connhost != NULL) + return conn->connhost[conn->whichhost].port; return conn->pgport; } @@ -5481,10 +5721,13 @@ PQbackendPID(const PGconn *conn) int PQconnectionNeedsPassword(const PGconn *conn) { + char *password; + if (!conn) return false; + password = PQpass(conn); if (conn->password_needed && - (conn->pgpass == NULL || conn->pgpass[0] == '\0')) + (password == NULL || password[0] == '\0')) return true; else return false; diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 7007692..854ec89 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -292,6 +292,30 @@ typedef struct pgDataValue const char *value; /* data value, without zero-termination */ } PGdataValue; +typedef enum pg_conn_host_type +{ + CHT_HOST_NAME, + CHT_HOST_ADDRESS, + CHT_UNIX_SOCKET +} pg_conn_host_type; + +/* + * pg_conn_host stores all information about one of possibly several hosts + * mentioned in the connection string. Derived by splitting the pghost + * on the comma character and then parsing each segment. + */ +typedef struct pg_conn_host +{ + char *host; /* host name or address, or socket path */ + pg_conn_host_type type; /* type of host */ + char *port; /* port number for this host; if not NULL, + * overrrides the PGConn's pgport */ + char *password; /* password for this host, read from the + * password file. only set if the PGconn's + * pgpass field is NULL. */ + struct addrinfo *addrlist; /* list of possible backend addresses */ +} pg_conn_host; + /* * PGconn stores all the state data associated with a single connection * to a backend. @@ -299,13 +323,15 @@ typedef struct pgDataValue struct pg_conn { /* Saved values of connection options */ - char *pghost; /* the machine on which the server is running */ + char *pghost; /* the machine on which the server is running, + * or a path to a UNIX-domain socket, or a + * comma-separated list of machines and/or + * paths, optionally with port suffixes; if + * NULL, use DEFAULT_PGSOCKET_DIR */ char *pghostaddr; /* the numeric IP address of the machine on * which the server is running. Takes * precedence over above. */ char *pgport; /* the server's communication port number */ - char *pgunixsocket; /* the directory of the server's Unix-domain - * socket; if NULL, use DEFAULT_PGSOCKET_DIR */ char *pgtty; /* tty on which the backend messages is * displayed (OBSOLETE, NOT USED) */ char *connect_timeout; /* connection timeout (numeric string) */ @@ -363,6 +389,11 @@ struct pg_conn PGnotify *notifyHead; /* oldest unreported Notify msg */ PGnotify *notifyTail; /* newest unreported Notify msg */ + /* Support for multiple hosts in connection string */ + int nconnhost; /* # of possible hosts */ + int whichhost; /* host we're currently considering */ + pg_conn_host *connhost; /* details about each possible host */ + /* Connection data */ pgsocket sock; /* FD for socket, PGINVALID_SOCKET if * unconnected */ @@ -378,9 +409,7 @@ struct pg_conn bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */ /* Transient state needed while establishing connection */ - struct addrinfo *addrlist; /* list of possible backend addresses */ - struct addrinfo *addr_cur; /* the one currently being tried */ - int addrlist_family; /* needed to know how to free addrlist */ + struct addrinfo *addr_cur; /* backend address currently being tried */ PGSetenvStatusType setenv_state; /* for 2.0 protocol only */ const PQEnvironmentOption *next_eo; bool send_appname; /* okay to send application_name? */
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-02 17:59  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-02 17:59 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 1, 2016 at 9:42 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Ah, nuts.  Thanks, good catch.  Should be fixed in the attached version.

I repeated the test on new patch, It works fine now, Also did some more
negative tests forcibly failing some internal calls. All tests have passed.
This patch works as described and look good to me.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-03 13:46  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 3 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-03 13:46 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 2, 2016 at 1:59 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Tue, Nov 1, 2016 at 9:42 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Ah, nuts.  Thanks, good catch.  Should be fixed in the attached version.
>
> I repeated the test on new patch, It works fine now, Also did some more
> negative tests forcibly failing some internal calls. All tests have passed.
> This patch works as described and look good to me.

Great, committed.  There's still potentially more work to be done
here, because my patch omits some features that were present in
Victor's original submission, like setting the failover timeout,
optionally randomizing the order of the hosts, and distinguishing
between master and standby servers; Victor, or anyone, please feel
free to submit separate patches for those things.

Thanks.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-09 15:05  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-09 15:05 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 3, 2016 at 7:16 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Great, committed.  There's still potentially more work to be done
> here, because my patch omits some features that were present in
> Victor's original submission, like setting the failover timeout,
> optionally randomizing the order of the hosts, and distinguishing
> between master and standby servers; Victor, or anyone, please feel
> free to submit separate patches for those things.

Among the remaining things I have worked on failover to new master idea.
Below patch implement that idea. This is taken from Victors patch but
rewritten by me to do some cleanup. As in Victor's patch we have a new
connection parameter "target_server_type", It can take 2 values 1. "any" 2.
"master" with DEFAULT as "any". If it's has the value "any" we can connect
to any of the host server (both master(primary) and slave(standby)). If the
value is "master" then we try to connect to master(primary) only.
NOTE: Parameter name is inspired and taken from PostgreSql JDBC Driver
<https://jdbc.postgresql.org/documentation/head/connect.html;.

The main difference between Victor's and this new patch is Default value of
parameter target_server_type. In Victor's patch if number of host in
connection string is 1 then default value is "any" (This was done to make
sure old psql connect to standby as it is now). If it is greater than 1
then default value is set as "master". For me this appeared slightly
inconsistent having default value as "any" for any number of connection
appeared more appropriate which is also backward compatible. And, if user
want failover to master he should ask for it by setting
target_server_type=master in connection string.

This patch do not include load balancing feature by trying to connect to
host in random fashion.

This patch also do not have failover timeout feature. Victor's
implementation of same is not a strict one. i. e. 1 walk of all of the host
is allowed even if timer might have expired. Only on second walk we check
for timeout. I thought application can manage the failover timeout instead
libpq doing it. So avoided the same in this patch. If others find that I am
wrong to think that way, will add the same.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover_to_new_master-v1.patch (application/octet-stream, 11.3K) download commit 04c20d33cf5ba6dd244abe21eac03c0bed4db0c8 Author: mithun <mithun@localhost.localdomain> Date: Wed Nov 9 20:22:37 2016 +0530 Failover to new master patch diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..b1ec41b 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -811,7 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp -postgresql://host1:123,host2:456/somedb +postgresql://host1:123,host2:456/somedb?target_server_type=any&amp;application_name=myapp </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -1382,6 +1382,17 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + This parameter specifies what kind of server to connect. + Set this to <literal>master</literal>, to connect only to master + server. Set this to <literal>any</literal>, if you want to connect to + any of the given host. And, the default is <literal>any</literal>. + </para> + </listitem> + </varlistentry> </variablelist> </para> </sect2> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..7774cab 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -300,6 +300,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"target_server_type", NULL, NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +340,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void release_all_addrinfo(PGconn *conn); +static void sendTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -1026,6 +1032,24 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "master") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value:" + " \"%s\" should be \"any\" or " + "\"master\"\n"), + conn->target_server_type); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1814,6 +1838,7 @@ PQconnectPoll(PGconn *conn) /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: + case CONNECTION_CHECK_MASTER: break; default: @@ -2752,27 +2777,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address lists now. */ - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; - -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2782,7 +2786,25 @@ keep_going: /* We will come back to here until there is return PGRES_POLLING_WRITING; } - /* Otherwise, we are open for business! */ + /* + * If asked to connect to a master then check if connected + * one is a master. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "master") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "SELECT pg_catalog.pg_is_in_recovery()")) + goto error_return; + conn->status = CONNECTION_CHECK_MASTER; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } @@ -2814,10 +2836,112 @@ keep_going: /* We will come back to here until there is goto error_return; } + /* + * If asked to connect to a master then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "master") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "SELECT pg_catalog.pg_is_in_recovery()")) + goto error_return; + conn->status = CONNECTION_CHECK_MASTER; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; + case CONNECTION_CHECK_MASTER: + { + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + goto error_return; + + if (PQisBusy(conn)) + { + conn->status = CONNECTION_CHECK_MASTER; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) && + PQntuples(res) == 1) + { + char *val; + val = PQgetvalue(res, 0 , 0); + if (val[0] == 't') + { + PQclear(res); + + /* + * This is a hot standby server terminate this connection + * and try next address. + */ + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Connection failed, " + "%s:%s is a hot standby.\n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + PQclear(res); + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Something went wrong with + * "SELECT pg_catalog.pg_is_in_recovery()". We should try next + * addresses. + */ + if (res) + PQclear(res); + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("test to check if, %s:%s is a \"master\" " + "failed \n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " @@ -3120,19 +3244,41 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * release_all_addrinfo + * - free addrinfo of all hostconn elements. */ + static void -closePGconn(PGconn *conn) +release_all_addrinfo(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } + conn->addr_cur = NULL; +} +/* + * sendTerminateConn + * - Send a terminate message to backend. + */ +static void +sendTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -3147,6 +3293,23 @@ closePGconn(PGconn *conn) pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + sendTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -3165,25 +3328,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; + release_all_addrinfo(conn); -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) { diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..5e01b57 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,8 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_MASTER /* Check if it is connected to MASTER. */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 854ec89..1ea6943 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,9 @@ struct pg_conn char *krbsrvname; /* Kerberos service name */ #endif + char *target_server_type; /* Type of server to connect. + * Possible values any, master. */ + /* Optional file to write trace info to */ FILE *Pfdebug;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-10 07:41  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-10 07:41 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> Among the remaining things I have worked on failover to new master idea.
> Below patch implement that idea. This is taken from Victors patch but
> rewritten by me to do some cleanup. As in Victor's patch we have a new
> connection parameter "target_server_type", It can take 2 values 1. "any"
> 2. "master" with DEFAULT as "any". If it's has the value "any" we can connect
> to any of the host server (both master(primary) and slave(standby)). If
> the value is "master" then we try to connect to master(primary) only.
> NOTE: Parameter name is inspired and taken from PostgreSql JDBC Driver
> <https://jdbc.postgresql.org/documentation/head/connect.html; .

I'm interested to review this patch (but I haven't read it yet, I'm reading Robert's patch now.)  Are you planning a new CommitFest entry?

Why don't you add "standby" and "prefer_standby" as the target_server_type value?  Are you thinking that those values are useful with load balancing feature?


> The main difference between Victor's and this new patch is Default value
> of parameter target_server_type. In Victor's patch if number of host in
> connection string is 1 then default value is "any" (This was done to make
> sure old psql connect to standby as it is now). If it is greater than 1
> then default value is set as "master". For me this appeared slightly
> inconsistent having default value as "any" for any number of connection
> appeared more appropriate which is also backward compatible. And, if user
> want failover to master he should ask for it by setting
> target_server_type=master in connection string.

That's sensible, I agree.


Regards
Takayuki Tsunakawa


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-10 14:59  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-10 14:59 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 10, 2016 at 1:11 PM, Tsunakawa, Takayuki <
tsunakawa.takay@jp.fujitsu.com> wrote:
> Why don't you add "standby" and "prefer_standby" as the
target_server_type value?  Are you thinking that those values are useful
with load balancing > feature?
Yes this patch will only address failover to new master, values "master"
and "any" appeared sufficient for that case.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-11 06:25  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-11 06:25 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> Yes this patch will only address failover to new master, values "master"
> and "any" appeared sufficient for that case.

Do you mean that unlike pgJDBC "standby" and "prefer_standby" are useless, or they are useful but you don't have time to implement it and want to do it in the near future?  Do you mind if I do it if time permits me?  I think they are useful without load balancing feature, when the user has multiple standbys for HA.

Could you add a new entry in CommitFest 2017-1? I'm afraid we can't track the status of your patch because the original patch in this thread has already been committed.

Regards
Takayuki Tsunakawa
 


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-11 07:03  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-11 07:03 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> Great, committed.  There's still potentially more work to be done here,
> because my patch omits some features that were present in Victor's original
> submission, like setting the failover timeout, optionally randomizing the
> order of the hosts, and distinguishing between master and standby servers;
> Victor, or anyone, please feel free to submit separate patches for those
> things.

I did a few tests with ECPG.  I'm satisfied with the current behavior, but someone says different.  I'd like to share the result.

The following literal connection strings succeeded.  host1 is a server where PostgreSQL is not running, and host2 is where it's running.  I could connect to the database server on host2.

EXEC SQL CONNECT TO 'tcp:postgresql://host1,host2:5450/postgres';
EXEC SQL CONNECT TO 'tcp:postgresql://host1,host2:5450,5450/postgres';

EXEC SQL CONNECT TO 'postgres@host1,host2:5450';
EXEC SQL CONNECT TO 'postgres@host1,host2:5450,5450';


EXEC SQL CONNECT TO 'tcp:postgresql://?service=my_service';

~/.pg_service.conf
[my_service]
host=host1,host2
port=5450  # and port=5450,5450 case
dbname=postgres


But this one makes PQconnectdbParams() fail, because the passed "host" is "host1:5450,host2" and "port" is "5450".  ECPGconnect()'s parser is different from libpq's.  However, the tcp:postgresql:// syntax is not described a URL in the manual, so I think it's sufficient to just describe the syntax in the ECPG article.

EXEC SQL CONNECT TO 'tcp:postgresql://host1:5450,host2:5450/postgres';


And without the single quote like below, ecpg fails to precompile the source file.  I also think it's enough to state in the manual "quote the connection target if you specify multiple hosts or ports".

EXEC SQL CONNECT TO tcp:postgresql://host1,host2:5450,5450/postgres;

connect.ec:12: ERROR: syntax error at or near ","


Comments?


Regards
Takayuki Tsunakawa


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-11 14:03  Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Peter Eisentraut @ 2016-11-11 14:03 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 11/9/16 10:05 AM, Mithun Cy wrote:
> As in Victor's patch we have a new connection parameter
> "target_server_type", It can take 2 values 1. "any" 2. "master" with
> DEFAULT as "any". If it's has the value "any" we can connect to any of
> the host server (both master(primary) and slave(standby)). If the value
> is "master" then we try to connect to master(primary) only.

We tend to use the term "primary" instead of "master".

Will this work with logical replication?

-- 
Peter Eisentraut              http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 02:02  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-14 02:02 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> Great, committed.  There's still potentially more work to be done here,
> because my patch omits some features that were present in Victor's original
> submission, like setting the failover timeout, optionally randomizing the
> order of the hosts, and distinguishing between master and standby servers;
> Victor, or anyone, please feel free to submit separate patches for those
> things.

The attached patch fixes some bugs and make a clarification for doc.  Could you check and test the authentication stuff as I don't have an environment at hand?

(1) fe-connect.c
There was a memory leak.

(2) fe-secure_openssl.c, fe-auth.c
GSSAPI/SSPI/SSL authentication requires the target host name, but the code uses conn->pghost which contains a comma-separated list of host names.

(3) libpq.sgml
Added sentences to clarify connect_timeout when it is used with multiple hosts.

BTW, let me two questions.

Q1: Is there any reason why hostaddr doesn't accept multiple IP addresses?

Q2: pg_isready (and hence PQping() family) reports success when one host is alive and other hosts are down.  Is this intended?  I think this behavior is correct.
e.g. host1 is down and host2 is alive.
$ pg_isready -h host1,host2
host1,host2:5450 - accepting connections
$ echo $?
0

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

libpq-failover-smallbugs.patch (application/octet-stream, 5.7K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..f01ecf2 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -1009,6 +1009,9 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname Maximum wait for connection, in seconds (write as a decimal integer string). Zero or not specified means wait indefinitely. It is not recommended to use a timeout of less than 2 seconds. + This timeout is applied to a connection attempt with each host. + For example, if you specify two hosts and both of them are unreachable, + and connect_timeout is 5, the total timeout is 10 seconds. </para> </listitem> </varlistentry> diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 19171fb..d861dc4 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -170,8 +170,9 @@ pg_GSS_startup(PGconn *conn) min_stat; int maxlen; gss_buffer_desc temp_gbuf; + char *host = PQhost(conn); - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified\n")); @@ -198,7 +199,7 @@ pg_GSS_startup(PGconn *conn) return STATUS_ERROR; } snprintf(temp_gbuf.value, maxlen, "%s@%s", - conn->krbsrvname, conn->pghost); + conn->krbsrvname, host); temp_gbuf.length = strlen(temp_gbuf.value); maj_stat = gss_import_name(&min_stat, &temp_gbuf, @@ -371,6 +372,7 @@ pg_SSPI_startup(PGconn *conn, int use_negotiate) { SECURITY_STATUS r; TimeStamp expire; + char *host = PQhost(conn); conn->sspictx = NULL; @@ -406,19 +408,19 @@ pg_SSPI_startup(PGconn *conn, int use_negotiate) * but not more complex. We can skip the @REALM part, because Windows will * fill that in for us automatically. */ - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified\n")); return STATUS_ERROR; } - conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(conn->pghost) + 2); + conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(host) + 2); if (!conn->sspitarget) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); return STATUS_ERROR; } - sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, conn->pghost); + sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, host); /* * Indicate that we're in SSPI authentication mode to make sure that diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..cd8889f 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -4931,7 +4931,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { int prefix_len; char *p; - char *buf; + char *buf = NULL; char *start; char prevchar = '\0'; char *user = NULL; @@ -4946,7 +4946,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n")); - return false; + goto cleanup; } /* need a modifiable copy of the input URI */ @@ -4955,7 +4955,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n")); - return false; + goto cleanup; } start = buf; @@ -5156,7 +5156,8 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, cleanup: termPQExpBuffer(&hostbuf); termPQExpBuffer(&portbuf); - free(buf); + if (buf) + free(buf); return retval; } diff --git a/src/interfaces/libpq/fe-secure-openssl.c b/src/interfaces/libpq/fe-secure-openssl.c index f474c96..7bdf927 100644 --- a/src/interfaces/libpq/fe-secure-openssl.c +++ b/src/interfaces/libpq/fe-secure-openssl.c @@ -483,6 +483,7 @@ verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, char *name; const unsigned char *namedata; int result; + char *host = PQhost(conn); *store_name = NULL; @@ -528,12 +529,12 @@ verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, return -1; } - if (pg_strcasecmp(name, conn->pghost) == 0) + if (pg_strcasecmp(name, host) == 0) { /* Exact name match */ result = 1; } - else if (wildcard_certificate_match(name, conn->pghost)) + else if (wildcard_certificate_match(name, host)) { /* Matched wildcard name */ result = 1; @@ -563,6 +564,7 @@ verify_peer_name_matches_certificate(PGconn *conn) STACK_OF(GENERAL_NAME) *peer_san; int i; int rc; + char *host = PQhost(conn); /* * If told not to verify the peer name, don't do it. Return true @@ -572,7 +574,7 @@ verify_peer_name_matches_certificate(PGconn *conn) return true; /* Check that we have a hostname to compare with. */ - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified for a verified SSL connection\n")); @@ -670,13 +672,13 @@ verify_peer_name_matches_certificate(PGconn *conn) libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n", "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n", names_examined - 1), - first_name, names_examined - 1, conn->pghost); + first_name, names_examined - 1, host); } else if (names_examined == 1) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"), - first_name, conn->pghost); + first_name, host); } else {
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 06:01  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-14 06:01 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

Hi, Mithun

Before going deeper into the patch, let me give you some findings.

(1)
PGconn->target_server_type is not freed in freePGconn().


(2)
Could you add PGTARGETSERVERTYPE environment variable?  Like other variables, it will ease testing, since users can change the behavior without altering the connection string here and there.


(3)
I think it would be better to expose the server state via ParameterStatus protocol message like standard_conforming_strings, instead of running "SELECT pg_is_in_recovery()".  We shouldn't want to add one round trip to check the server type (master, standby).  postmaster can return the server type based on its state (pmState); PM_RUN is master, and PM_HOT_STANDBY is standby.  In addition, as an impractical concern, DBA can revoke EXECUTE privilege on pg_is_in_recovery() from non-superusers.

Regards
Takayuki Tsunakawa


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 07:38  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-14 07:38 UTC (permalink / raw)
  To: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Fri, Nov 11, 2016 at 7:33 PM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:
> We tend to use the term "primary" instead of "master".

Thanks, I will use primary instead of master in my next patch.

>Will this work with logical replication?

I have not tested with logical replication. Currently we identify the
primary to connect based on result of "SELECT pg_is_in_recovery()". So I
think it works. Do you want me test a particular setup?

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 07:56  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-14 07:56 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Nov 14, 2016 at 11:31 AM, Tsunakawa, Takayuki <
tsunakawa.takay@jp.fujitsu.com> wrote:
> PGconn->target_server_type is not freed in freePGconn().

Thanks, will fix in new patch.

>Could you add PGTARGETSERVERTYPE environment variable?  Like other
variables, it will ease testing, since users can change the behavior
>without altering the connection string here and there.

Okay, will add one.

> I think it would be better to expose the server state via ParameterStatus
protocol message like standard_conforming_strings, instead of running >
>"SELECT pg_is_in_recovery()".  We shouldn't want to add one round trip to
check the server type (master, standby).  postmaster can return the server
>type based on its state (pmState); PM_RUN is master, and PM_HOT_STANDBY is
standby.  In addition, as an impractical concern, DBA can revoke >EXECUTE
privilege on pg_is_in_recovery() from non-superusers.

If you are suggesting me to change in protocol messages, I think that would
not be backward compatible to older version servers. I also think such
level of protocol changes will not be allowed. with connection status
CONNECTION_SETENV used for protocol version 2.0 setup, we sent some query
 like
"select pg_catalog.pg_client_encoding()" for same. So I think using "SELECT
pg_is_in_recovery()" should be fine.
-
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 08:07  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-14 08:07 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> If you are suggesting me to change in protocol messages, I think that would
> not be backward compatible to older version servers. I also think such level
> of protocol changes will not be allowed. with connection status
> CONNECTION_SETENV used for protocol version 2.0 setup, we sent some query
> like "select pg_catalog.pg_client_encoding()" for same. So I think using
> "SELECT pg_is_in_recovery()" should be fine.

No, there's no concern about compatibility.  Please look at this:

https://www.postgresql.org/docs/devel/static/protocol-flow.html#PROTOCOL-ASYNC

[Excerpt]
----------------------------------------
ParameterStatus messages will be generated whenever the active value changes for any of the parameters the backend believes the frontend should know about. Most commonly this occurs in response to a SET SQL command executed by the frontend, and this case is effectively synchronous — but it is also possible for parameter status changes to occur because the administrator changed a configuration file and then sent the SIGHUP signal to the server. Also, if a SET command is rolled back, an appropriate ParameterStatus message will be generated to report the current effective value.

At present there is a hard-wired set of parameters for which ParameterStatus will be generated: they are server_version, server_encoding, client_encoding, application_name, is_superuser, session_authorization, DateStyle, IntervalStyle, TimeZone, integer_datetimes, and standard_conforming_strings. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0; standard_conforming_strings was not reported by releases before 8.1; IntervalStyle was not reported by releases before 8.4; application_name was not reported by releases before 9.0.) Note that server_version, server_encoding and integer_datetimes are pseudo-parameters that cannot change after startup. This set might change in the future, or even become configurable. Accordingly, a frontend should simply ignore ParameterStatus for parameters that it does not understand or care about.
----------------------------------------



Regards
Takayuki Tsunakawa


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-14 11:05  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-14 11:05 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Nov 14, 2016 at 1:37 PM, Tsunakawa, Takayuki <
tsunakawa.takay@jp.fujitsu.com> wrote:
 > No, there's no concern about compatibility.  Please look at this:
 > https://www.postgresql.org/docs/devel/static/protocol-
flow.html#PROTOCOL-ASYNC
Thanks, my concern is suppose you have 3 server in cluster A(new version),
B(new version), C(old version). If we implement as above only new servers
will send ParameterStatus message to indicate what type of server we are
connected. Server C will not send same. So we will not be able to use new
feature "failover to new master" for such a kind of cluster.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 01:09  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-15 01:09 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> Thanks, my concern is suppose you have 3 server in cluster A(new version),
> B(new version), C(old version). If we implement as above only new servers
> will send ParameterStatus message to indicate what type of server we are
> connected. Server C will not send same. So we will not be able to use new
> feature "failover to new master" for such a kind of cluster.

No, the streaming replication requires the same major release for all member servers, so there's no concern about the mixed-version cluster.

Sorry, pmState can only be used in postmaster.  In our context, postgres can use RecoveryInProgress().  Anyway, in addition to the reduced round trip, the libpq code would be much simpler.

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 14:32  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-15 14:32 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Nov 14, 2016 at 2:38 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Fri, Nov 11, 2016 at 7:33 PM, Peter Eisentraut
> <peter.eisentraut@2ndquadrant.com> wrote:
>> We tend to use the term "primary" instead of "master".
>
> Thanks, I will use primary instead of master in my next patch.
>
>>Will this work with logical replication?
>
> I have not tested with logical replication. Currently we identify the
> primary to connect based on result of "SELECT pg_is_in_recovery()". So I
> think it works. Do you want me test a particular setup?

If logical replication is in use, none of the servers involved would
be in recovery.  I'm not sure what command would need to be used to
assess whether we've got a master or a standby, but probably not that
one.  This gets at one of my earlier complaints about this part of the
functionality, which is that hardcoding that particular SQL statement
into libpq seems like a giant hack.  However, I'm not sure what to do
about it.  The functionality is clearly useful, because JDBC has it,
and Victor proposed this patch to add it to libpq, and - totally
independently of any of that - EnterpriseDB has a customer who has
requested libpq support for this as well.  So I am tempted to just
hold my nose and hard-code the SQL as JDBC is presumably already
doing.  If we figure out what the equivalent for logical replication
would be we can add something to cover that case, too.  It's ugly, but
I don't have a better idea, and I think there's value in being
compatible with what JDBC has already done (even if it's not what we
would have chosen to do tabula rasa).

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 14:36  Robert Haas <robertmhaas@gmail.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-15 14:36 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Nov 14, 2016 at 8:09 PM, Tsunakawa, Takayuki
<tsunakawa.takay@jp.fujitsu.com> wrote:
> From: pgsql-hackers-owner@postgresql.org
>> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
>> Thanks, my concern is suppose you have 3 server in cluster A(new version),
>> B(new version), C(old version). If we implement as above only new servers
>> will send ParameterStatus message to indicate what type of server we are
>> connected. Server C will not send same. So we will not be able to use new
>> feature "failover to new master" for such a kind of cluster.
>
> No, the streaming replication requires the same major release for all member servers, so there's no concern about the mixed-version cluster.

True, but there is a concern about a newer libpq connecting to older
servers.  If we mimic what JDBC is already doing, we'll be compatible
and you'll be able to use this feature with a v10 libpq without
worrying about whether the target server is also v10.  If we invent
something new on the server side, then you'll need to be sure you have
both a v10 libpq and v10 server.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 14:42  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 165+ messages in thread

From: Alvaro Herrera @ 2016-11-15 14:42 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

Robert Haas wrote:
> On Mon, Nov 14, 2016 at 2:38 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> > I have not tested with logical replication. Currently we identify the
> > primary to connect based on result of "SELECT pg_is_in_recovery()". So I
> > think it works. Do you want me test a particular setup?
> 
> If logical replication is in use, none of the servers involved would
> be in recovery.  I'm not sure what command would need to be used to
> assess whether we've got a master or a standby, but probably not that
> one.  This gets at one of my earlier complaints about this part of the
> functionality, which is that hardcoding that particular SQL statement
> into libpq seems like a giant hack.  However, I'm not sure what to do
> about it.  The functionality is clearly useful, because JDBC has it,
> and Victor proposed this patch to add it to libpq, and - totally
> independently of any of that - EnterpriseDB has a customer who has
> requested libpq support for this as well.  So I am tempted to just
> hold my nose and hard-code the SQL as JDBC is presumably already
> doing.  If we figure out what the equivalent for logical replication
> would be we can add something to cover that case, too.  It's ugly, but
> I don't have a better idea, and I think there's value in being
> compatible with what JDBC has already done (even if it's not what we
> would have chosen to do tabula rasa).

I would rather come up with something that works in both cases that we
can extend internally later, say pg_is_primary_node() or something like
that instead; and we implement it initially by returning the inverse of
pg_is_in_recovery() for replicated non-logical flocks, while we figure
out what to do in logical replication.  Otherwise it will be harder to
change later if we embed it in libpq, and we may be forced into
supporting nonsensical situations such as having pg_is_in_recovery()
return true for logical replication primary nodes.

FWIW I'm not sure "primary" is the right term here either.  I think what
we really want to know is whether the node can accept writes; maybe
"pg_is_writable_node".

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 16:58  Robert Haas <robertmhaas@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-15 16:58 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 15, 2016 at 9:42 AM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Robert Haas wrote:
>> On Mon, Nov 14, 2016 at 2:38 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>> > I have not tested with logical replication. Currently we identify the
>> > primary to connect based on result of "SELECT pg_is_in_recovery()". So I
>> > think it works. Do you want me test a particular setup?
>>
>> If logical replication is in use, none of the servers involved would
>> be in recovery.  I'm not sure what command would need to be used to
>> assess whether we've got a master or a standby, but probably not that
>> one.  This gets at one of my earlier complaints about this part of the
>> functionality, which is that hardcoding that particular SQL statement
>> into libpq seems like a giant hack.  However, I'm not sure what to do
>> about it.  The functionality is clearly useful, because JDBC has it,
>> and Victor proposed this patch to add it to libpq, and - totally
>> independently of any of that - EnterpriseDB has a customer who has
>> requested libpq support for this as well.  So I am tempted to just
>> hold my nose and hard-code the SQL as JDBC is presumably already
>> doing.  If we figure out what the equivalent for logical replication
>> would be we can add something to cover that case, too.  It's ugly, but
>> I don't have a better idea, and I think there's value in being
>> compatible with what JDBC has already done (even if it's not what we
>> would have chosen to do tabula rasa).
>
> I would rather come up with something that works in both cases that we
> can extend internally later, say pg_is_primary_node() or something like
> that instead; and we implement it initially by returning the inverse of
> pg_is_in_recovery() for replicated non-logical flocks, while we figure
> out what to do in logical replication.  Otherwise it will be harder to
> change later if we embed it in libpq, and we may be forced into
> supporting nonsensical situations such as having pg_is_in_recovery()
> return true for logical replication primary nodes.

I don't think we'll be backed into a corner like that, because we can
always make this contingent on server version.  libpq will have that
available.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 17:53  Catalin Iacob <iacobcatalin@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Catalin Iacob @ 2016-11-15 17:53 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 15, 2016 at 5:58 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> On Tue, Nov 15, 2016 at 9:42 AM, Alvaro Herrera
> <alvherre@2ndquadrant.com> wrote:
>> I would rather come up with something that works in both cases that we
>> can extend internally later, say pg_is_primary_node() or something like
>> that instead; and we implement it initially by returning the inverse of
>> pg_is_in_recovery() for replicated non-logical flocks, while we figure
>> out what to do in logical replication.  Otherwise it will be harder to
>> change later if we embed it in libpq, and we may be forced into
>> supporting nonsensical situations such as having pg_is_in_recovery()
>> return true for logical replication primary nodes.
>
> I don't think we'll be backed into a corner like that, because we can
> always make this contingent on server version.  libpq will have that
> available.

But even with server version checking code, that code will be inside
libpq so there will be old libpq versions in the field that won't know
the proper query to send to new server versions.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 18:00  Catalin Iacob <iacobcatalin@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Catalin Iacob @ 2016-11-15 18:00 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 15, 2016 at 3:42 PM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> FWIW I'm not sure "primary" is the right term here either.  I think what
> we really want to know is whether the node can accept writes; maybe
> "pg_is_writable_node".

This made me think of another complication: what about cascading
replication where the middle node is both a master and a slave? You'd
probably not want to fallback to the middle node even though it is a
master for its downstream.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 18:14  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Catalin Iacob <iacobcatalin@gmail.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Alvaro Herrera @ 2016-11-15 18:14 UTC (permalink / raw)
  To: Catalin Iacob <iacobcatalin@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

Catalin Iacob wrote:
> On Tue, Nov 15, 2016 at 3:42 PM, Alvaro Herrera
> <alvherre@2ndquadrant.com> wrote:
> > FWIW I'm not sure "primary" is the right term here either.  I think what
> > we really want to know is whether the node can accept writes; maybe
> > "pg_is_writable_node".
> 
> This made me think of another complication: what about cascading
> replication where the middle node is both a master and a slave? You'd
> probably not want to fallback to the middle node even though it is a
> master for its downstream.

Exactly my thought, hence the above suggestion.

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-15 18:28  Robert Haas <robertmhaas@gmail.com>
  parent: Catalin Iacob <iacobcatalin@gmail.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-15 18:28 UTC (permalink / raw)
  To: Catalin Iacob <iacobcatalin@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 15, 2016 at 12:53 PM, Catalin Iacob <iacobcatalin@gmail.com> wrote:
> On Tue, Nov 15, 2016 at 5:58 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> On Tue, Nov 15, 2016 at 9:42 AM, Alvaro Herrera
>> <alvherre@2ndquadrant.com> wrote:
>>> I would rather come up with something that works in both cases that we
>>> can extend internally later, say pg_is_primary_node() or something like
>>> that instead; and we implement it initially by returning the inverse of
>>> pg_is_in_recovery() for replicated non-logical flocks, while we figure
>>> out what to do in logical replication.  Otherwise it will be harder to
>>> change later if we embed it in libpq, and we may be forced into
>>> supporting nonsensical situations such as having pg_is_in_recovery()
>>> return true for logical replication primary nodes.
>>
>> I don't think we'll be backed into a corner like that, because we can
>> always make this contingent on server version.  libpq will have that
>> available.
>
> But even with server version checking code, that code will be inside
> libpq so there will be old libpq versions in the field that won't know
> the proper query to send to new server versions.

Good point.  pg_is_writable_node() sounds good, then, and we can still
send pg_is_in_recovery() if we're connected to a pre-10 version.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-16 04:31  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 3 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-16 04:31 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

>
> > So I am tempted to just
> > hold my nose and hard-code the SQL as JDBC is presumably already
> doing.


JDBC is sending "show transaction_read_only" to find whether it is master
or not.
Victor's patch also started with it, but later it was transformed into
pg_is_in_recovery
by him as it appeared more appropriate to identify the master / slave.

ConnectionFactoryImpl.java:685

+ private boolean isMaster(QueryExecutor queryExecutor, Logger logger)
+ throws SQLException, IOException {
+    byte[][] results = SetupQueryRunner.run(queryExecutor, "show
transaction_read_only", true);
+    String value = queryExecutor.getEncoding().decode(results[0]);
+    return value.equalsIgnoreCase("off");
}

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-16 05:03  Tatsuo Ishii <ishii@sraoss.co.jp>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Tatsuo Ishii @ 2016-11-16 05:03 UTC (permalink / raw)
  To: mithun.cy@enterprisedb.com; +Cc: robertmhaas@gmail.com; peter.eisentraut@2ndquadrant.com; pvh@pvh.ca; pgsql-hackers@postgresql.org

> JDBC is sending "show transaction_read_only" to find whether it is master
> or not.
> Victor's patch also started with it, but later it was transformed into
> pg_is_in_recovery
> by him as it appeared more appropriate to identify the master / slave.

In my understanding pg_is_in_recovery() returns true if it's a standby
node. However, even if it returns other than true, the server is not
necessarily a primary. Even it's not configured as a streaming
replication primary, it returns other than true.

So if your intention is finding a primary, I am not sure if
pg_is_in_recovery() is the best solution.

Best regards,
--
Tatsuo Ishii
SRA OSS, Inc. Japan
English: http://www.sraoss.co.jp/index_en.php
Japanese:http://www.sraoss.co.jp


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-16 13:50  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-16 13:50 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 15, 2016 at 11:31 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>> > So I am tempted to just
>> > hold my nose and hard-code the SQL as JDBC is presumably already
>> doing.
>
> JDBC is sending "show transaction_read_only" to find whether it is master or
> not.
> Victor's patch also started with it, but later it was transformed into
> pg_is_in_recovery
> by him as it appeared more appropriate to identify the master / slave.

Hmm, let's go back to the JDBC method, then.  "show
transaction_read_only" will return true on a standby, but presumably
also on any other non-writable node.  You could even force it to be
true artificially if you wanted to force traffic off of a node, using
ALTER {SYSTEM|USER ...|DATABASE ..} SET default_transaction_read_only
= on

I think that would address Alvaro's concern, and it's nicer anyway if
libpq and JDBC are doing the same thing.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: [HACKERS] Patch: Implement failover on libpq connect level.
@ 2016-11-16 14:02  Kevin Grittner <kgrittn@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  2 siblings, 1 reply; 165+ messages in thread

From: Kevin Grittner @ 2016-11-16 14:02 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-jdbc

[moving this branch of discussion to pgsql-jdbc]

On Tue, Nov 15, 2016 at 10:31 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:

> JDBC is sending "show transaction_read_only" to find whether it
> is master or not.

If true, that's insane.  That can be different on each connection
to the cluster and can change tens of thousands of times per second
on any connection!

I know of one large shop that sets default_transaction_read_only =
true because 99% of their transactions are read only and they use
serializable transactions -- which run faster and with less
contention when transactions which don't need to write are flagged
as read only.  It seems safer to them to only turn off the read
only property for transactions which might need to write.

> Victor's patch also started with it, but later it was transformed into
> pg_is_in_recovery
> by him as it appeared more appropriate to identify the master / slave.

I don't know whether that is ideal, but it is sure a lot better
than something which can change with every transaction -- or even
within a transaction (in one direction).

--
Kevin Grittner
EDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: [HACKERS] Patch: Implement failover on libpq connect level.
@ 2016-11-16 15:13  Robert Haas <robertmhaas@gmail.com>
  parent: Kevin Grittner <kgrittn@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-16 15:13 UTC (permalink / raw)
  To: Kevin Grittner <kgrittn@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-jdbc

On Wed, Nov 16, 2016 at 9:02 AM, Kevin Grittner <kgrittn@gmail.com> wrote:
> [moving this branch of discussion to pgsql-jdbc]
>
> On Tue, Nov 15, 2016 at 10:31 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>
>> JDBC is sending "show transaction_read_only" to find whether it
>> is master or not.
>
> If true, that's insane.  That can be different on each connection
> to the cluster and can change tens of thousands of times per second
> on any connection!

I don't think that's insane.  The command is only being issued at
connection startup, and will only be different on different
connections if it's been configured that way.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-16 17:00  Catalin Iacob <iacobcatalin@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Catalin Iacob @ 2016-11-16 17:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 16, 2016 at 2:50 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Hmm, let's go back to the JDBC method, then.  "show
> transaction_read_only" will return true on a standby, but presumably
> also on any other non-writable node.  You could even force it to be
> true artificially if you wanted to force traffic off of a node, using
> ALTER {SYSTEM|USER ...|DATABASE ..} SET default_transaction_read_only
> = on
>
> I think that would address Alvaro's concern, and it's nicer anyway if
> libpq and JDBC are doing the same thing.

Not sure I agree that using this is a good idea in the first place.

But if we end up using this, I really think the docs should be very
explicit about what's implemented and not just say master/any. With
the master/any docs in the patch I would be *very* surprised if a
master is skipped only because it was configured with
default_transaction_read_only = on.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-16 18:55  Robert Haas <robertmhaas@gmail.com>
  parent: Catalin Iacob <iacobcatalin@gmail.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-16 18:55 UTC (permalink / raw)
  To: Catalin Iacob <iacobcatalin@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 16, 2016 at 12:00 PM, Catalin Iacob <iacobcatalin@gmail.com> wrote:
> On Wed, Nov 16, 2016 at 2:50 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Hmm, let's go back to the JDBC method, then.  "show
>> transaction_read_only" will return true on a standby, but presumably
>> also on any other non-writable node.  You could even force it to be
>> true artificially if you wanted to force traffic off of a node, using
>> ALTER {SYSTEM|USER ...|DATABASE ..} SET default_transaction_read_only
>> = on
>>
>> I think that would address Alvaro's concern, and it's nicer anyway if
>> libpq and JDBC are doing the same thing.
>
> Not sure I agree that using this is a good idea in the first place.
>
> But if we end up using this, I really think the docs should be very
> explicit about what's implemented and not just say master/any. With
> the master/any docs in the patch I would be *very* surprised if a
> master is skipped only because it was configured with
> default_transaction_read_only = on.

It seems like it is going to be difficult to please everyone here
100%, because there are multiple conflicting priorities.  But we can
definitely document whatever choices we make.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:00  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-17 02:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> On Mon, Nov 14, 2016 at 8:09 PM, Tsunakawa, Takayuki
> <tsunakawa.takay@jp.fujitsu.com> wrote:
> > From: pgsql-hackers-owner@postgresql.org
> >> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> >> Thanks, my concern is suppose you have 3 server in cluster A(new
> >> version), B(new version), C(old version). If we implement as above
> >> only new servers will send ParameterStatus message to indicate what
> >> type of server we are connected. Server C will not send same. So we
> >> will not be able to use new feature "failover to new master" for such
> a kind of cluster.
> >
> > No, the streaming replication requires the same major release for all
> member servers, so there's no concern about the mixed-version cluster.
> 
> True, but there is a concern about a newer libpq connecting to older servers.
> If we mimic what JDBC is already doing, we'll be compatible and you'll be
> able to use this feature with a v10 libpq without worrying about whether
> the target server is also v10.  If we invent something new on the server
> side, then you'll need to be sure you have both a v10 libpq and v10 server.

Do we really want to enable libpq failover against pre-V10 servers?  I don't think so, as libpq is a part of PostgreSQL and libpq failover is a new feature in PostgreSQL 10.  At least, as one user, I don't want PostgreSQL to sacrifice another round trip to establish a connection.  As a developer, I don't want libpq code more complex than necessary (the proposed patch adds a new state to the connection state machine.)  And I think it's natural for the server to return the server attribute (primary/standby, writable, etc.) as a response to the Startup message like server_version, standard_conforming_strings and server_encoding.

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: [HACKERS] Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:09  Craig Ringer <craig@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2016-11-17 02:09 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Kevin Grittner <kgrittn@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-jdbc

On 16 November 2016 at 23:13, Robert Haas <robertmhaas@gmail.com> wrote:
> On Wed, Nov 16, 2016 at 9:02 AM, Kevin Grittner <kgrittn@gmail.com> wrote:
>> [moving this branch of discussion to pgsql-jdbc]
>>
>> On Tue, Nov 15, 2016 at 10:31 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>>
>>> JDBC is sending "show transaction_read_only" to find whether it
>>> is master or not.
>>
>> If true, that's insane.  That can be different on each connection
>> to the cluster and can change tens of thousands of times per second
>> on any connection!
>
> I don't think that's insane.  The command is only being issued at
> connection startup, and will only be different on different
> connections if it's been configured that way.

I agree. However, I also think we should make sure add a GUC_REPORT
var in v10 that lets a client tell whether it's connected to a
read/write or read-only node right from the start. This will save an
unnecessary round-trip and some annoying log-spam.

I'd rather not bind it directly to "in recovery" because we're likely
to want to support read-only logical replication nodes in future, but
even that would be OK.

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:29  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Tatsuo Ishii <ishii@sraoss.co.jp>
  0 siblings, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-17 02:29 UTC (permalink / raw)
  To: Tatsuo Ishii <ishii@sraoss.co.jp>; mithun.cy@enterprisedb.com <mithun.cy@enterprisedb.com>; +Cc: robertmhaas@gmail.com <robertmhaas@gmail.com>; peter.eisentraut@2ndquadrant.com <peter.eisentraut@2ndquadrant.com>; pvh@pvh.ca <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Tatsuo Ishii
> In my understanding pg_is_in_recovery() returns true if it's a standby node.
> However, even if it returns other than true, the server is not necessarily
> a primary. Even it's not configured as a streaming replication primary,
> it returns other than true.
> 
> So if your intention is finding a primary, I am not sure if
> pg_is_in_recovery() is the best solution.

Yes, I don't think pg_is_in_recovery() is the best, but there doesn't seem to be a better solution.  pg_is_in_recovery(), as its name clearly suggests, returns true if the server is performing recovery.  For example, it returns true if hot_standby=on is present in postgresql.conf and the recovery from backup is in progress.  It's not a standby.

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: [HACKERS] Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:49  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-17 02:49 UTC (permalink / raw)
  To: Craig Ringer <craig@2ndquadrant.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Kevin Grittner <kgrittn@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-jdbc

From: pgsql-jdbc-owner@postgresql.org
> [mailto:pgsql-jdbc-owner@postgresql.org] On Behalf Of Craig Ringer
> >> If true, that's insane.  That can be different on each connection to
> >> the cluster and can change tens of thousands of times per second on
> >> any connection!
> >
> > I don't think that's insane.  The command is only being issued at
> > connection startup, and will only be different on different
> > connections if it's been configured that way.
> 
> I agree. However, I also think we should make sure add a GUC_REPORT var
> in v10 that lets a client tell whether it's connected to a read/write or
> read-only node right from the start. This will save an unnecessary
> round-trip and some annoying log-spam.

Yes, I meant the GUC_REPORT method.  I don't think something like read-only and read/write is intuitive as values values of target_server_type, because people who want to use reporting apps that use temporary tables have to connect to the primary, because temp tables are not supported on standbys.  I think the current notion of primary/standby is good; those who require temp tables need to specify primary.


> I'd rather not bind it directly to "in recovery" because we're likely to
> want to support read-only logical replication nodes in future, but even
> that would be OK.

Maybe we should determine the name and value of the connection parameter and GUC-REPORTed variable in light of the logical replication.

Regards
Takayuki Tsunakawa


-- 
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:56  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-17 02:56 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> Hmm, let's go back to the JDBC method, then.  "show transaction_read_only"
> will return true on a standby, but presumably also on any other non-writable
> node.  You could even force it to be true artificially if you wanted to
> force traffic off of a node, using ALTER {SYSTEM|USER ...|DATABASE ..} SET
> default_transaction_read_only = on
> 
> I think that would address Alvaro's concern, and it's nicer anyway if libpq
> and JDBC are doing the same thing.

If you prefer consistency between libpq and JDBC, then we could correct JDBC.  People here should know the server state well, and be able to figure out a good specification.

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-17 02:57  Robert Haas <robertmhaas@gmail.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-17 02:57 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 16, 2016 at 9:00 PM, Tsunakawa, Takayuki
<tsunakawa.takay@jp.fujitsu.com> wrote:
> Do we really want to enable libpq failover against pre-V10 servers?  I don't think so, as libpq is a part of PostgreSQL and libpq failover is a new feature in PostgreSQL 10.  At least, as one user, I don't want PostgreSQL to sacrifice another round trip to establish a connection.  As a developer, I don't want libpq code more complex than necessary (the proposed patch adds a new state to the connection state machine.)  And I think it's natural for the server to return the server attribute (primary/standby, writable, etc.) as a response to the Startup message like server_version, standard_conforming_strings and server_encoding.

Well, generally speaking, a new feature that works against older
server is better than one that doesn't.  Of course, if that entails
making other compromises then you have to decide whether it's worth
it, but SELECT pg_is_in_recovery() and SHOW transaction_read_only
exist in older versions so if we pick either of those methods then it
will just work.  If we decide to invent some completely new method of
distinguishing masters from standbys, then it might not, but that
would be a drawback of such a choice, not a benefit.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-17 11:33  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-17 11:33 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 17, 2016 at 8:27 AM, Robert Haas <robertmhaas@gmail.com> wrote:
>but SELECT pg_is_in_recovery() and SHOW transaction_read_only
>exist in older versions so if we pick either of those methods then it
>will just work.

I am adding next version of the patch it have following fixes.
Tsunakawa's comments
1.  PGconn->target_server_type is now freed in freePGconn()
2.  Added PGTARGETSERVERTYPE.

*Additional comments from others*
3.  Moved from SELECT pg_is_in_recovery() to SHOW transaction_read_only now
should handle different kind of replication, as we recognise server to
which writable connection can be made as primary. Very exactly like JDBC
driver. Also documented about it.
4. renamed words from master to primary.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover_to_new_master-v2.patch (application/octet-stream, 12.3K) download commit 03def11a0b8b4a3927b70d6dcc9f0baa3c62d756 Author: mithun <mithun@localhost.localdomain> Date: Thu Nov 17 16:59:44 2016 +0530 Mithuns patch diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..0a0b820 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -811,7 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp -postgresql://host1:123,host2:456/somedb +postgresql://host1:123,host2:456/somedb?target_server_type=any&amp;application_name=myapp </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -1382,6 +1382,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + This parameter specifies what kind of server to connect. + Set this to <literal>primary</literal>, to connect only to primary + server. Set this to <literaL>any</literal>, if you want to connect to + any of the given host. And, the default is <literal>any</literal>. + A server is recognized as a primary/standby by observering whether it + allows write for this connection. Internally we identify same based on + the output of <literal>show transaction_read_only</literal>. + </para> + </listitem> + </varlistentry> </variablelist> </para> </sect2> @@ -7065,6 +7079,16 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-client-encoding"> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGTARGETSERVERTYPE</envar></primary> + </indexterm> + <envar>PGTARGETSERVERTYPE</envar> behaves the same as the <xref + linkend="libpq-connect-target-server-type"> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..fff5049 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -300,6 +300,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"target_server_type", "PGTARGETSERVERTYPE", NULL, NULL, + "Target server type", "", 6, + offsetof(struct pg_conn, target_server_type)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +340,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void release_all_addrinfo(PGconn *conn); +static void sendTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -1026,6 +1032,24 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "primary") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value:" + " \"%s\" should be \"any\" or " + "\"primary\"\n"), + conn->target_server_type); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1814,6 +1838,7 @@ PQconnectPoll(PGconn *conn) /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: + case CONNECTION_CHECK_PRIMARY: break; default: @@ -2752,27 +2777,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address lists now. */ - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; - -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2782,7 +2786,25 @@ keep_going: /* We will come back to here until there is return PGRES_POLLING_WRITING; } - /* Otherwise, we are open for business! */ + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } @@ -2814,10 +2836,112 @@ keep_going: /* We will come back to here until there is goto error_return; } + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; + case CONNECTION_CHECK_PRIMARY: + { + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + goto error_return; + + if (PQisBusy(conn)) + { + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) && + PQntuples(res) == 1) + { + char *val; + val = PQgetvalue(res, 0 , 0); + if (strncmp(val, "on", 2) == 0) + { + PQclear(res); + + /* + * This is a hot standby server terminate this connection + * and try next address. + */ + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Connection failed, " + "%s:%s is a hot standby.\n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + PQclear(res); + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Something went wrong with + * "SELECT pg_catalog.pg_is_in_recovery()". We should try next + * addresses. + */ + if (res) + PQclear(res); + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("test to check if, %s:%s is a \"primary\" " + "failed \n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " @@ -3109,6 +3233,8 @@ freePGconn(PGconn *conn) free(conn->outBuffer); if (conn->rowBuf) free(conn->rowBuf); + if (conn->target_server_type) + free(conn->target_server_type); termPQExpBuffer(&conn->errorMessage); termPQExpBuffer(&conn->workBuffer); @@ -3120,19 +3246,41 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * release_all_addrinfo + * - free addrinfo of all hostconn elements. */ + static void -closePGconn(PGconn *conn) +release_all_addrinfo(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } + conn->addr_cur = NULL; +} +/* + * sendTerminateConn + * - Send a terminate message to backend. + */ +static void +sendTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -3147,6 +3295,23 @@ closePGconn(PGconn *conn) pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + sendTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -3165,25 +3330,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; + release_all_addrinfo(conn); -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) { diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..f39a110 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,8 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_PRIMARY /* Check if it is connected to PRIMARY. */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 854ec89..710f3ab 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,9 @@ struct pg_conn char *krbsrvname; /* Kerberos service name */ #endif + char *target_server_type; /* Type of server to connect. + * Possible values any, primary. */ + /* Optional file to write trace info to */ FILE *Pfdebug;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-18 01:09  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-18 01:09 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Mithun Cy
> I am adding next version of the patch it have following fixes.
> Tsunakawa's comments
> 
> 1.  PGconn->target_server_type is now freed in freePGconn() 2.  Added
> PGTARGETSERVERTYPE.
> 
> 
> Additional comments from others
> 3.  Moved from SELECT pg_is_in_recovery() to SHOW transaction_read_only
> now should handle different kind of replication, as we recognise server
> to which writable connection can be made as primary. Very exactly like JDBC
> driver. Also documented about it.
> 4. renamed words from master to primary.

Thank you.  The following items need addressing.  Some of them require some more discussion to reach consensus, and I hope they will settle down soon.  After checking the progress for a week or so, I'll mark the CommitFest entry as "ready for committer" or "waiting on author".

(1)
+        server. Set this to <literaL>any</literal>, if you want to connect to
+        A server is recognized as a primary/standby by observering whether it

Typo.  <literaL. -> <literal>, and "observering" -> "observing".


(2)
+	{"target_server_type", "PGTARGETSERVERTYPE", NULL, NULL,
+		"Target server type", "", 6,

Looking at existing parameters, the default value is defined as a macro, and the display label is a sequence of words separated by "-".  i.e.

+	{"target_server_type", "PGTARGETSERVERTYPE", DefaultTargetServerType, NULL,
+		"Target-Server-Type", "", 6,


(3)
Please avoid adding another round trip by using a GUC_REPORTed variable (ParameterStatus entry).  If you want to support this libpq failover with pre-10 servers, you can switch the method of determining the primary based on the server version.  But I don't think it's worth supporting older servers at the price of libpq code complexity.


(4)
Please consider supporting "standby" and "prefer_standby" like PgJDBC.  They are useful without load balancing when multiple standbys are used for HA.


(5)
I haven't tracked the progress of logical replication, but will target_server_type be likely to be usable with it?  How will target_server_type fit logical replication?

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-18 03:08  Craig Ringer <craig@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2016-11-18 03:08 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 17 November 2016 at 10:57, Robert Haas <robertmhaas@gmail.com> wrote:
> On Wed, Nov 16, 2016 at 9:00 PM, Tsunakawa, Takayuki
> <tsunakawa.takay@jp.fujitsu.com> wrote:
>> Do we really want to enable libpq failover against pre-V10 servers?  I don't think so, as libpq is a part of PostgreSQL and libpq failover is a new feature in PostgreSQL 10.  At least, as one user, I don't want PostgreSQL to sacrifice another round trip to establish a connection.  As a developer, I don't want libpq code more complex than necessary (the proposed patch adds a new state to the connection state machine.)  And I think it's natural for the server to return the server attribute (primary/standby, writable, etc.) as a response to the Startup message like server_version, standard_conforming_strings and server_encoding.
>
> Well, generally speaking, a new feature that works against older
> server is better than one that doesn't.  Of course, if that entails
> making other compromises then you have to decide whether it's worth
> it, but SELECT pg_is_in_recovery() and SHOW transaction_read_only
> exist in older versions so if we pick either of those methods then it
> will just work.  If we decide to invent some completely new method of
> distinguishing masters from standbys, then it might not, but that
> would be a drawback of such a choice, not a benefit.

We can and probably should have both.

If the server tells us on connect whether it's a standby or not, use that.

Otherwise, ask it.

That way we don't pay the round-trip cost and get the log spam when
talking to newer servers that send us something useful in the startup
packet, but we can still query it on older servers. Graceful fallback.

Every round trip is potentially very expensive. Having libpq do them
unnecessarily is bad.

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-18 17:29  Robert Haas <robertmhaas@gmail.com>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-18 17:29 UTC (permalink / raw)
  To: Craig Ringer <craig@2ndquadrant.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 17, 2016 at 10:08 PM, Craig Ringer <craig@2ndquadrant.com> wrote:
> On 17 November 2016 at 10:57, Robert Haas <robertmhaas@gmail.com> wrote:
>> On Wed, Nov 16, 2016 at 9:00 PM, Tsunakawa, Takayuki
>> <tsunakawa.takay@jp.fujitsu.com> wrote:
>>> Do we really want to enable libpq failover against pre-V10 servers?  I don't think so, as libpq is a part of PostgreSQL and libpq failover is a new feature in PostgreSQL 10.  At least, as one user, I don't want PostgreSQL to sacrifice another round trip to establish a connection.  As a developer, I don't want libpq code more complex than necessary (the proposed patch adds a new state to the connection state machine.)  And I think it's natural for the server to return the server attribute (primary/standby, writable, etc.) as a response to the Startup message like server_version, standard_conforming_strings and server_encoding.
>>
>> Well, generally speaking, a new feature that works against older
>> server is better than one that doesn't.  Of course, if that entails
>> making other compromises then you have to decide whether it's worth
>> it, but SELECT pg_is_in_recovery() and SHOW transaction_read_only
>> exist in older versions so if we pick either of those methods then it
>> will just work.  If we decide to invent some completely new method of
>> distinguishing masters from standbys, then it might not, but that
>> would be a drawback of such a choice, not a benefit.
>
> We can and probably should have both.
>
> If the server tells us on connect whether it's a standby or not, use that.
>
> Otherwise, ask it.
>
> That way we don't pay the round-trip cost and get the log spam when
> talking to newer servers that send us something useful in the startup
> packet, but we can still query it on older servers. Graceful fallback.
>
> Every round trip is potentially very expensive. Having libpq do them
> unnecessarily is bad.

True, but raising the bar for this feature so that it doesn't get done
is also bad.  It can be improved in a later patch.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-19 01:23  Craig Ringer <craig@2ndquadrant.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Craig Ringer @ 2016-11-19 01:23 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 19 November 2016 at 01:29, Robert Haas <robertmhaas@gmail.com> wrote:

>> We can and probably should have both.
>>
>> If the server tells us on connect whether it's a standby or not, use that.
>>
>> Otherwise, ask it.
>>
>> That way we don't pay the round-trip cost and get the log spam when
>> talking to newer servers that send us something useful in the startup
>> packet, but we can still query it on older servers. Graceful fallback.
>>
>> Every round trip is potentially very expensive. Having libpq do them
>> unnecessarily is bad.
>
> True, but raising the bar for this feature so that it doesn't get done
> is also bad.  It can be improved in a later patch.

Good point. Starting with the followup query method seems fine.


-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-20 16:08  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-20 16:08 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Fri, Nov 18, 2016 at 6:39 AM, Tsunakawa, Takayuki <
tsunakawa.takay@jp.fujitsu.com> wrote:
 >Typo.  <literaL. -> <literal>, and "observering" -> "observing".

Thanks fixed.

> +       {"target_server_type", "PGTARGETSERVERTYPE",
DefaultTargetServerType, NULL,
> +               "Target-Server-Type", "", 6,

Thanks fixed.

> Please avoid adding another round trip by using a GUC_REPORTed variable
(ParameterStatus entry).  If you want to support this libpq failover with
>pre-10 servers, you can switch the method of determining the primary based
on the server version.  But I don't think it's worth supporting older
servers > at the price of libpq code complexity.

Currently there is no consensus around this. For now, making this patch to
address failover to next primary as similar to JDBC seems sufficient for me.
On next proposal of patch I think we can try to extend as you have proposed

>Please consider supporting "standby" and "prefer_standby" like PgJDBC.
They are useful without load balancing when multiple standbys are used for
HA.

I think they become more relevant with load-balancing. And, making it
usable when we extend this feature to have load-balancing makes sense to
me.

> I haven't tracked the progress of logical replication, but will
target_server_type be likely to be usable with it?  How will
target_server_type fit logical       > replication?

I tried to check logical replication WIP patch, not very sure how to
accomodate same.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover_to_new_master_v3.patch (application/octet-stream, 12.4K) download commit bf2b8500df2f28cfc99b3721c077e0033b946088 Author: mithun <mithun@localhost.localdomain> Date: Sat Nov 19 21:52:17 2016 +0530 Mithuns patch diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..385a931 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -811,7 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp -postgresql://host1:123,host2:456/somedb +postgresql://host1:123,host2:456/somedb?target_server_type=any&amp;application_name=myapp </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -1382,6 +1382,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + This parameter specifies what kind of server to connect. + Set this to <literal>primary</literal>, to connect only to primary + server. Set this to <literal>any</literal>, if you want to connect to + any of the given host. And, the default is <literal>any</literal>. + A server is recognized as a primary/standby by observering whether it + allows write for this connection. Internally we identify same based on + the output of <literal>show transaction_read_only</literal>. + </para> + </listitem> + </varlistentry> </variablelist> </para> </sect2> @@ -7065,6 +7079,16 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-client-encoding"> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGTARGETSERVERTYPE</envar></primary> + </indexterm> + <envar>PGTARGETSERVERTYPE</envar> behaves the same as the <xref + linkend="libpq-connect-target-server-type"> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..773137c 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -300,6 +300,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"target_server_type", "PGTARGETSERVERTYPE", NULL, NULL, + "Target-Server-Type", "", 8, /* sizeof("primary") = 8 */ + offsetof(struct pg_conn, target_server_type)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +340,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void release_all_addrinfo(PGconn *conn); +static void sendTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -1026,6 +1032,24 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "primary") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value:" + " \"%s\" should be \"any\" or " + "\"primary\"\n"), + conn->target_server_type); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1814,6 +1838,7 @@ PQconnectPoll(PGconn *conn) /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: + case CONNECTION_CHECK_PRIMARY: break; default: @@ -2752,27 +2777,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address lists now. */ - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; - -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2782,7 +2786,25 @@ keep_going: /* We will come back to here until there is return PGRES_POLLING_WRITING; } - /* Otherwise, we are open for business! */ + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } @@ -2814,10 +2836,112 @@ keep_going: /* We will come back to here until there is goto error_return; } + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; + case CONNECTION_CHECK_PRIMARY: + { + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + goto error_return; + + if (PQisBusy(conn)) + { + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) && + PQntuples(res) == 1) + { + char *val; + val = PQgetvalue(res, 0 , 0); + if (strncmp(val, "on", 2) == 0) + { + PQclear(res); + + /* + * This is a hot standby server terminate this connection + * and try next address. + */ + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Connection failed, " + "%s:%s is a hot standby.\n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + PQclear(res); + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Something went wrong with + * "SELECT pg_catalog.pg_is_in_recovery()". We should try next + * addresses. + */ + if (res) + PQclear(res); + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("test to check if, %s:%s is a \"primary\" " + "failed \n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " @@ -3109,6 +3233,8 @@ freePGconn(PGconn *conn) free(conn->outBuffer); if (conn->rowBuf) free(conn->rowBuf); + if (conn->target_server_type) + free(conn->target_server_type); termPQExpBuffer(&conn->errorMessage); termPQExpBuffer(&conn->workBuffer); @@ -3120,19 +3246,41 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * release_all_addrinfo + * - free addrinfo of all hostconn elements. */ + static void -closePGconn(PGconn *conn) +release_all_addrinfo(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } + conn->addr_cur = NULL; +} +/* + * sendTerminateConn + * - Send a terminate message to backend. + */ +static void +sendTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -3147,6 +3295,23 @@ closePGconn(PGconn *conn) pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + sendTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -3165,25 +3330,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; + release_all_addrinfo(conn); -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) { diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..f39a110 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,8 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_PRIMARY /* Check if it is connected to PRIMARY. */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 854ec89..710f3ab 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,9 @@ struct pg_conn char *krbsrvname; /* Kerberos service name */ #endif + char *target_server_type; /* Type of server to connect. + * Possible values any, primary. */ + /* Optional file to write trace info to */ FILE *Pfdebug;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-21 01:33  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-21 01:33 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: Mithun Cy [mailto:mithun.cy@enterprisedb.com]
> > +       {"target_server_type", "PGTARGETSERVERTYPE",
> DefaultTargetServerType, NULL,
> > +               "Target-Server-Type", "", 6,
> 
> Thanks fixed.

+	{"target_server_type", "PGTARGETSERVERTYPE", NULL, NULL,

The default value field is still NULL.


> > Please avoid adding another round trip by using a GUC_REPORTed variable
> (ParameterStatus entry).  If you want to support this libpq failover with
> >pre-10 servers, you can switch the method of determining the primary based
> on the server version.  But I don't think it's worth supporting older
> servers > at the price of libpq code complexity.
> 
> Currently there is no consensus around this. For now, making this patch
> to address failover to next primary as similar to JDBC seems sufficient
> for me.
> On next proposal of patch I think we can try to extend as you have proposed

I don't think show transaction is correct, because it's affected by default_transaction_read_only and ALTER DATABASE/USER SET transaction_read_only.  transaction_read_only is a transaction attribute, not the server type.  What we want to use to determine the connection target should be not only whether the transaction is read only, but also other attributes such as whether temporary tables can be used (only standby), maintenance commands can be executed (VACUUM and ANALYZE can run when transaction_read_only is on, but not on standby), etc.  And how about other DBMSs?  Do we really want to determine the target based on transaction_read_only while e.g. Oracle is based on primary/standby?

If you really want the transaction_read_only attribute for your application, then your app should execute "SET default_transaction_read_only = on" upon connection, or ALTER DATABASE/USER SET default_transaction_read_only = on in advance.


Regards
Takayuki Tsunakawa






-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-21 01:48  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-21 01:48 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Craig Ringer <craig@2ndquadrant.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> On Thu, Nov 17, 2016 at 10:08 PM, Craig Ringer <craig@2ndquadrant.com>
> wrote:
> > We can and probably should have both.
> >
> > If the server tells us on connect whether it's a standby or not, use that.
> >
> > Otherwise, ask it.
> >
> > That way we don't pay the round-trip cost and get the log spam when
> > talking to newer servers that send us something useful in the startup
> > packet, but we can still query it on older servers. Graceful fallback.
> >
> > Every round trip is potentially very expensive. Having libpq do them
> > unnecessarily is bad.
> 
> True, but raising the bar for this feature so that it doesn't get done is
> also bad.  It can be improved in a later patch.

I thought you are very strict about performance, so I hesitate to believe you forgive the additional round trip.  libpq failover is a new feature in v10, so I think it should provide the best user experience for v10 client+server users from the start.  If the concern is the time for development, then support for older releases can be added in a later patch.

There are still several months left for v10.  Why don't we try the best?  Could you share the difficulty?


Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-21 18:43  Robert Haas <robertmhaas@gmail.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-11-21 18:43 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Craig Ringer <craig@2ndquadrant.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Sun, Nov 20, 2016 at 8:48 PM, Tsunakawa, Takayuki
<tsunakawa.takay@jp.fujitsu.com> wrote:
>> True, but raising the bar for this feature so that it doesn't get done is
>> also bad.  It can be improved in a later patch.
>
> I thought you are very strict about performance, so I hesitate to believe you forgive the additional round trip.  libpq failover is a new feature in v10, so I think it should provide the best user experience for v10 client+server users from the start.  If the concern is the time for development, then support for older releases can be added in a later patch.
>
> There are still several months left for v10.  Why don't we try the best?  Could you share the difficulty?

I am very strict about regressing the performance of things that we
already have, but I try not to make a policy that a new feature must
be as fast as it could ever be.  That could result in us having very
few new features.  Of course, it also matters how frequently the
overhead is likely to be incurred.  A little overhead on each tuple
visibility check is a much bigger problem than a little overhead on
each CREATE TABLE statement, which in turn is a much bigger problem
than a little overhead on each connection attempt.  For good
performance, connections must last a while, so a little extra time
setting one up doesn't seem like a showstopper to me.  Anyway, anybody
who finds this mechanism too expensive doesn't have to use it; they
can implement something else instead.

Also, I am not saying that we should not change this in time for v10.
I'm saying that I don't think it should be a requirement for the next
patch to be committed in this area to introduce a whole new mechanism
for determining whether something is a master or a standby.  Love it
or hate it, pgsql-jdbc has already implemented something in this area
and it does something useful -- without requiring a wire protocol
change.  Now you and Kevin are trying to say that what they did is all
wrong, but I don't agree.  There are very many users for whom the
pgsql-jdbc approach will do exactly what they need, and no doubt some
for whom it won't.  Getting a patch that mimics that approach
committed is *progress*.  Improving it afterwards, whether for v10 or
some later release, is also good.

There is a saying that one should not let the perfect be the enemy of
the good.  I believe that saying applies here.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-22 07:38  Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Tsunakawa, Takayuki @ 2016-11-22 07:38 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Craig Ringer <craig@2ndquadrant.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

From: pgsql-hackers-owner@postgresql.org
> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
> I am very strict about regressing the performance of things that we already
> have, but I try not to make a policy that a new feature must be as fast
> as it could ever be.  That could result in us having very few new features.

I see.  I like your attitude toward new features.  But I don't think now is the time to compromise this feature and rush to the commit.


> Also, I am not saying that we should not change this in time for v10.
> I'm saying that I don't think it should be a requirement for the next patch
> to be committed in this area to introduce a whole new mechanism for
> determining whether something is a master or a standby.  Love it or hate
> it, pgsql-jdbc has already implemented something in this area and it does
> something useful -- without requiring a wire protocol change.  Now you and
> Kevin are trying to say that what they did is all wrong, but I don't agree.
> There are very many users for whom the pgsql-jdbc approach will do exactly
> what they need, and no doubt some for whom it won't.  Getting a patch that
> mimics that approach committed is *progress*.  Improving it afterwards,
> whether for v10 or some later release, is also good.

transaction_read_only=on does not mean the standby.  As the manual article on hot standby says, they are different.

https://www.postgresql.org/docs/devel/static/hot-standby.html

[Excerpt]
--------------------------------------------------
In normal operation, “read-only” transactions are allowed to update sequences and to use LISTEN, UNLISTEN, and NOTIFY, so Hot Standby sessions operate under slightly tighter restrictions than ordinary read-only sessions. It is possible that some of these restrictions might be loosened in a future release.
...
Users will be able to tell whether their session is read-only by issuing SHOW transaction_read_only. In addition, a set of functions (Table 9.79, “Recovery Information Functions”) allow users to access information about the standby server. These allow you to write programs that are aware of the current state of the database. These can be used to monitor the progress of recovery, or to allow you to write complex programs that restore the database to particular states.
--------------------------------------------------


I'm afraid that if the current patch is committed, you will lose interest in the ideal solution.  Then if the current patch is out as v10, there would be a concern about incompatibility when we pursue the ideal solution in a later release.  That is, "should we continue to report that this server is standby even if it's actually a primary with transaction_read_only is on, to maintain compatibility with the older release."

If you want to connect to a server where the transaction is read-only, then shouldn't the connection parameter be something like "target_session_attrs=readonly"?  That represents exactly what the code does.


> There is a saying that one should not let the perfect be the enemy of the
> good.  I believe that saying applies here.

True, so I suggested not including the support for older servers for a while.  Shall we find the real enemy -- what's preventing the ideal solution?  I know my knowledge is still far less than you, so I may be missing something difficult.  So, I'd like Mithun to share the difficulty.

Regards
Takayuki Tsunakawa



-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers


^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-22 07:51  Craig Ringer <craig@2ndquadrant.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Craig Ringer @ 2016-11-22 07:51 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>; Petr Jelinek <petr.jelinek@2ndquadrant.com>

On 21 November 2016 at 00:08, Mithun Cy <mithun.cy@enterprisedb.com> wrote:

>> Please avoid adding another round trip by using a GUC_REPORTed variable
>> (ParameterStatus entry).  If you want to support this libpq failover with
>> >pre-10 servers, you can switch the method of determining the primary based
>> on the server version.  But I don't think it's worth supporting older
>> servers > at the price of libpq code complexity.
>
> Currently there is no consensus around this. For now, making this patch to
> address failover to next primary as similar to JDBC seems sufficient for me.
> On next proposal of patch I think we can try to extend as you have proposed

FWIW, I agree. Working first, then improved.

>> I haven't tracked the progress of logical replication, but will
>> target_server_type be likely to be usable with it?  How will
>> target_server_type fit logical       > replication?
>
> I tried to check logical replication WIP patch, not very sure how to
> accomodate same.

Logical replication downstreams won't force transactions to read-only.
A significant part of the appeal of logical replication is that you
can use temp tables and unlogged tables on the downstream, and even
use persistent tables so long as they don't clash with the upstream.
More sophisticated models even allow the downstream to safely write to
replicated tables by doing conflict resolution.

So as it stands, this patch would consider any logical replication
downstream a 'master'.

That's fine for now IMO. Determining whether a server is a logical
replica isn't that simple, nor is it a clear-cut yes/no answer, and I
think it's out of the scope of this patch to deal with it. Figure it
out once logical replication lands.

-- 
 Craig Ringer                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-22 12:10  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Craig Ringer <craig@2ndquadrant.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-22 12:10 UTC (permalink / raw)
  To: Craig Ringer <craig@2ndquadrant.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Robert Haas <robertmhaas@gmail.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>; Petr Jelinek <petr.jelinek@2ndquadrant.com>

An updated patch with some fixes for bugs reported earlier,

A. failover_to_new_master_v4.patch
Default value "any" is added to target_server_type parameter during its
definition.

B. libpq-failover-smallbugs_02.patch
Fixed the issue raised by [PATCH] pgpassfile connection option
<https://www.postgresql.org/message-id/alpine.DEB.2.20.1611200841560.4443%40lancre;,
Now added host and port name along with pgpass file error message when ever
authentication fails and added same to file libpq-failover-smallbugs.patch
(bugs reported and fixed by Tsunakawa). I did review of original bugs
reported and fixes it seems okay for me. I could not test GSS and SSPI
authentication as it appears they needed windows.

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments: download all (2 files, .tar.gz)

failover_to_new_master_v4.patch (application/octet-stream, 12.6K) download commit af3fc3a53b38bbd2ff1e13fd84ae06f3c9d4bbdc Author: mithun <mithun@localhost.localdomain> Date: Tue Nov 22 16:58:00 2016 +0530 Mithuns patch diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..385a931 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -811,7 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp -postgresql://host1:123,host2:456/somedb +postgresql://host1:123,host2:456/somedb?target_server_type=any&amp;application_name=myapp </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -1382,6 +1382,20 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-target-server-type" xreflabel="target_server_type"> + <term><literal>target_server_type</literal></term> + <listitem> + <para> + This parameter specifies what kind of server to connect. + Set this to <literal>primary</literal>, to connect only to primary + server. Set this to <literal>any</literal>, if you want to connect to + any of the given host. And, the default is <literal>any</literal>. + A server is recognized as a primary/standby by observering whether it + allows write for this connection. Internally we identify same based on + the output of <literal>show transaction_read_only</literal>. + </para> + </listitem> + </varlistentry> </variablelist> </para> </sect2> @@ -7065,6 +7079,16 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-client-encoding"> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGTARGETSERVERTYPE</envar></primary> + </indexterm> + <envar>PGTARGETSERVERTYPE</envar> behaves the same as the <xref + linkend="libpq-connect-target-server-type"> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..fd52421 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -108,6 +108,7 @@ static int ldapServiceLookup(const char *purl, PQconninfoOption *options, #define DefaultOption "" #define DefaultAuthtype "" #define DefaultPassword "" +#define DefaultTargetServerType "any" #ifdef USE_SSL #define DefaultSSLMode "prefer" #else @@ -300,6 +301,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"target_server_type", "PGTARGETSERVERTYPE", DefaultTargetServerType, NULL, + "Target-Server-Type", "", 8, /* sizeof("primary") = 8 */ + offsetof(struct pg_conn, target_server_type)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +341,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void release_all_addrinfo(PGconn *conn); +static void sendTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -1026,6 +1033,24 @@ connectOptions2(PGconn *conn) } /* + * Validate target_server_mode option. + */ + if (conn->target_server_type) + { + if (strcmp(conn->target_server_type, "any") != 0 + && strcmp(conn->target_server_type, "primary") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_server_type value:" + " \"%s\" should be \"any\" or " + "\"primary\"\n"), + conn->target_server_type); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1814,6 +1839,7 @@ PQconnectPoll(PGconn *conn) /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: + case CONNECTION_CHECK_PRIMARY: break; default: @@ -2752,27 +2778,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address lists now. */ - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; - -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2782,7 +2787,25 @@ keep_going: /* We will come back to here until there is return PGRES_POLLING_WRITING; } - /* Otherwise, we are open for business! */ + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } @@ -2814,10 +2837,112 @@ keep_going: /* We will come back to here until there is goto error_return; } + /* + * If asked to connect to a primary then check if connected + * one is so. + */ + if (conn->target_server_type != NULL && + strcmp(conn->target_server_type, "primary") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; + case CONNECTION_CHECK_PRIMARY: + { + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + goto error_return; + + if (PQisBusy(conn)) + { + conn->status = CONNECTION_CHECK_PRIMARY; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) && + PQntuples(res) == 1) + { + char *val; + val = PQgetvalue(res, 0 , 0); + if (strncmp(val, "on", 2) == 0) + { + PQclear(res); + + /* + * This is a hot standby server terminate this connection + * and try next address. + */ + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("Connection failed, " + "%s:%s is a hot standby.\n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + PQclear(res); + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Something went wrong with + * "SELECT pg_catalog.pg_is_in_recovery()". We should try next + * addresses. + */ + if (res) + PQclear(res); + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("test to check if, %s:%s is a \"primary\" " + "failed \n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " @@ -3109,6 +3234,8 @@ freePGconn(PGconn *conn) free(conn->outBuffer); if (conn->rowBuf) free(conn->rowBuf); + if (conn->target_server_type) + free(conn->target_server_type); termPQExpBuffer(&conn->errorMessage); termPQExpBuffer(&conn->workBuffer); @@ -3120,19 +3247,41 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * release_all_addrinfo + * - free addrinfo of all hostconn elements. */ + static void -closePGconn(PGconn *conn) +release_all_addrinfo(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } + conn->addr_cur = NULL; +} +/* + * sendTerminateConn + * - Send a terminate message to backend. + */ +static void +sendTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -3147,6 +3296,23 @@ closePGconn(PGconn *conn) pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + sendTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -3165,25 +3331,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; + release_all_addrinfo(conn); -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) { diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..f39a110 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,8 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_PRIMARY /* Check if it is connected to PRIMARY. */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 854ec89..710f3ab 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,9 @@ struct pg_conn char *krbsrvname; /* Kerberos service name */ #endif + char *target_server_type; /* Type of server to connect. + * Possible values any, primary. */ + /* Optional file to write trace info to */ FILE *Pfdebug;
libpq-failover-smallbugs_02.patch (application/octet-stream, 6.6K) download diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index d04dba7..3814c57 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -867,6 +867,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname is equivalent to a connection string of the form <literal>host=host1,host2,host3 port=port1,port2,port3</literal>. Each host will be tried in turn until a connection is successfully established. + If failure is due to authentication issue, we return error immediately no + more hosts will be tried. </para> </sect3> </sect2> @@ -1009,6 +1011,9 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname Maximum wait for connection, in seconds (write as a decimal integer string). Zero or not specified means wait indefinitely. It is not recommended to use a timeout of less than 2 seconds. + This timeout is applied to a connection attempt with each host. + For example, if you specify two hosts and both of them are unreachable, + and connect_timeout is 5, the total timeout is 10 seconds. </para> </listitem> </varlistentry> diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 19171fb..d861dc4 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -170,8 +170,9 @@ pg_GSS_startup(PGconn *conn) min_stat; int maxlen; gss_buffer_desc temp_gbuf; + char *host = PQhost(conn); - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified\n")); @@ -198,7 +199,7 @@ pg_GSS_startup(PGconn *conn) return STATUS_ERROR; } snprintf(temp_gbuf.value, maxlen, "%s@%s", - conn->krbsrvname, conn->pghost); + conn->krbsrvname, host); temp_gbuf.length = strlen(temp_gbuf.value); maj_stat = gss_import_name(&min_stat, &temp_gbuf, @@ -371,6 +372,7 @@ pg_SSPI_startup(PGconn *conn, int use_negotiate) { SECURITY_STATUS r; TimeStamp expire; + char *host = PQhost(conn); conn->sspictx = NULL; @@ -406,19 +408,19 @@ pg_SSPI_startup(PGconn *conn, int use_negotiate) * but not more complex. We can skip the @REALM part, because Windows will * fill that in for us automatically. */ - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified\n")); return STATUS_ERROR; } - conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(conn->pghost) + 2); + conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(host) + 2); if (!conn->sspitarget) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); return STATUS_ERROR; } - sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, conn->pghost); + sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, host); /* * Indicate that we're in SSPI authentication mode to make sure that diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index b4f9ad7..52fb4cf 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -4931,7 +4931,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { int prefix_len; char *p; - char *buf; + char *buf = NULL; char *start; char prevchar = '\0'; char *user = NULL; @@ -4946,7 +4946,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n")); - return false; + goto cleanup; } /* need a modifiable copy of the input URI */ @@ -4955,7 +4955,7 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, { printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n")); - return false; + goto cleanup; } start = buf; @@ -5156,7 +5156,8 @@ conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, cleanup: termPQExpBuffer(&hostbuf); termPQExpBuffer(&portbuf); - free(buf); + if (buf) + free(buf); return retval; } @@ -6104,8 +6105,10 @@ dot_pg_pass_warning(PGconn *conn) if (!getPgPassFilename(pgpassfile)) return; appendPQExpBuffer(&conn->errorMessage, - libpq_gettext("password retrieved from file \"%s\"\n"), - pgpassfile); + libpq_gettext("password retrieved from file \"%s\" " + "for host \"%s:%s\"\n"), pgpassfile, + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); } } diff --git a/src/interfaces/libpq/fe-secure-openssl.c b/src/interfaces/libpq/fe-secure-openssl.c index f474c96..7bdf927 100644 --- a/src/interfaces/libpq/fe-secure-openssl.c +++ b/src/interfaces/libpq/fe-secure-openssl.c @@ -483,6 +483,7 @@ verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, char *name; const unsigned char *namedata; int result; + char *host = PQhost(conn); *store_name = NULL; @@ -528,12 +529,12 @@ verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, return -1; } - if (pg_strcasecmp(name, conn->pghost) == 0) + if (pg_strcasecmp(name, host) == 0) { /* Exact name match */ result = 1; } - else if (wildcard_certificate_match(name, conn->pghost)) + else if (wildcard_certificate_match(name, host)) { /* Matched wildcard name */ result = 1; @@ -563,6 +564,7 @@ verify_peer_name_matches_certificate(PGconn *conn) STACK_OF(GENERAL_NAME) *peer_san; int i; int rc; + char *host = PQhost(conn); /* * If told not to verify the peer name, don't do it. Return true @@ -572,7 +574,7 @@ verify_peer_name_matches_certificate(PGconn *conn) return true; /* Check that we have a hostname to compare with. */ - if (!(conn->pghost && conn->pghost[0] != '\0')) + if (!(host && host[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified for a verified SSL connection\n")); @@ -670,13 +672,13 @@ verify_peer_name_matches_certificate(PGconn *conn) libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n", "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n", names_examined - 1), - first_name, names_examined - 1, conn->pghost); + first_name, names_examined - 1, host); } else if (names_examined == 1) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"), - first_name, conn->pghost); + first_name, host); } else {
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-22 20:52  Robert Haas <robertmhaas@gmail.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-22 20:52 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Sun, Nov 13, 2016 at 9:02 PM, Tsunakawa, Takayuki
<tsunakawa.takay@jp.fujitsu.com> wrote:
> From: pgsql-hackers-owner@postgresql.org
>> [mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Robert Haas
>> Great, committed.  There's still potentially more work to be done here,
>> because my patch omits some features that were present in Victor's original
>> submission, like setting the failover timeout, optionally randomizing the
>> order of the hosts, and distinguishing between master and standby servers;
>> Victor, or anyone, please feel free to submit separate patches for those
>> things.
>
> The attached patch fixes some bugs and make a clarification for doc.  Could you check and test the authentication stuff as I don't have an environment at hand?

I don't have an environment at hand, either, but I think your fixes
are correct, so I have committed them.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-23 16:49  Catalin Iacob <iacobcatalin@gmail.com>
  parent: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Catalin Iacob @ 2016-11-23 16:49 UTC (permalink / raw)
  To: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Craig Ringer <craig@2ndquadrant.com>; Mithun Cy <mithun.cy@enterprisedb.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 22, 2016 at 8:38 AM, Tsunakawa, Takayuki
<tsunakawa.takay@jp.fujitsu.com> wrote:
> transaction_read_only=on does not mean the standby.  As the manual article on hot standby says, they are different.

> I'm afraid that if the current patch is committed, you will lose interest in the ideal solution.

I agree with Robert that lacking the ideal solution shouldn't block a
good enough solution today. But I find the current patch as it stands
too confusing to pass the "good enough" bar.

> Then if the current patch is out as v10, there would be a concern about incompatibility when we pursue the ideal solution in a later release.  That is, "should we continue to report > that this server is standby even if it's actually a primary with transaction_read_only is on, to maintain compatibility with the older release."

Agreed. I am worried that this will end up being a wart:
target_server_type=primary doesn't really mean primary it means that
by default the session is not read only which by the way is usually
the case for primaries but that can be changed.

> If you want to connect to a server where the transaction is read-only, then shouldn't the connection parameter be something like "target_session_attrs=readonly"?  That represents exactly what the code does.

FWIW I find this to be a reasonable compromise. To keep the analogy
with the current patch it would be more something like
"target_session_attrs=read_write|any" and the docs could point out "by
the way, if you didn't tweak default_transaction_read_only read_write
will only pick a primary so this can be used for failover".
The functionality is the same but changing the name removes the
ambiguity in the semantics and leaves the door open for a future real
primary/replica functionality which includes logical replication with
whatever semantics are deemed appropriate then.

We do lose pgjdbc compatibility but the current patch doesn't have
that 100% anyway: in pgjdbc it's called targetServerType and it
accepts master instead of primary and it also accepts slave and
preferSlave
I notice at https://github.com/pgjdbc/www/blob/master/documentation/head/connect.md
that pgjdbc says "The master/slave distinction is currently done by
observing if the server allows writes" which, due to the "currently"
part seems to acknowledge this is not ideal and leaves the door open
for changes in semantics but I don't think changing semantics is going
to fly for Postgres itself.


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-24 12:16  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Catalin Iacob <iacobcatalin@gmail.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-11-24 12:16 UTC (permalink / raw)
  To: Catalin Iacob <iacobcatalin@gmail.com>; +Cc: Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Robert Haas <robertmhaas@gmail.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 23, 2016 at 10:19 PM, Catalin Iacob <iacobcatalin@gmail.com>
wrote:
   On Tue, Nov 22, 2016 at 8:38 AM, Tsunakawa, Takayuki <
tsunakawa.takay@jp.fujitsu.com> wrote:
 >> If you want to connect to a server where the transaction is read-only,
then shouldn't the connection parameter be something like
 >>"target_session_attrs=readonly"?  That represents exactly what the code
does.

 >FWIW I find this to be a reasonable compromise. To keep the analogy
 >with the current patch it would be more something like
"target_session_attrs=read_write|any".

I have taken this suggestion now renamed target_server_type to
target_session_attrs with possible 2 values "read-write", "any".
May be we could expand to "readonly" and "prefer-readonly" in next patch
proposal. Attaching the patch for same.
-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover-to-new-writable-session-05.patch (application/octet-stream, 12.4K) download commit f86776463383cec57784b4ca54da6bcd15ceca67 Author: mithun <mithun@localhost.localdomain> Date: Thu Nov 24 17:28:41 2016 +0530 Failover-to-next-writable-connection-05 diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 0f375bf..99a0173 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -811,7 +811,7 @@ postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp -postgresql://host1:123,host2:456/somedb +postgresql://host1:123,host2:456/somedb?target_session_attrs=any&amp;application_name=myapp </programlisting> Components of the hierarchical part of the <acronym>URI</acronym> can also be given as parameters. For example: @@ -1386,6 +1386,16 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-target-session-attrs" xreflabel="target_session_attrs"> + <term><literal>target_session_attrs</literal></term> + <listitem> + <para> + This parameter specifies what kind of connection is requested. Set to + <literal>read-write</literal>, to make a writable connection. Else set + to <literal>any</literal>. And, the default is <literal>any</literal>. + </para> + </listitem> + </varlistentry> </variablelist> </para> </sect2> @@ -7069,6 +7079,16 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-client-encoding"> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGTARGETSESSIONATTRS</envar></primary> + </indexterm> + <envar>PGTARGETSESSIONATTRS</envar> behaves the same as the <xref + linkend="libpq-connect-target-session-attrs"> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 3e9c45b..0a0df8d 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -108,6 +108,7 @@ static int ldapServiceLookup(const char *purl, PQconninfoOption *options, #define DefaultOption "" #define DefaultAuthtype "" #define DefaultPassword "" +#define DefaultTargetSessionAttrs "any" #ifdef USE_SSL #define DefaultSSLMode "prefer" #else @@ -300,6 +301,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Replication", "D", 5, offsetof(struct pg_conn, replication)}, + {"target_session_attrs", "PGTARGETSESSIONATTRS", DefaultTargetSessionAttrs, NULL, + "Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */ + offsetof(struct pg_conn, target_session_attrs)}, + /* Terminating entry --- MUST BE LAST */ {NULL, NULL, NULL, NULL, NULL, NULL, 0} @@ -336,6 +341,8 @@ static PGconn *makeEmptyPGconn(void); static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions); static void freePGconn(PGconn *conn); static void closePGconn(PGconn *conn); +static void release_all_addrinfo(PGconn *conn); +static void sendTerminateConn(PGconn *conn); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults); @@ -1026,6 +1033,24 @@ connectOptions2(PGconn *conn) } /* + * Validate target_session_attrs option. + */ + if (conn->target_session_attrs) + { + if (strcmp(conn->target_session_attrs, "any") != 0 + && strcmp(conn->target_session_attrs, "read-write") != 0) + { + conn->status = CONNECTION_BAD; + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("invalid target_session_attrs " + "value:\"%s\" should be \"any\" or " + "\"read-write\"\n"), + conn->target_session_attrs); + return false; + } + } + + /* * Only if we get this far is it appropriate to try to connect. (We need a * state flag, rather than just the boolean result of this function, in * case someone tries to PQreset() the PGconn.) @@ -1814,6 +1839,7 @@ PQconnectPoll(PGconn *conn) /* Special cases: proceed without waiting. */ case CONNECTION_SSL_STARTUP: case CONNECTION_NEEDED: + case CONNECTION_CHECK_WRITABLE: break; default: @@ -2752,27 +2778,6 @@ keep_going: /* We will come back to here until there is goto error_return; } - /* We can release the address lists now. */ - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; - -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; - /* Fire up post-connection housekeeping if needed */ if (PG_PROTOCOL_MAJOR(conn->pversion) < 3) { @@ -2782,7 +2787,24 @@ keep_going: /* We will come back to here until there is return PGRES_POLLING_WRITING; } - /* Otherwise, we are open for business! */ + /* + * If a read-write connection is requisted check for same. + */ + if (conn->target_session_attrs != NULL && + strcmp(conn->target_session_attrs, "read-write") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_WRITABLE; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; } @@ -2814,10 +2836,111 @@ keep_going: /* We will come back to here until there is goto error_return; } + /* + * If a read-write connection is requisted check for same. + */ + if (conn->target_session_attrs != NULL && + strcmp(conn->target_session_attrs, "read-write") == 0) + { + conn->status = CONNECTION_OK; + if (!PQsendQuery(conn, + "show transaction_read_only")) + goto error_return; + conn->status = CONNECTION_CHECK_WRITABLE; + return PGRES_POLLING_READING; + } + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + /* We are open for business! */ conn->status = CONNECTION_OK; return PGRES_POLLING_OK; + case CONNECTION_CHECK_WRITABLE: + { + conn->status = CONNECTION_OK; + if (!PQconsumeInput(conn)) + goto error_return; + + if (PQisBusy(conn)) + { + conn->status = CONNECTION_CHECK_WRITABLE; + return PGRES_POLLING_READING; + } + + res = PQgetResult(conn); + if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) && + PQntuples(res) == 1) + { + char *val; + val = PQgetvalue(res, 0 , 0); + if (strncmp(val, "on", 2) == 0) + { + PQclear(res); + + /* + * This is not a writable connection lets try next + * address. + */ + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not make a writable " + "connection to server " + "\"%s:%s\"\n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + PQclear(res); + + /* We can release the address lists now. */ + release_all_addrinfo(conn); + + /* We are open for business! */ + conn->status = CONNECTION_OK; + return PGRES_POLLING_OK; + } + + /* + * Something went wrong with + * "show transaction_read_only". We should try next addresses. + */ + if (res) + PQclear(res); + appendPQExpBuffer(&conn->errorMessage, + libpq_gettext("test \"show transaction_read_only\" failed " + " on \"%s:%s\" \n"), + conn->connhost[conn->whichhost].host, + conn->connhost[conn->whichhost].port); + conn->status = CONNECTION_OK; + sendTerminateConn(conn); + pqDropConnection(conn, true); + + if (conn->addr_cur->ai_next != NULL || + conn->whichhost + 1 < conn->nconnhost) + { + conn->addr_cur = conn->addr_cur->ai_next; + conn->status = CONNECTION_NEEDED; + goto keep_going; + } + + /* No more addresses to try. So we fail. */ + goto error_return; + } + default: appendPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid connection state %d, " @@ -3109,6 +3232,8 @@ freePGconn(PGconn *conn) free(conn->outBuffer); if (conn->rowBuf) free(conn->rowBuf); + if (conn->target_session_attrs) + free(conn->target_session_attrs); termPQExpBuffer(&conn->errorMessage); termPQExpBuffer(&conn->workBuffer); @@ -3120,19 +3245,41 @@ freePGconn(PGconn *conn) } /* - * closePGconn - * - properly close a connection to the backend - * - * This should reset or release all transient state, but NOT the connection - * parameters. On exit, the PGconn should be in condition to start a fresh - * connection with the same parameters (see PQreset()). + * release_all_addrinfo + * - free addrinfo of all hostconn elements. */ + static void -closePGconn(PGconn *conn) +release_all_addrinfo(PGconn *conn) { - PGnotify *notify; - pgParameterStatus *pstatus; + if (conn->connhost != NULL) + { + int i; + + for (i = 0; i < conn->nconnhost; ++i) + { + int family = AF_UNSPEC; + +#ifdef HAVE_UNIX_SOCKETS + if (conn->connhost[i].type == CHT_UNIX_SOCKET) + family = AF_UNIX; +#endif + + pg_freeaddrinfo_all(family, + conn->connhost[i].addrlist); + conn->connhost[i].addrlist = NULL; + } + } + conn->addr_cur = NULL; +} +/* + * sendTerminateConn + * - Send a terminate message to backend. + */ +static void +sendTerminateConn(PGconn *conn) +{ /* * Note that the protocol doesn't allow us to send Terminate messages * during the startup phase. @@ -3147,6 +3294,23 @@ closePGconn(PGconn *conn) pqPutMsgEnd(conn); (void) pqFlush(conn); } +} + +/* + * closePGconn + * - properly close a connection to the backend + * + * This should reset or release all transient state, but NOT the connection + * parameters. On exit, the PGconn should be in condition to start a fresh + * connection with the same parameters (see PQreset()). + */ +static void +closePGconn(PGconn *conn) +{ + PGnotify *notify; + pgParameterStatus *pstatus; + + sendTerminateConn(conn); /* * Must reset the blocking status so a possible reconnect will work. @@ -3165,25 +3329,8 @@ closePGconn(PGconn *conn) conn->asyncStatus = PGASYNC_IDLE; pqClearAsyncResult(conn); /* deallocate result */ resetPQExpBuffer(&conn->errorMessage); - if (conn->connhost != NULL) - { - int i; - - for (i = 0; i < conn->nconnhost; ++i) - { - int family = AF_UNSPEC; + release_all_addrinfo(conn); -#ifdef HAVE_UNIX_SOCKETS - if (conn->connhost[i].type == CHT_UNIX_SOCKET) - family = AF_UNIX; -#endif - - pg_freeaddrinfo_all(family, - conn->connhost[i].addrlist); - conn->connhost[i].addrlist = NULL; - } - } - conn->addr_cur = NULL; notify = conn->notifyHead; while (notify != NULL) { diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 9ca0756..20b7e57 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -62,7 +62,9 @@ typedef enum * backend startup. */ CONNECTION_SETENV, /* Negotiating environment. */ CONNECTION_SSL_STARTUP, /* Negotiating SSL. */ - CONNECTION_NEEDED /* Internal state: connect() needed */ + CONNECTION_NEEDED, /* Internal state: connect() needed */ + CONNECTION_CHECK_WRITABLE /* Check if we could make a writable + * connection. */ } ConnStatusType; typedef enum diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 854ec89..a2f8589 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,9 @@ struct pg_conn char *krbsrvname; /* Kerberos service name */ #endif + char *target_session_attrs; /* Type of connection to make + * Possible values any, read-write. */ + /* Optional file to write trace info to */ FILE *Pfdebug;
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-29 17:37  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-29 17:37 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 24, 2016 at 7:16 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Wed, Nov 23, 2016 at 10:19 PM, Catalin Iacob <iacobcatalin@gmail.com>
> wrote:
>    On Tue, Nov 22, 2016 at 8:38 AM, Tsunakawa, Takayuki
> <tsunakawa.takay@jp.fujitsu.com> wrote:
>  >> If you want to connect to a server where the transaction is read-only,
> then shouldn't the connection parameter be something like
>>>"target_session_attrs=readonly"?  That represents exactly what the code
> does.
>
>  >FWIW I find this to be a reasonable compromise. To keep the analogy
>  >with the current patch it would be more something like
> "target_session_attrs=read_write|any".
>
> I have taken this suggestion now renamed target_server_type to
> target_session_attrs with possible 2 values "read-write", "any".

I didn't hear any objections to this approach and, after some thought,
I think it's good.  So I've committed this after rewriting the
documentation, some cosmetic cleanup, and changing the logic so that
if one IP for a host turns out to be read-only, we skip all remaining
IPs for that host, not just the one that we tested already.  This
seems likely to be what users will want.

I recognize that this isn't going to be please everybody 100%, but
there's still room for followup patches to improve things further.
One thing I really like about the target_session_attrs renaming is
that it seems to leave the door open to a variety of things we might
want to do later.  The "read-write" value we now support is closely
related to the query we use for testing ("show
transaction_read_only").  If we later want to filter based on some
other server property, we can add additional values with associated
SQL commands for each.  Of course that could get a little crazy if
overdone, but hopefully we won't overdo it.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-29 19:19  Kuntal Ghosh <kuntalghosh.2007@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Kuntal Ghosh @ 2016-11-29 19:19 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Robert Haas <robertmhaas@gmail.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Nov 24, 2016 at 5:46 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> I have taken this suggestion now renamed target_server_type to
> target_session_attrs with possible 2 values "read-write", "any".
> May be we could expand to "readonly" and "prefer-readonly" in next patch
> proposal. Attaching the patch for same.
I was doing some testing with the patch and I found some inconsistency
in the error message.
I've a read-only server running on port 5433 and no server on 5436 and 5438.

command: bin/psql
'postgresql://localhost:5436,localhost:5433,localhost:5438/postgres?target_session_attrs=read-write'

I get the following error message.

psql: could not make a writable connection to server "localhost:5433"
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5438?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5438?

It didn't show any error message for port 5436. But, if I modify the
connection string as following:

command: bin/psql
'postgresql://localhost:5433,localhost:5436,localhost:5438/postgres?target_session_attrs=read-write'

I get the following error message:

psql: could not make a writable connection to server "localhost:5433"
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5436?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5436?
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5438?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5438?

-- 
Thanks & Regards,
Kuntal Ghosh
EnterpriseDB: http://www.enterprisedb.com


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-29 20:14  Robert Haas <robertmhaas@gmail.com>
  parent: Kuntal Ghosh <kuntalghosh.2007@gmail.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-29 20:14 UTC (permalink / raw)
  To: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 29, 2016 at 2:19 PM, Kuntal Ghosh
<kuntalghosh.2007@gmail.com> wrote:
> On Thu, Nov 24, 2016 at 5:46 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>> I have taken this suggestion now renamed target_server_type to
>> target_session_attrs with possible 2 values "read-write", "any".
>> May be we could expand to "readonly" and "prefer-readonly" in next patch
>> proposal. Attaching the patch for same.
> I was doing some testing with the patch and I found some inconsistency
> in the error message.
> I've a read-only server running on port 5433 and no server on 5436 and 5438.
>
> command: bin/psql
> 'postgresql://localhost:5436,localhost:5433,localhost:5438/postgres?target_session_attrs=read-write'
>
> I get the following error message.
>
> psql: could not make a writable connection to server "localhost:5433"
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (::1) and accepting
>     TCP/IP connections on port 5438?
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (127.0.0.1) and accepting
>     TCP/IP connections on port 5438?
>
> It didn't show any error message for port 5436. But, if I modify the
> connection string as following:
>
> command: bin/psql
> 'postgresql://localhost:5433,localhost:5436,localhost:5438/postgres?target_session_attrs=read-write'
>
> I get the following error message:
>
> psql: could not make a writable connection to server "localhost:5433"
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (::1) and accepting
>     TCP/IP connections on port 5436?
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (127.0.0.1) and accepting
>     TCP/IP connections on port 5436?
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (::1) and accepting
>     TCP/IP connections on port 5438?
> could not connect to server: Connection refused
>     Is the server running on host "localhost" (127.0.0.1) and accepting
>     TCP/IP connections on port 5438?

Hmm, maybe the query buffer is getting cleared someplace in there.  We
might need to save/restore it.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-29 20:14  Robert Haas <robertmhaas@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-11-29 20:14 UTC (permalink / raw)
  To: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; +Cc: Mithun Cy <mithun.cy@enterprisedb.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Tue, Nov 29, 2016 at 3:14 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> On Tue, Nov 29, 2016 at 2:19 PM, Kuntal Ghosh
> <kuntalghosh.2007@gmail.com> wrote:
>> On Thu, Nov 24, 2016 at 5:46 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
>>> I have taken this suggestion now renamed target_server_type to
>>> target_session_attrs with possible 2 values "read-write", "any".
>>> May be we could expand to "readonly" and "prefer-readonly" in next patch
>>> proposal. Attaching the patch for same.
>> I was doing some testing with the patch and I found some inconsistency
>> in the error message.
>> I've a read-only server running on port 5433 and no server on 5436 and 5438.
>>
>> command: bin/psql
>> 'postgresql://localhost:5436,localhost:5433,localhost:5438/postgres?target_session_attrs=read-write'
>>
>> I get the following error message.
>>
>> psql: could not make a writable connection to server "localhost:5433"
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (::1) and accepting
>>     TCP/IP connections on port 5438?
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (127.0.0.1) and accepting
>>     TCP/IP connections on port 5438?
>>
>> It didn't show any error message for port 5436. But, if I modify the
>> connection string as following:
>>
>> command: bin/psql
>> 'postgresql://localhost:5433,localhost:5436,localhost:5438/postgres?target_session_attrs=read-write'
>>
>> I get the following error message:
>>
>> psql: could not make a writable connection to server "localhost:5433"
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (::1) and accepting
>>     TCP/IP connections on port 5436?
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (127.0.0.1) and accepting
>>     TCP/IP connections on port 5436?
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (::1) and accepting
>>     TCP/IP connections on port 5438?
>> could not connect to server: Connection refused
>>     Is the server running on host "localhost" (127.0.0.1) and accepting
>>     TCP/IP connections on port 5438?
>
> Hmm, maybe the query buffer is getting cleared someplace in there.  We
> might need to save/restore it.

Not the query buffer.  conn->errorMessage.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-11-30 01:44  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-11-30 01:44 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 30, 2016 at 1:44 AM, Robert Haas <robertmhaas@gmail.com> wrote:
 >On Tue, Nov 29, 2016 at 2:19 PM, Kuntal Ghosh <kuntalghosh.2007@gmail.com>
wrote:
 >> I was doing some testing with the patch and I found some inconsistency
 >> in the error message.

 > Hmm, maybe the query buffer is getting cleared someplace in there.  We
 > might need to save/restore it.

 Thanks, send query resets the errorMessage. Will fix same.

* PQsendQuery()->PQsendQueryStart()->resetPQExpBuffer(&conn->errorMessage);*

Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-01 10:00  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-12-01 10:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Wed, Nov 30, 2016 at 7:14 AM, Mithun Cy <mithun.cy@enterprisedb.com>
wrote:
> Thanks, send query resets the errorMessage. Will fix same.
>
*PQsendQuery()->PQsendQueryStart()->resetPQExpBuffer(&conn->errorMessage);*

*Please find the patch which fixes this bug. **conn->errorMessage as per
definition only stores current error message, a new member*
*conn->savedMessage is introduced to save and restore error messages
related to previous hosts which we failed to connect.*

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover-to-new-writable-session_bugfix_01.patch (application/octet-stream, 3.6K) download diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index cd96ddb..9139186 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -1662,6 +1662,7 @@ connectDBStart(PGconn *conn) conn->addr_cur = conn->connhost[0].addrlist; conn->pversion = PG_PROTOCOL(3, 0); conn->send_appname = true; + resetPQExpBuffer(&conn->savedMessage); conn->status = CONNECTION_NEEDED; /* @@ -1730,6 +1731,7 @@ connectDBComplete(PGconn *conn) * Reset stored error messages since we now have a working * connection */ + resetPQExpBuffer(&conn->savedMessage); resetPQExpBuffer(&conn->errorMessage); return 1; /* success! */ @@ -2792,6 +2794,18 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + /* + * We are yet to make a connection. Save all existing error + * messages until we make a successful connection state. + * This is important because PQsendQuery is going to reset + * conn->errorMessage and we will loose error messages + * related to previous hosts we have tried to connect and + * failed. + */ + appendPQExpBufferStr(&conn->savedMessage, + conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) @@ -2841,6 +2855,10 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + appendPQExpBufferStr(&conn->savedMessage, + conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) @@ -2950,6 +2968,12 @@ keep_going: /* We will come back to here until there is error_return: + /* Failed to connect, restore the errorMessage. */ + appendPQExpBufferStr(&conn->savedMessage, conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + appendPQExpBufferStr(&conn->errorMessage, conn->savedMessage.data); + resetPQExpBuffer(&conn->savedMessage); + dot_pg_pass_warning(conn); /* @@ -3106,12 +3130,14 @@ makeEmptyPGconn(void) conn->rowBufLen = 32; conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue)); initPQExpBuffer(&conn->errorMessage); + initPQExpBuffer(&conn->savedMessage); initPQExpBuffer(&conn->workBuffer); if (conn->inBuffer == NULL || conn->outBuffer == NULL || conn->rowBuf == NULL || PQExpBufferBroken(&conn->errorMessage) || + PQExpBufferBroken(&conn->savedMessage) || PQExpBufferBroken(&conn->workBuffer)) { /* out of memory already :-( */ @@ -3232,6 +3258,7 @@ freePGconn(PGconn *conn) if (conn->target_session_attrs) free(conn->target_session_attrs); termPQExpBuffer(&conn->errorMessage); + termPQExpBuffer(&conn->savedMessage); termPQExpBuffer(&conn->workBuffer); free(conn); diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index a2f8589..bab7a92 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -496,6 +496,9 @@ struct pg_conn /* Buffer for current error message */ PQExpBufferData errorMessage; /* expansible string */ + /* Saves previous error messages in case of multipple hosts. */ + PQExpBufferData savedMessage; /* expansible string */ + /* Buffer for receiving various parts of messages */ PQExpBufferData workBuffer; /* expansible string */ };
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-02 15:24  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-12-02 15:24 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Thu, Dec 1, 2016 at 5:00 AM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Wed, Nov 30, 2016 at 7:14 AM, Mithun Cy <mithun.cy@enterprisedb.com>
> wrote:
>> Thanks, send query resets the errorMessage. Will fix same.
>> PQsendQuery()->PQsendQueryStart()->resetPQExpBuffer(&conn->errorMessage);
>
> Please find the patch which fixes this bug. conn->errorMessage as per
> definition only stores current error message, a new member
> conn->savedMessage is introduced to save and restore error messages related
> to previous hosts which we failed to connect.

Couldn't this just be a variable in PQconnectPoll(), instead of adding
a new structure member?

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-05 04:00  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 2 replies; 165+ messages in thread

From: Mithun Cy @ 2016-12-05 04:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Fri, Dec 2, 2016 at 8:54 PM, Robert Haas <robertmhaas@gmail.com> wrote:
> Couldn't this just be a variable in PQconnectPoll(), instead of adding
> a new structure member?

I have fixed same with a local variable in PQconnectPoll, Initally I
thought savedMessage should have same visiblitly as errorMessage so we can
restore the errorMessage even outside PQconnectPoll. But that seems not
required. Attacting the new patch which fixes the same.

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover-to-new-master-bug-fix-02.patch (application/octet-stream, 4.6K) download commit de4994d4a74aa988cc981b47da20a911175a4502 Author: mithun <mithun@localhost.localdomain> Date: Sun Dec 4 12:53:05 2016 +0530 Fix Error messages reset for while PQquery diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index cd96ddb..c18b5a7 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -1762,6 +1762,39 @@ connectDBComplete(PGconn *conn) } } +/* + * This subroutine saves conn->errorMessage, which will be restored back by + * restoreErrorMessage subroutine. + */ +static inline bool +saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage) +{ + initPQExpBuffer(savedMessage); + if (PQExpBufferBroken(savedMessage)) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("out of memory\n")); + return false; + } + + appendPQExpBufferStr(savedMessage, + conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + return true; +} + +/* + * Restores saved error messages back to conn->errorMessage. + */ +static inline void +restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage) +{ + appendPQExpBufferStr(savedMessage, conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + appendPQExpBufferStr(&conn->errorMessage, savedMessage->data); + termPQExpBuffer(savedMessage); +} + /* ---------------- * PQconnectPoll * @@ -1795,6 +1828,7 @@ PQconnectPoll(PGconn *conn) PGresult *res; char sebuf[256]; int optval; + PQExpBufferData savedMessage; if (conn == NULL) return PGRES_POLLING_FAILED; @@ -1821,8 +1855,9 @@ PQconnectPoll(PGconn *conn) if (n < 0) goto error_return; if (n == 0) + { return PGRES_POLLING_READING; - + } break; } @@ -2792,11 +2827,26 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + /* + * We are yet to make a connection. Save all existing error + * messages until we make a successful connection state. + * This is important because PQsendQuery is going to reset + * conn->errorMessage and we will loose error messages + * related to previous hosts we have tried to connect and + * failed. + */ + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2841,11 +2891,18 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2858,13 +2915,20 @@ keep_going: /* We will come back to here until there is case CONNECTION_CHECK_WRITABLE: { + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQconsumeInput(conn)) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } if (PQisBusy(conn)) { conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2878,6 +2942,7 @@ keep_going: /* We will come back to here until there is if (strncmp(val, "on", 2) == 0) { PQclear(res); + restoreErrorMessage(conn, &savedMessage); /* Not writable; close connection. */ appendPQExpBuffer(&conn->errorMessage, @@ -2902,6 +2967,7 @@ keep_going: /* We will come back to here until there is goto error_return; } PQclear(res); + termPQExpBuffer(&savedMessage); /* We can release the address lists now. */ release_all_addrinfo(conn); @@ -2917,6 +2983,7 @@ keep_going: /* We will come back to here until there is */ if (res) PQclear(res); + restoreErrorMessage(conn, &savedMessage); appendPQExpBuffer(&conn->errorMessage, libpq_gettext("test \"show transaction_read_only\" failed " " on \"%s:%s\" \n"),
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-05 17:53  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 1 reply; 165+ messages in thread

From: Robert Haas @ 2016-12-05 17:53 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Sun, Dec 4, 2016 at 11:00 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Fri, Dec 2, 2016 at 8:54 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>> Couldn't this just be a variable in PQconnectPoll(), instead of adding
>> a new structure member?
>
> I have fixed same with a local variable in PQconnectPoll, Initally I thought
> savedMessage should have same visiblitly as errorMessage so we can restore
> the errorMessage even outside PQconnectPoll. But that seems not required.
> Attacting the new patch which fixes the same.

I think that you need a restoreErrorMessage call here:

                        /* Skip any remaining addresses for this host. */
                        conn->addr_cur = NULL;
                        if (conn->whichhost + 1 < conn->nconnhost)
                        {
                            conn->status = CONNECTION_NEEDED;
                            restoreErrorMessage(conn, &savedMessage);
                            goto keep_going;
                        }

Updated patch attached with that change, the removal of a useless
hunk, and the removal of "inline" from the new functions, which seems
like second-guessing of whatever decision the compiler chooses to
make.

Thoughts?

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments:

failover-to-new-master-bug-fix-03.patch (text/x-patch, 4.5K) download diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 3b9b263..24fc12d 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -1762,6 +1762,39 @@ connectDBComplete(PGconn *conn) } } +/* + * This subroutine saves conn->errorMessage, which will be restored back by + * restoreErrorMessage subroutine. + */ +static bool +saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage) +{ + initPQExpBuffer(savedMessage); + if (PQExpBufferBroken(savedMessage)) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("out of memory\n")); + return false; + } + + appendPQExpBufferStr(savedMessage, + conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + return true; +} + +/* + * Restores saved error messages back to conn->errorMessage. + */ +static void +restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage) +{ + appendPQExpBufferStr(savedMessage, conn->errorMessage.data); + resetPQExpBuffer(&conn->errorMessage); + appendPQExpBufferStr(&conn->errorMessage, savedMessage->data); + termPQExpBuffer(savedMessage); +} + /* ---------------- * PQconnectPoll * @@ -1795,6 +1828,7 @@ PQconnectPoll(PGconn *conn) PGresult *res; char sebuf[256]; int optval; + PQExpBufferData savedMessage; if (conn == NULL) return PGRES_POLLING_FAILED; @@ -2792,11 +2826,26 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + /* + * We are yet to make a connection. Save all existing error + * messages until we make a successful connection state. + * This is important because PQsendQuery is going to reset + * conn->errorMessage and we will loose error messages + * related to previous hosts we have tried to connect and + * failed. + */ + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2841,11 +2890,18 @@ keep_going: /* We will come back to here until there is if (conn->target_session_attrs != NULL && strcmp(conn->target_session_attrs, "read-write") == 0) { + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQsendQuery(conn, "show transaction_read_only")) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2858,13 +2914,20 @@ keep_going: /* We will come back to here until there is case CONNECTION_CHECK_WRITABLE: { + if (!saveErrorMessage(conn, &savedMessage)) + goto error_return; + conn->status = CONNECTION_OK; if (!PQconsumeInput(conn)) + { + restoreErrorMessage(conn, &savedMessage); goto error_return; + } if (PQisBusy(conn)) { conn->status = CONNECTION_CHECK_WRITABLE; + restoreErrorMessage(conn, &savedMessage); return PGRES_POLLING_READING; } @@ -2878,6 +2941,7 @@ keep_going: /* We will come back to here until there is if (strncmp(val, "on", 2) == 0) { PQclear(res); + restoreErrorMessage(conn, &savedMessage); /* Not writable; close connection. */ appendPQExpBuffer(&conn->errorMessage, @@ -2895,6 +2959,7 @@ keep_going: /* We will come back to here until there is if (conn->whichhost + 1 < conn->nconnhost) { conn->status = CONNECTION_NEEDED; + restoreErrorMessage(conn, &savedMessage); goto keep_going; } @@ -2902,6 +2967,7 @@ keep_going: /* We will come back to here until there is goto error_return; } PQclear(res); + termPQExpBuffer(&savedMessage); /* We can release the address lists now. */ release_all_addrinfo(conn); @@ -2917,6 +2983,7 @@ keep_going: /* We will come back to here until there is */ if (res) PQclear(res); + restoreErrorMessage(conn, &savedMessage); appendPQExpBuffer(&conn->errorMessage, libpq_gettext("test \"show transaction_read_only\" failed " " on \"%s:%s\" \n"),
^ permalink raw reply [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-05 17:57  Gavin Flower <GavinFlower@archidevsys.co.nz>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  1 sibling, 0 replies; 165+ messages in thread

From: Gavin Flower @ 2016-12-05 17:57 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; Robert Haas <robertmhaas@gmail.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On 05/12/16 17:00, Mithun Cy wrote:
[...]
> errorMessage even outside PQconnectPoll. But that seems not required. 
> Attacting the new patch which fixes the same.
>
> -- 
> Thanks and Regards
> Mithun C Y
> EnterpriseDB: http://www.enterprisedb.com <http://www.enterprisedb.com/;
[...]

Is that meant to be 'attaching' or 'attacking'???
<ducks, and runs away VERY quickly>


MORE SERIOUSLY
thanks for your and others efforts for making pg great!


Cheers,
Gavin


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-05 18:59  Mithun Cy <mithun.cy@enterprisedb.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 165+ messages in thread

From: Mithun Cy @ 2016-12-05 18:59 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Dec 5, 2016 at 11:23 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>I think that you need a restoreErrorMessage call here:
>                        /* Skip any remaining addresses for this host. */
>                        conn->addr_cur = NULL;
>                        if (conn->whichhost + 1 < conn->nconnhost)
>                        {
>                            conn->status = CONNECTION_NEEDED
>                            restoreErrorMessage(conn, &savedMessage);
>                            goto keep_going;
>                        }

Right after seeing transaction is read-only we have restored the saved
message so I think we do not need one more restore there.
  if (strncmp(val, "on", 2) == 0)
  {
  PQclear(res);
+ restoreErrorMessage(conn, &savedMessage);

-- 
Thanks and Regards
Mithun C Y
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 165+ messages in thread

* Re: Patch: Implement failover on libpq connect level.
@ 2016-12-05 19:12  Robert Haas <robertmhaas@gmail.com>
  parent: Mithun Cy <mithun.cy@enterprisedb.com>
  0 siblings, 0 replies; 165+ messages in thread

From: Robert Haas @ 2016-12-05 19:12 UTC (permalink / raw)
  To: Mithun Cy <mithun.cy@enterprisedb.com>; +Cc: Kuntal Ghosh <kuntalghosh.2007@gmail.com>; Catalin Iacob <iacobcatalin@gmail.com>; Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>; Craig Ringer <craig@2ndquadrant.com>; Peter van Hardenberg <pvh@pvh.ca>; Peter Eisentraut <peter_e@gmx.net>; pgsql-hackers@postgresql.org <pgsql-hackers@postgresql.org>

On Mon, Dec 5, 2016 at 1:59 PM, Mithun Cy <mithun.cy@enterprisedb.com> wrote:
> On Mon, Dec 5, 2016 at 11:23 PM, Robert Haas <robertmhaas@gmail.com> wrote:
>>I think that you need a restoreErrorMessage call here:
>>                        /* Skip any remaining addresses for this host. */
>>                        conn->addr_cur = NULL;
>>                        if (conn->whichhost + 1 < conn->nconnhost)
>>                        {
>>                            conn->status = CONNECTION_NEEDED
>>                            restoreErrorMessage(conn, &savedMessage);
>>                            goto keep_going;
>>                        }
>
> Right after seeing transaction is read-only we have restored the saved
> message so I think we do not need one more restore there.
>   if (strncmp(val, "on", 2) == 0)
>   {
>   PQclear(res);
> + restoreErrorMessage(conn, &savedMessage);

D'oh!  You're correct, of course.

Committed without that.

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers



^ permalink  raw  reply  [nested|flat] 165+ messages in thread


end of thread, other threads:[~2016-12-05 19:12 UTC | newest]

Thread overview: 165+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2015-10-14 10:41 Patch: Implement failover on libpq connect level. Victor Wagner <vitus@wagner.pp.ru>
2015-10-14 12:47 ` Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
2015-10-15 07:07   ` Victor Wagner <vitus@wagner.pp.ru>
2015-10-15 09:13 ` Craig Ringer <craig@2ndquadrant.com>
2015-10-15 09:43   ` Victor Wagner <vitus@wagner.pp.ru>
2015-10-26 20:25 ` Peter Eisentraut <peter_e@gmx.net>
2015-10-26 21:02   ` Christopher Browne <cbbrowne@gmail.com>
2015-10-27 08:42     ` Shulgin, Oleksandr <oleksandr.shulgin@zalando.de>
2015-10-27 17:35       ` Josh Berkus <josh@agliodbs.com>
2015-10-28 08:18   ` Victor Wagner <vitus@wagner.pp.ru>
2015-10-29 19:29     ` Peter Eisentraut <peter_e@gmx.net>
2015-10-30 13:26       ` Robert Haas <robertmhaas@gmail.com>
2015-10-30 14:09         ` Victor Wagner <vitus@wagner.pp.ru>
2015-10-30 15:29         ` Christopher Browne <cbbrowne@gmail.com>
2015-10-30 16:23           ` David Fetter <david@fetter.org>
2015-10-30 17:21           ` Josh Berkus <josh@agliodbs.com>
2015-11-02 17:15         ` Peter Eisentraut <peter_e@gmx.net>
2015-11-03 15:24           ` Robert Haas <robertmhaas@gmail.com>
2015-11-05 15:12           ` Victor Wagner <vitus@wagner.pp.ru>
2015-11-06 05:34             ` Robert Haas <robertmhaas@gmail.com>
2015-11-06 05:43               ` Craig Ringer <craig@2ndquadrant.com>
2015-11-06 15:38                 ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-11-06 20:59                   ` Robert Haas <robertmhaas@gmail.com>
2015-11-09 07:14                     ` Craig Ringer <craig@2ndquadrant.com>
2015-11-09 09:44                       ` Victor Wagner <vitus@wagner.pp.ru>
2015-12-07 20:26                         ` Korry Douglas <korry.douglas@enterprisedb.com>
2015-12-07 21:12                           ` Korry Douglas <korry.douglas@enterprisedb.com>
2015-12-10 04:54                           ` Victor Wagner <vitus@wagner.pp.ru>
2015-12-21 14:18                             ` Teodor Sigaev <teodor@sigaev.ru>
2015-12-21 14:50                               ` Victor Wagner <vitus@wagner.pp.ru>
2015-12-21 18:12                                 ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-12-22 06:16                                 ` Michael Paquier <michael.paquier@gmail.com>
2016-01-19 14:34                                 ` Thom Brown <thom@linux.com>
2016-01-21 09:49                                   ` Victor Wagner <vitus@wagner.pp.ru>
2016-01-22 19:30                                   ` Victor Wagner <vitus@wagner.pp.ru>
2016-01-22 19:36                                     ` Alvaro Herrera <alvherre@2ndquadrant.com>
2016-01-24 09:18                                       ` Victor Wagner <vitus@wagner.pp.ru>
2016-02-01 22:05                                         ` Alvaro Herrera <alvherre@2ndquadrant.com>
2016-03-09 23:11                                           ` David Steele <david@pgmasters.net>
2016-03-10 12:34                                             ` Simon Riggs <simon@2ndQuadrant.com>
2016-03-16 23:17                                               ` David Steele <david@pgmasters.net>
2016-08-26 04:40                                                 ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-08-26 04:47                                                   ` Victor Wagner <vitus@wagner.pp.ru>
2016-08-30 09:24                                                   ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-08-31 08:13                                                     ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-05 02:29                                                       ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-09-05 04:22                                                         ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-05 11:03                                                           ` Aleksander Alekseev <a.alekseev@postgrespro.ru>
2016-09-06 02:28                                                             ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-09-06 05:03                                                               ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-08 11:24                                                               ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-08 14:44                                                                 ` Aleksander Alekseev <a.alekseev@postgrespro.ru>
2016-09-08 14:48                                                                   ` Aleksander Alekseev <a.alekseev@postgrespro.ru>
2016-09-07 13:56                                                             ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-07 14:32                                                               ` Aleksander Alekseev <a.alekseev@postgrespro.ru>
2016-09-09 05:50                                                               ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-09-09 08:49                                                                 ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-13 18:58                                                                   ` Robert Haas <robertmhaas@gmail.com>
2016-09-25 12:01                                                                     ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-09-27 09:19                                                                       ` Victor Wagner <vitus@wagner.pp.ru>
2016-09-29 18:15                                                                         ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-09-30 08:44                                                                           ` Victor Wagner <vitus@wagner.pp.ru>
2016-10-03 00:50                                                                             ` Michael Paquier <michael.paquier@gmail.com>
2016-10-13 07:00                                                                             ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-10-13 09:53                                                                               ` Victor Wagner <vitus@wagner.pp.ru>
2016-10-19 16:04                                                                                 ` Robert Haas <robertmhaas@gmail.com>
2016-10-20 00:15                                                                                   ` Robert Haas <robertmhaas@gmail.com>
2016-10-24 10:36                                                                                     ` Thom Brown <thom@linux.com>
2016-10-24 11:03                                                                                       ` Victor Wagner <vitus@wagner.pp.ru>
2016-10-24 20:10                                                                                       ` Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
2016-10-24 11:09                                                                                     ` Victor Wagner <vitus@wagner.pp.ru>
2016-10-24 19:38                                                                                   ` Victor Wagner <vitus@wagner.pp.ru>
2016-10-19 17:44                                                                                 ` Thom Brown <thom@linux.com>
2016-08-31 08:13                                                   ` Victor Wagner <vitus@wagner.pp.ru>
2016-01-23 03:32                                     ` Thom Brown <thom@linux.com>
2016-01-23 04:23                                       ` Thom Brown <thom@linux.com>
2016-01-24 15:30                                       ` Thom Brown <thom@linux.com>
2016-01-24 15:58                                         ` Thom Brown <thom@linux.com>
2016-01-24 19:53                                           ` Victor Wagner <vitus@wagner.pp.ru>
2016-01-24 20:11                                             ` Thom Brown <thom@linux.com>
2016-01-24 20:17                                               ` Thom Brown <thom@linux.com>
2016-01-24 19:46                                         ` Victor Wagner <vitus@wagner.pp.ru>
2015-11-17 20:20                     ` Peter Eisentraut <peter_e@gmx.net>
2015-11-18 20:55                       ` Robert Haas <robertmhaas@gmail.com>
2015-11-17 20:23             ` Peter Eisentraut <peter_e@gmx.net>
2016-10-19 22:08   ` Robert Haas <robertmhaas@gmail.com>
2016-10-19 23:26     ` Peter van Hardenberg <pvh@pvh.ca>
2016-10-24 15:57       ` Robert Haas <robertmhaas@gmail.com>
2016-10-24 20:15         ` Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
2016-10-25 17:26           ` Robert Haas <robertmhaas@gmail.com>
2016-10-24 20:40         ` Alvaro Herrera <alvherre@2ndquadrant.com>
2016-10-25 08:15           ` Amit Kapila <amit.kapila16@gmail.com>
2016-10-25 17:23           ` Robert Haas <robertmhaas@gmail.com>
2016-10-26 15:19         ` Robert Haas <robertmhaas@gmail.com>
2016-10-27 13:46           ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-10-27 17:45             ` Robert Haas <robertmhaas@gmail.com>
2016-11-01 06:03               ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-01 13:24                 ` Robert Haas <robertmhaas@gmail.com>
2016-11-01 13:43                   ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-01 14:14                     ` Robert Haas <robertmhaas@gmail.com>
2016-11-01 15:21                       ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-01 16:12                         ` Robert Haas <robertmhaas@gmail.com>
2016-11-02 17:59                           ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-03 13:46                             ` Robert Haas <robertmhaas@gmail.com>
2016-11-09 15:05                               ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-10 07:41                                 ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-10 14:59                                   ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-11 06:25                                     ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-14 06:01                                     ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-14 07:56                                       ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-14 08:07                                         ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-14 11:05                                           ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-15 01:09                                             ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-15 14:36                                               ` Robert Haas <robertmhaas@gmail.com>
2016-11-17 02:00                                                 ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-17 02:57                                                   ` Robert Haas <robertmhaas@gmail.com>
2016-11-17 11:33                                                     ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-18 01:09                                                       ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-20 16:08                                                         ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-21 01:33                                                           ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-22 07:51                                                           ` Craig Ringer <craig@2ndquadrant.com>
2016-11-22 12:10                                                             ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-18 03:08                                                     ` Craig Ringer <craig@2ndquadrant.com>
2016-11-18 17:29                                                       ` Robert Haas <robertmhaas@gmail.com>
2016-11-19 01:23                                                         ` Craig Ringer <craig@2ndquadrant.com>
2016-11-21 01:48                                                         ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-21 18:43                                                           ` Robert Haas <robertmhaas@gmail.com>
2016-11-22 07:38                                                             ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-23 16:49                                                               ` Catalin Iacob <iacobcatalin@gmail.com>
2016-11-24 12:16                                                                 ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-29 17:37                                                                   ` Robert Haas <robertmhaas@gmail.com>
2016-11-29 19:19                                                                   ` Kuntal Ghosh <kuntalghosh.2007@gmail.com>
2016-11-29 20:14                                                                     ` Robert Haas <robertmhaas@gmail.com>
2016-11-29 20:14                                                                       ` Robert Haas <robertmhaas@gmail.com>
2016-11-30 01:44                                                                       ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-12-01 10:00                                                                         ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-12-02 15:24                                                                           ` Robert Haas <robertmhaas@gmail.com>
2016-12-05 04:00                                                                             ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-12-05 17:53                                                                               ` Robert Haas <robertmhaas@gmail.com>
2016-12-05 18:59                                                                                 ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-12-05 19:12                                                                                   ` Robert Haas <robertmhaas@gmail.com>
2016-12-05 17:57                                                                               ` Gavin Flower <GavinFlower@archidevsys.co.nz>
2016-11-11 14:03                                 ` Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
2016-11-14 07:38                                   ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-15 14:32                                     ` Robert Haas <robertmhaas@gmail.com>
2016-11-15 14:42                                       ` Alvaro Herrera <alvherre@2ndquadrant.com>
2016-11-15 16:58                                         ` Robert Haas <robertmhaas@gmail.com>
2016-11-15 17:53                                           ` Catalin Iacob <iacobcatalin@gmail.com>
2016-11-15 18:28                                             ` Robert Haas <robertmhaas@gmail.com>
2016-11-15 18:00                                         ` Catalin Iacob <iacobcatalin@gmail.com>
2016-11-15 18:14                                           ` Alvaro Herrera <alvherre@2ndquadrant.com>
2016-11-16 04:31                                       ` Mithun Cy <mithun.cy@enterprisedb.com>
2016-11-16 05:03                                         ` Tatsuo Ishii <ishii@sraoss.co.jp>
2016-11-17 02:29                                           ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-16 13:50                                         ` Robert Haas <robertmhaas@gmail.com>
2016-11-16 17:00                                           ` Catalin Iacob <iacobcatalin@gmail.com>
2016-11-16 18:55                                             ` Robert Haas <robertmhaas@gmail.com>
2016-11-17 02:56                                           ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-16 14:02                                         ` Kevin Grittner <kgrittn@gmail.com>
2016-11-16 15:13                                           ` Robert Haas <robertmhaas@gmail.com>
2016-11-17 02:09                                             ` Craig Ringer <craig@2ndquadrant.com>
2016-11-17 02:49                                               ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-11 07:03                               ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-14 02:02                               ` Tsunakawa, Takayuki <tsunakawa.takay@jp.fujitsu.com>
2016-11-22 20:52                                 ` Robert Haas <robertmhaas@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox